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.BeanValidators;
import com.ozs.entity.BaseVehicleTerminal;
import com.ozs.entity.vo.BaseVehicleTerminalVo;
import com.ozs.mapper.BaseVehicleTerminalMapper;
import com.ozs.service.BaseVehicleTerminalService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

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

    @Autowired
    private BaseVehicleTerminalMapper baseVehicleTerminalMapper;
    @Autowired
    protected Validator validator;

    @Override
    public IPage<BaseVehicleTerminal> vehicleTerminalList(BaseVehicleTerminalVo baseVehicleTerminalleVo) {
        LambdaQueryWrapper<BaseVehicleTerminal> wrapper = new LambdaQueryWrapper<BaseVehicleTerminal>();
        if (!StringUtils.isEmptySunhh(baseVehicleTerminalleVo) && !StringUtils.isEmptySunhh(baseVehicleTerminalleVo.getTerminalCode())) {
            wrapper.eq(BaseVehicleTerminal::getTerminalCode, baseVehicleTerminalleVo.getTerminalCode());
        }
        if (!StringUtils.isEmptySunhh(baseVehicleTerminalleVo) && !StringUtils.isEmptySunhh(baseVehicleTerminalleVo.getTerminalName())) {
            wrapper.eq(BaseVehicleTerminal::getTerminalName, baseVehicleTerminalleVo.getTerminalName());
        }
        if (!StringUtils.isEmptySunhh(baseVehicleTerminalleVo) && !StringUtils.isEmptySunhh(baseVehicleTerminalleVo.getStatus())) {
            wrapper.eq(BaseVehicleTerminal::getStatus, baseVehicleTerminalleVo.getStatus());
        }
        int pageNum = Integer.parseInt(baseVehicleTerminalleVo.getPageNum().toString());
        int pageSize = Integer.parseInt(baseVehicleTerminalleVo.getPageSize().toString());
        com.github.pagehelper.Page<BaseVehicleTerminal> page = PageHelper.startPage(pageNum, pageSize)
                .doSelectPage(() -> baseVehicleTerminalMapper.selectList(wrapper));
        com.baomidou.mybatisplus.extension.plugins.pagination.Page<BaseVehicleTerminal> pageR =
                new com.baomidou.mybatisplus.extension.plugins.pagination.Page<>(pageNum, pageSize);
        pageR.setRecords(page.getResult());
        pageR.setTotal(page.getTotal());
        return pageR;
    }

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

    @Override
    public AjaxResult vehicleTerminalAdd(BaseVehicleTerminal baseVehicleTerminal, String userId) {
        LambdaQueryWrapper<BaseVehicleTerminal> wrapper = new LambdaQueryWrapper<BaseVehicleTerminal>();
        if (!StringUtils.isEmptySunhh(baseVehicleTerminal) && !StringUtils.isEmptySunhh(baseVehicleTerminal.getTerminalCode())) {
            wrapper.eq(BaseVehicleTerminal::getTerminalCode, baseVehicleTerminal.getTerminalCode());
        }
        List<BaseVehicleTerminal> baseVehicles = baseVehicleTerminalMapper.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 = baseVehicleTerminalMapper.insert(baseVehicleTerminal);
        if (insert > 0) {
            return AjaxResult.success();
        } else {
            return AjaxResult.error();
        }
    }

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

    @Override
    public String importBaseVehicleTerminal(List<BaseVehicleTerminal> accountManageList, boolean updateSupport, String userId) {
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (BaseVehicleTerminal baseVehicleTerminal : accountManageList) {
            try {
//                BaseVehicle baseVehicle = new BaseVehicle();
//                BeanUtils.copyProperties(baseVehicleTerminal, baseVehicle);
                // 判断机车编码是否存在
                LambdaQueryWrapper<BaseVehicleTerminal> lw = new LambdaQueryWrapper<BaseVehicleTerminal>();
                if (!StringUtils.isEmptySunhh(baseVehicleTerminal.getTerminalCode())) {
                    lw.eq(BaseVehicleTerminal::getTerminalCode, baseVehicleTerminal.getTerminalCode());
                }
                BaseVehicleTerminal baseVehicle1 = baseVehicleTerminalMapper.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 = baseVehicleTerminalMapper.insert(baseVehicleTerminal);
                    successNum++;
                    successMsg.append(successNum + "、终端编码 " + baseVehicleTerminal.getTerminalCode() + " 导入成功");
                } else if (updateSupport) {
                    BeanValidators.validateWithException(validator, baseVehicleTerminal);
                    LambdaQueryWrapper<BaseVehicleTerminal> lambdaQueryWrapper = new LambdaQueryWrapper<BaseVehicleTerminal>();
                    if (!StringUtils.isEmptySunhh(baseVehicleTerminal.getTerminalCode())) {
                        lambdaQueryWrapper.eq(BaseVehicleTerminal::getTerminalCode, baseVehicleTerminal.getTerminalCode());
                    }
                    BaseVehicleTerminal baseVehicle4 = baseVehicleTerminalMapper.selectOne(lambdaQueryWrapper);
                    if (StringUtils.isEmptySunhh(baseVehicle4)) {
                        baseVehicleTerminal.setUpdateBy(userId);
                        baseVehicleTerminal.setUpdateTime(new Date());
                        baseVehicleTerminal.setId(baseVehicle4.getId());
                        baseVehicleTerminalMapper.updateById(baseVehicleTerminal);
                        successNum++;
                        successMsg.append(successNum + "、终端编码 " + baseVehicleTerminal.getTerminalCode() + " 更新成功");
                    } else {
                        failureNum++;
                        failureMsg.append(failureNum + "、终端编码 " + baseVehicleTerminal.getTerminalCode() + "不存在");
                    }
                }
            } catch (Exception e) {
                failureNum++;
                String 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<BaseVehicleTerminal> exportBaseVehicleTerminal(BaseVehicleTerminal baseVehicleTerminal) {
        LambdaQueryWrapper<BaseVehicleTerminal> wrapper = new LambdaQueryWrapper<BaseVehicleTerminal>();
        if (!StringUtils.isEmptySunhh(baseVehicleTerminal) && !StringUtils.isEmptySunhh(baseVehicleTerminal.getTerminalName())) {
            wrapper.eq(BaseVehicleTerminal::getTerminalName, baseVehicleTerminal.getTerminalName());
        }
        if (!StringUtils.isEmptySunhh(baseVehicleTerminal) && !StringUtils.isEmptySunhh(baseVehicleTerminal.getTerminalCode())) {
            wrapper.eq(BaseVehicleTerminal::getTerminalCode, baseVehicleTerminal.getTerminalCode());
        }
        if (!StringUtils.isEmptySunhh(baseVehicleTerminal) && !StringUtils.isEmptySunhh(baseVehicleTerminal.getStatus())) {
            wrapper.eq(BaseVehicleTerminal::getStatus, baseVehicleTerminal.getStatus());
        }
        List<BaseVehicleTerminal> baseVehicleTerminalList = baseVehicleTerminalMapper.selectList(wrapper);
        for (BaseVehicleTerminal baseVehicleTerminal1 : baseVehicleTerminalList) {
            baseVehicleTerminal1.setStatusStr(baseVehicleTerminal1.getStatus() == 1 ? "在线" : "离线");
        }
        return baseVehicleTerminalList;
    }
}
