package com.ozs.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
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.core.domain.entity.SysDictData;
import com.ozs.common.exception.ServiceException;
import com.ozs.common.utils.AppendUtils;
import com.ozs.common.utils.StringUtils;
import com.ozs.common.utils.bean.BeanValidators;
import com.ozs.entity.BaseRailwayManagement;
import com.ozs.entity.BaseTerminal;
import com.ozs.entity.BaseVehicle;
import com.ozs.entity.BaseVehicleTerminal;
import com.ozs.entity.vo.BaseVehicleTerminalVo;
import com.ozs.mapper.BaseTerminalMapper;
import com.ozs.mapper.BaseVehicleMapper;
import com.ozs.mapper.BaseVehicleTerminalMapper;
import com.ozs.service.BaseTerminalService;
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.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 机车车载终端信息表 服务实现类
 * </p>
 *
 * @author ozs
 * @since 2023-04-11
 */
@Service
public class BaseTerminalServiceImpl extends ServiceImpl<BaseTerminalMapper, BaseTerminal> implements BaseTerminalService {

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

    @Override
    public IPage<BaseTerminal> vehicleTerminalList(BaseVehicleTerminalVo baseVehicleTerminalleVo) {
        LambdaQueryWrapper<BaseTerminal> wrapper = new LambdaQueryWrapper<BaseTerminal>();
        if (!StringUtils.isEmptySunhh(baseVehicleTerminalleVo) && !StringUtils.isEmptySunhh(baseVehicleTerminalleVo.getTerminalCode())) {
            wrapper.like(BaseTerminal::getTerminalCode, baseVehicleTerminalleVo.getTerminalCode());
        }
        if (!StringUtils.isEmptySunhh(baseVehicleTerminalleVo) && !StringUtils.isEmptySunhh(baseVehicleTerminalleVo.getTerminalName())) {
            wrapper.like(BaseTerminal::getTerminalName, baseVehicleTerminalleVo.getTerminalName());
        }
        if (!StringUtils.isEmptySunhh(baseVehicleTerminalleVo) && !StringUtils.isEmptySunhh(baseVehicleTerminalleVo.getStatus())) {
            wrapper.eq(BaseTerminal::getStatus, baseVehicleTerminalleVo.getStatus());
        }
        wrapper.orderByDesc(BaseTerminal::getCreateTime);
        int pageNum = Integer.parseInt(baseVehicleTerminalleVo.getPageNum().toString());
        int pageSize = Integer.parseInt(baseVehicleTerminalleVo.getPageSize().toString());
        com.github.pagehelper.Page<BaseTerminal> page = PageHelper.startPage(pageNum, pageSize)
                .doSelectPage(() -> baseTerminalMapper.selectList(wrapper));
        com.baomidou.mybatisplus.extension.plugins.pagination.Page<BaseTerminal> pageR =
                new com.baomidou.mybatisplus.extension.plugins.pagination.Page<>(pageNum, pageSize);
        pageR.setRecords(page.getResult());
        pageR.setTotal(page.getTotal());
        if (!ObjectUtils.isEmpty(pageR) && !ObjectUtils.isEmpty(pageR.getRecords())) {
            List<BaseTerminal> dto1 = pageR.getRecords().stream().map(o -> {
                LambdaQueryWrapper<BaseVehicleTerminal> wrapper1 = new LambdaQueryWrapper<>();
                wrapper1.eq(BaseVehicleTerminal::getTerminalCode, o.getTerminalCode());
                List<BaseVehicleTerminal> baseVehicleTerminals = baseVehicleTerminalMapper.selectList(wrapper1);
                if (!ObjectUtils.isEmpty(baseVehicleTerminals)) {
                    for (BaseVehicleTerminal baseVehicleTerminal : baseVehicleTerminals) {
                        o.setVehicleCode(baseVehicleTerminal.getVehicleCode());
                        o.setEnd(baseVehicleTerminal.getEnds());
                    }
                }
                return o;
            }).collect(Collectors.toList());
            pageR.setRecords(dto1);
        }
        return pageR;
    }

    @Override
    public AjaxResult baseVehicleTerminalDetails(BaseVehicleTerminalVo baseVehicleTerminalVo) {
        BaseTerminal baseVehicleTerminal = baseTerminalMapper.selectById(baseVehicleTerminalVo.getId());
        return AjaxResult.success(baseVehicleTerminal);
    }

    @Override
    public AjaxResult vehicleTerminalAdd(BaseTerminal baseVehicleTerminal, String userId) {
        LambdaQueryWrapper<BaseTerminal> wrapper = new LambdaQueryWrapper<BaseTerminal>();
        if (!StringUtils.isEmptySunhh(baseVehicleTerminal) && !StringUtils.isEmptySunhh(baseVehicleTerminal.getTerminalCode())) {
            wrapper.eq(BaseTerminal::getTerminalCode, baseVehicleTerminal.getTerminalCode());
        }
        List<BaseTerminal> baseVehicles = baseTerminalMapper.selectList(wrapper);
        if (baseVehicles.size() > 0) {
            return AjaxResult.error("车载终端编码已存在！");
        }
        Date date = new Date();
        baseVehicleTerminal.setCreateBy(userId);
        baseVehicleTerminal.setUpdateBy(userId);
        baseVehicleTerminal.setCreateTime(date);
        baseVehicleTerminal.setUpdateTime(date);
        int insert = baseTerminalMapper.insert(baseVehicleTerminal);
        if (insert > 0) {
            return AjaxResult.success();
        } else {
            return AjaxResult.error();
        }
    }

    @Override
    public AjaxResult vehicleTerminalUpdate(BaseTerminal baseTerminal, String userId) {
        LambdaQueryWrapper<BaseTerminal> wrapper = new LambdaQueryWrapper<BaseTerminal>();
        if (!StringUtils.isEmptySunhh(baseTerminal) && !StringUtils.isEmptySunhh(baseTerminal.getTerminalCode())) {
            wrapper.eq(BaseTerminal::getTerminalCode, baseTerminal.getTerminalCode());
        }
        if (!StringUtils.isEmptySunhh(baseTerminal) && !StringUtils.isEmptySunhh(baseTerminal.getId())) {
            wrapper.ne(BaseTerminal::getId, baseTerminal.getId());
        }
        List<BaseTerminal> baseVehicles = baseTerminalMapper.selectList(wrapper);
        if (baseVehicles.size() > 0) {
            return AjaxResult.error("机车号已存在！");
        }
        baseTerminal.setUpdateBy(userId);
        baseTerminal.setUpdateTime(new Date());
        int update = baseTerminalMapper.updateById(baseTerminal);
        if (update > 0) {
            return AjaxResult.success();
        } else {
            return AjaxResult.error();
        }
    }

    @Override
    public String importBaseVehicleTerminal(List<BaseTerminal> accountManageList, boolean updateSupport, String userId) {
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (BaseTerminal baseVehicleTerminal : accountManageList) {
            try {
//                BaseVehicle baseVehicle = new BaseVehicle();
//                BeanUtils.copyProperties(baseVehicleTerminal, baseVehicle);
                // 判断机车号是否存在
                LambdaQueryWrapper<BaseTerminal> lw = new LambdaQueryWrapper<BaseTerminal>();
                if (!StringUtils.isEmptySunhh(baseVehicleTerminal.getTerminalCode())) {
                    lw.eq(BaseTerminal::getTerminalCode, baseVehicleTerminal.getTerminalCode());
                }
                BaseTerminal baseVehicle1 = baseTerminalMapper.selectOne(lw);
                if (StringUtils.isEmptySunhh(baseVehicle1)) {
                    BeanValidators.validateWithException(validator, baseVehicleTerminal);
                    baseVehicleTerminal.setStatus("在线".equals(baseVehicleTerminal.getStatusStr()) ? 1 : 2);
                    baseVehicleTerminal.setUpdateBy(userId);
                    baseVehicleTerminal.setCreateBy(userId);
                    Date date = new Date();
                    baseVehicleTerminal.setCreateTime(date);
                    baseVehicleTerminal.setUpdateTime(date);
                    int insert = baseTerminalMapper.insert(baseVehicleTerminal);
                    successNum++;
                    successMsg.append(successNum + "、终端编码 " + baseVehicleTerminal.getTerminalCode() + " 导入成功");
                } else if (updateSupport) {
                    BeanValidators.validateWithException(validator, baseVehicleTerminal);
                    LambdaQueryWrapper<BaseTerminal> lambdaQueryWrapper = new LambdaQueryWrapper<BaseTerminal>();
                    if (!StringUtils.isEmptySunhh(baseVehicleTerminal.getTerminalCode())) {
                        lambdaQueryWrapper.eq(BaseTerminal::getTerminalCode, baseVehicleTerminal.getTerminalCode());
                    }
                    BaseTerminal baseVehicle4 = baseTerminalMapper.selectOne(lambdaQueryWrapper);
                    if (StringUtils.isEmptySunhh(baseVehicle4)) {
                        baseVehicleTerminal.setUpdateBy(userId);
                        baseVehicleTerminal.setUpdateTime(new Date());
                        baseVehicleTerminal.setId(baseVehicle4.getId());
                        baseTerminalMapper.updateById(baseVehicleTerminal);
                        successNum++;
                        successMsg.append(successNum + "、终端编码 " + baseVehicleTerminal.getTerminalCode() + " 更新成功");
                    } else {
                        failureNum++;
                        failureMsg.append(failureNum + "、终端编码 " + baseVehicleTerminal.getTerminalCode() + "不存在");
                    }
                }
            } catch (Exception e) {
                String msg = null;
                failureNum++;
                if (ObjectUtils.isEmpty(baseVehicleTerminal)) {
                    msg = "导入的文档格式不正确";
                } else {
                    msg = failureNum + "、终端编码 " + baseVehicleTerminal.getTerminalCode() + " 导入失败：";
                }
                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 List<BaseTerminal> exportBaseVehicleTerminal(BaseTerminal baseVehicleTerminal) {
        LambdaQueryWrapper<BaseTerminal> wrapper = new LambdaQueryWrapper<BaseTerminal>();
        if (!StringUtils.isEmptySunhh(baseVehicleTerminal) && !StringUtils.isEmptySunhh(baseVehicleTerminal.getTerminalName())) {
            wrapper.eq(BaseTerminal::getTerminalName, baseVehicleTerminal.getTerminalName());
        }
        if (!StringUtils.isEmptySunhh(baseVehicleTerminal) && !StringUtils.isEmptySunhh(baseVehicleTerminal.getTerminalCode())) {
            wrapper.eq(BaseTerminal::getTerminalCode, baseVehicleTerminal.getTerminalCode());
        }
        if (!StringUtils.isEmptySunhh(baseVehicleTerminal) && !StringUtils.isEmptySunhh(baseVehicleTerminal.getStatus())) {
            wrapper.eq(BaseTerminal::getStatus, baseVehicleTerminal.getStatus());
        }
        if (baseVehicleTerminal.getIds().size() > 0) {
            wrapper.in(BaseTerminal::getId, baseVehicleTerminal.getIds());
        }
        List<BaseTerminal> baseVehicleTerminalList = baseTerminalMapper.selectList(wrapper);
        for (BaseTerminal baseVehicleTerminal1 : baseVehicleTerminalList) {
            baseVehicleTerminal1.setStatusStr(baseVehicleTerminal1.getStatus() == 1 ? "在线" : "离线");
            LambdaQueryWrapper<BaseVehicleTerminal> wrapper1 = new LambdaQueryWrapper<>();
            wrapper1.eq(BaseVehicleTerminal::getTerminalCode, baseVehicleTerminal1.getTerminalCode());
            BaseVehicleTerminal baseVehicleTerminals = baseVehicleTerminalMapper.selectOne(wrapper1);
            if (!ObjectUtils.isEmpty(baseVehicleTerminals)) {
                LambdaQueryWrapper<BaseVehicle> wrapper2 = new LambdaQueryWrapper<>();
                wrapper2.eq(BaseVehicle::getVehicleCode, baseVehicleTerminals.getVehicleCode());
                BaseVehicle baseVehicle = baseVehicleMapper.selectOne(wrapper2);
                if (!ObjectUtils.isEmpty(baseVehicle)) {
                    baseVehicleTerminal1.setVehicleCode(baseVehicle.getVehicleCode());
                }
            }
        }
        return baseVehicleTerminalList;
    }

    @Override
    public Map<String, Integer> getMessageStatisticsTerminal() {
        return baseTerminalMapper.getMessageStatisticsTerminal();
    }
}
