package com.ozs.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.ozs.common.core.domain.AjaxResult;
import com.ozs.common.exception.ServiceException;
import com.ozs.common.utils.StringUtils;
import com.ozs.common.utils.bean.BeanUtils;
import com.ozs.common.utils.bean.BeanValidators;
import com.ozs.entity.BaseTerminal;
import com.ozs.entity.BaseVehicle;
import com.ozs.entity.BaseVehicleTerminal;
import com.ozs.entity.vo.BaseCameraManagementDto;
import com.ozs.entity.vo.BaseVehicleTerminalDto;
import com.ozs.entity.vo.BaseVehicleTerminalVo;
import com.ozs.entity.vo.BaseVehicleVo;
import com.ozs.mapper.BaseDeviceDynamicManagementMapper;
import com.ozs.mapper.BaseTerminalMapper;
import com.ozs.mapper.BaseVehicleMapper;
import com.ozs.mapper.BaseVehicleTerminalMapper;
import com.ozs.service.BaseVehicleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.validation.Validator;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 机车信息表 服务实现类
 * </p>
 *
 * @author ozs
 * @since 2023-04-11
 */
@Service
public class BaseVehicleServiceImpl extends ServiceImpl<BaseVehicleMapper, BaseVehicle> implements BaseVehicleService {

    @Autowired
    private BaseVehicleMapper baseVehicleMapper;
    @Autowired
    private BaseTerminalMapper baseTerminalMapper;
    @Autowired
    BaseDeviceDynamicManagementMapper baseDeviceDynamicManagementMapper;
    @Autowired
    private BaseVehicleTerminalMapper baseVehicleTerminalMapper;
    @Autowired
    protected Validator validator;

    @Override
    public IPage<BaseVehicle> vehicleList(BaseVehicleVo baseVehicle) {
        LambdaQueryWrapper<BaseVehicle> wrapper = new LambdaQueryWrapper<BaseVehicle>();
        if (!StringUtils.isEmptySunhh(baseVehicle) && !StringUtils.isEmptySunhh(baseVehicle.getVehicleName())) {
            wrapper.eq(BaseVehicle::getVehicleName, baseVehicle.getVehicleName());
        }
        if (!StringUtils.isEmptySunhh(baseVehicle) && !StringUtils.isEmptySunhh(baseVehicle.getVehicleCode())) {
            wrapper.eq(BaseVehicle::getVehicleCode, baseVehicle.getVehicleCode());
        }
        int pageNum = Integer.parseInt(baseVehicle.getPageNum().toString());
        int pageSize = Integer.parseInt(baseVehicle.getPageSize().toString());
        com.github.pagehelper.Page<BaseVehicle> page = PageHelper.startPage(pageNum, pageSize)
                .doSelectPage(() -> baseVehicleMapper.selectList(wrapper));
        com.baomidou.mybatisplus.extension.plugins.pagination.Page<BaseVehicle> pageR =
                new com.baomidou.mybatisplus.extension.plugins.pagination.Page<>(pageNum, pageSize);
        pageR.setRecords(page.getResult());
        pageR.setTotal(page.getTotal());
        return pageR;
    }

    @Override
    public AjaxResult vehicleAdd(BaseVehicle baseVehicle, String userId) {
        LambdaQueryWrapper<BaseVehicle> wrapper = new LambdaQueryWrapper<BaseVehicle>();
        if (!StringUtils.isEmptySunhh(baseVehicle) && !StringUtils.isEmptySunhh(baseVehicle.getVehicleCode())) {
            wrapper.eq(BaseVehicle::getVehicleCode, baseVehicle.getVehicleCode());
        }
        List<BaseVehicle> baseVehicles = baseVehicleMapper.selectList(wrapper);
        if (baseVehicles.size() > 0) {
            return AjaxResult.error("机车编码已存在！");
        }
        Date date = new Date();
        baseVehicle.setCreateBy(userId);
        baseVehicle.setUpdateBy(userId);
        baseVehicle.setCreateTime(date);
        baseVehicle.setUpdateTime(date);
        int insert = baseVehicleMapper.insert(baseVehicle);
        if (insert > 0) {
            return AjaxResult.success();
        } else {
            return AjaxResult.error();
        }
    }

    @Override
    public AjaxResult vehicleUpdate(BaseVehicle baseVehicle, String userId) {
        LambdaQueryWrapper<BaseVehicle> wrapper = new LambdaQueryWrapper<>();
        if (!StringUtils.isEmptySunhh(baseVehicle) && !StringUtils.isEmptySunhh(baseVehicle.getVehicleCode())) {
            wrapper.eq(BaseVehicle::getVehicleCode, baseVehicle.getVehicleCode());
        }
        List<BaseVehicle> baseVehicles = baseVehicleMapper.selectList(wrapper);
        if (baseVehicles.size() > 0) {
            return AjaxResult.error("机车编码已存在！");
        }
        baseVehicle.setUpdateBy(userId);
        baseVehicle.setUpdateTime(new Date());
        int update = baseVehicleMapper.updateById(baseVehicle);
        if (update > 0) {
            return AjaxResult.success();
        } else {
            return AjaxResult.error();
        }
    }

    @Override
    public String importBaseVehicle(List<BaseVehicle> accountManageList, boolean updateSupport, String userId) {
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (BaseVehicle baseVehicle2 : accountManageList) {
            try {
                BaseVehicle baseVehicle = new BaseVehicle();
                BeanUtils.copyProperties(baseVehicle2, baseVehicle);
                // 判断机车编码是否存在
                LambdaQueryWrapper<BaseVehicle> lw = new LambdaQueryWrapper<BaseVehicle>();
                if (!StringUtils.isEmptySunhh(baseVehicle.getVehicleCode())) {
                    lw.eq(BaseVehicle::getVehicleCode, baseVehicle.getVehicleCode());
                }
                BaseVehicle baseVehicle1 = baseVehicleMapper.selectOne(lw);
                if (StringUtils.isEmptySunhh(baseVehicle1)) {
                    BeanValidators.validateWithException(validator, baseVehicle);
                    baseVehicle.setUpdateBy(userId);
                    baseVehicle.setCreateBy(userId);
                    Date date = new Date();
                    baseVehicle.setCreateTime(date);
                    baseVehicle.setUpdateTime(date);
                    int insert = baseVehicleMapper.insert(baseVehicle);
                    successNum++;
                    successMsg.append(successNum + "、机车编码 " + baseVehicle.getVehicleCode() + " 导入成功");
                } else if (updateSupport) {
                    BeanValidators.validateWithException(validator, baseVehicle);
                    LambdaQueryWrapper<BaseVehicle> lambdaQueryWrapper = new LambdaQueryWrapper<BaseVehicle>();
                    if (!StringUtils.isEmptySunhh(baseVehicle.getVehicleCode())) {
                        lambdaQueryWrapper.eq(BaseVehicle::getVehicleCode, baseVehicle.getVehicleCode());
                    }
                    BaseVehicle baseVehicle4 = baseVehicleMapper.selectOne(lambdaQueryWrapper);
                    if (StringUtils.isEmptySunhh(baseVehicle4)) {
                        baseVehicle.setUpdateBy(userId);
                        baseVehicle.setUpdateTime(new Date());
                        baseVehicle.setId(baseVehicle4.getId());
                        baseVehicleMapper.updateById(baseVehicle);
                        successNum++;
                        successMsg.append(successNum + "、机车编码 " + baseVehicle.getVehicleCode() + " 更新成功");
                    } else {
                        failureNum++;
                        failureMsg.append(failureNum + "、机车编码 " + baseVehicle.getVehicleCode() + "不存在");
                    }
                }
            } catch (Exception e) {
                failureNum++;
                String msg = failureNum + "、机车编码 " + baseVehicle2.getVehicleCode() + " 导入失败：";
                failureMsg.append(msg);
                log.error(msg, e);
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条。");
        }
        return successMsg.toString();
    }

    @Override
    public AjaxResult vehicleDetails(BaseVehicle baseVehicle) {
        BaseVehicle baseVehicle1 = baseVehicleMapper.selectById(baseVehicle.getId());
        return AjaxResult.success(baseVehicle1);
    }

    @Override
    public List<BaseVehicle> exportBaseVehicle(BaseVehicle baseVehicle) {
        LambdaQueryWrapper<BaseVehicle> wrapper = new LambdaQueryWrapper<>();
        if (!StringUtils.isEmptySunhh(baseVehicle) && !StringUtils.isEmptySunhh(baseVehicle.getVehicleName())) {
            wrapper.eq(BaseVehicle::getVehicleName, baseVehicle.getVehicleName());
        }
        if (!StringUtils.isEmptySunhh(baseVehicle) && !StringUtils.isEmptySunhh(baseVehicle.getVehicleCode())) {
            wrapper.eq(BaseVehicle::getVehicleCode, baseVehicle.getVehicleCode());
        }
        List<BaseVehicle> baseVehicles = baseVehicleMapper.selectList(wrapper);
        return baseVehicles;
    }

    @Override
    public IPage<BaseVehicleTerminalVo> vehicleTerminal(BaseVehicleVo baseVehicleVo) {
        BaseTerminal baseTerminal = baseTerminalMapper.selectTerminal(baseVehicleVo.getVehicleCode());
        List<String> terminalCodeList = baseTerminalMapper.selectMountCode(baseVehicleVo.getVehicleCode());
        // List<String> collect = terminalCodeList.stream().map(BaseTerminal::getTerminalCode).collect(Collectors.toList());
        LambdaQueryWrapper<BaseVehicleTerminal> wrapper = new LambdaQueryWrapper<>();
        if (!StringUtils.isEmptySunhh(terminalCodeList) && terminalCodeList.size() > 0) {
            wrapper.notIn(BaseVehicleTerminal::getTerminalCode, terminalCodeList);
        }
//        List<BaseVehicleTerminal> baseVehicleTerminalList = baseVehicleTerminalMapper.selectList(wrapper);
        int pageNum = Integer.parseInt(baseVehicleVo.getPageNum().toString());
        int pageSize = Integer.parseInt(baseVehicleVo.getPageSize().toString());
        com.github.pagehelper.Page<BaseVehicleTerminal> page = PageHelper
                .startPage(pageNum, pageSize).doSelectPage(() -> baseVehicleTerminalMapper.selectList(wrapper));
        com.baomidou.mybatisplus.extension.plugins.pagination.Page<BaseVehicleTerminalVo> pageR =
                new com.baomidou.mybatisplus.extension.plugins.pagination.Page<>(pageNum, pageSize);
        if (!ObjectUtils.isEmpty(page) && page.getResult().size() > 0) {
            List<BaseVehicleTerminalVo> dto1 = page.getResult().stream().map(o -> {
                BaseVehicleTerminalVo baseVehicleTerminalVo = new BaseVehicleTerminalVo();
                BeanUtils.copyProperties(o, baseVehicleTerminalVo);
                if (baseTerminal.getTerminalCode().equals(o.getTerminalCode())) {
                    baseVehicleTerminalVo.setIsMount("2");
                } else {
                    baseVehicleTerminalVo.setIsMount("1");
                }
                return baseVehicleTerminalVo;
            }).collect(Collectors.toList());
            pageR.setRecords(dto1);
        }
        return pageR;
    }

    @Override
    public AjaxResult vehicleTerminalAdd(BaseTerminal baseTerminal1, String userId) {
        LambdaQueryWrapper<BaseTerminal> wrapper = new LambdaQueryWrapper<>();
        if (!StringUtils.isEmptySunhh(baseTerminal1) && !StringUtils.isEmptySunhh(baseTerminal1.getVehicleCode())) {
            wrapper.eq(BaseTerminal::getVehicleCode, baseTerminal1.getVehicleCode());
        }
        BaseTerminal baseTerminal = baseTerminalMapper.selectOne(wrapper);
        if (StringUtils.isEmptySunhh(baseTerminal)) {
            BaseTerminal baseTerminal2 = new BaseTerminal();
            baseTerminal2.setVehicleCode(baseTerminal1.getVehicleCode());
            baseTerminal2.setTerminalCode(baseTerminal1.getTerminalCode());
            baseTerminal2.setCreateBy(userId);
            baseTerminal2.setUpdateBy(userId);
            Date date = new Date();
            baseTerminal2.setCreateTime(date);
            baseTerminal2.setUpdateTime(date);
            int insert = baseTerminalMapper.insert(baseTerminal2);
        } else {
            baseTerminal.setUpdateBy(userId);
            baseTerminal.setUpdateTime(new Date());
            baseTerminal.setVehicleCode(baseTerminal1.getVehicleCode());
            baseTerminal.setTerminalCode(baseTerminal1.getTerminalCode());
            int updateById = baseTerminalMapper.updateById(baseTerminal);
        }
        return AjaxResult.success();
    }

    @Override
    public Boolean isMount(BaseVehicleVo baseVehicleVo) {
        LambdaQueryWrapper<BaseTerminal> wrapper = new LambdaQueryWrapper<>();
        if (!StringUtils.isEmptySunhh(baseVehicleVo) && !StringUtils.isEmptySunhh(baseVehicleVo.getVehicleCode())) {
            wrapper.eq(BaseTerminal::getVehicleCode, baseVehicleVo.getVehicleCode());
        }
        BaseTerminal baseTerminal = baseTerminalMapper.selectOne(wrapper);
        if (StringUtils.isEmptySunhh(baseTerminal)) {
            return true;
        }
        return false;
    }

    @Override
    public List<BaseVehicleTerminalDto> vehicleList() {
        List<BaseVehicleTerminalDto> dtoList = baseDeviceDynamicManagementMapper.vehicleTreelist(null);
        List<String> strings = dtoList.stream().map(BaseVehicleTerminalDto::getVehicleCode).collect(Collectors.toList());
        LambdaQueryWrapper<BaseVehicle> bw = new LambdaQueryWrapper<>();
        bw.in(BaseVehicle::getVehicleCode, strings);
        List<BaseVehicle> vehicles = baseVehicleMapper.selectList(bw);
        for (BaseVehicleTerminalDto terminalDto : dtoList) {
            for (BaseVehicle vehicle : vehicles) {
                if (terminalDto.getVehicleCode().equals(vehicle.getVehicleCode())) {
                    terminalDto.setVehicleName(vehicle.getVehicleName());
                    break;
                }
            }
        }
        return dtoList;
    }
}
