package com.maintain.business.listener;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.maintain.business.domain.ErpCar;
import com.maintain.business.domain.ErpClient;
import com.maintain.business.domain.ErpVehicleModel;
import com.maintain.business.domain.vo.ErpCarVo;
import com.maintain.business.mapper.ErpCarMapper;
import com.maintain.business.mapper.ErpClientMapper;
import com.maintain.business.mapper.ErpVehicleModelMapper;
import com.maintain.common.excel.ExcelListener;
import com.maintain.common.excel.ExcelResult;
import com.maintain.common.exception.ServiceException;
import com.maintain.common.helper.LoginHelper;
import com.maintain.common.utils.ValidatorUtils;
import com.maintain.common.utils.spring.SpringUtils;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

/**
 * 车辆自定义导入
 *
 * @author liushuai
 */
@Slf4j
public class ErpCarImportListener extends AnalysisEventListener<ErpCarVo> implements ExcelListener<ErpCarVo> {

    private final ErpCarMapper carMapper;

    private final ErpClientMapper clientMapper;

    private final ErpVehicleModelMapper vehicleModelMapper;

    private final Boolean isUpdateSupport;

    private final String operName;

    private int successNum = 0;
    private int failureNum = 0;
    private final StringBuilder successMsg = new StringBuilder();
    private final StringBuilder failureMsg = new StringBuilder();

    public ErpCarImportListener(Boolean isUpdateSupport) {
        this.carMapper = SpringUtils.getBean(ErpCarMapper.class);
        this.clientMapper = SpringUtils.getBean(ErpClientMapper.class);
        this.vehicleModelMapper = SpringUtils.getBean(ErpVehicleModelMapper.class);
        this.isUpdateSupport = isUpdateSupport;
        this.operName = LoginHelper.getUsername();
    }

    @Override
    public void invoke(ErpCarVo carImportVo, AnalysisContext context) {
        LambdaQueryWrapper<ErpCar> carLambdaQueryWrapper = new LambdaQueryWrapper<>();
        carLambdaQueryWrapper.eq(ErpCar::getPlateNumber, carImportVo.getPlateNumber());
        ErpCar erpCar = carMapper.selectOne(carLambdaQueryWrapper);
        try {
            // 验证是否存在这个车辆
            if (ObjectUtil.isNull(erpCar)) {
                erpCar = BeanUtil.toBean(carImportVo, ErpCar.class);
                ValidatorUtils.validate(erpCar);
                /*
                  客户是否存在
                 */
                ErpClient erpClient = clientMapper.selectOne(new LambdaQueryWrapper<ErpClient>().eq(ErpClient::getName, erpCar.getClientName()));
                if (null == erpClient) {
                    ErpClient client = new ErpClient();
                    client.setName(erpCar.getClientName());
                    clientMapper.insert(client);
                    erpCar.setClientId(client.getId());
                    erpCar.setClientName(client.getName());
                }else {
                    erpCar.setClientId(erpClient.getId());
                    erpCar.setClientName(erpClient.getName());
                    erpCar.setPhone(erpClient.getPhone());
                }
                /*
                  车型是否存在
                 */
                ErpVehicleModel vehicleModel = vehicleModelMapper.selectOne(new LambdaQueryWrapper<ErpVehicleModel>().eq(ErpVehicleModel::getCarModel, carImportVo.getCarModel()));
                if (null == vehicleModel) {
                    ErpVehicleModel model = new ErpVehicleModel();
                    model.setCarModel(carImportVo.getCarModel());
                    vehicleModelMapper.insert(model);
                    erpCar.setCarTypeId(model.getId());
                }else {
                    erpCar.setCarTypeId(vehicleModel.getId());
                }
                carMapper.insert(erpCar);
                successNum++;
                successMsg.append("<br/>").append(successNum).append("、车辆 ").append(erpCar.getPlateNumber()).append(" 导入成功");
            } else if (isUpdateSupport) {
                Long carId = erpCar.getId();
                erpCar = BeanUtil.toBean(carImportVo, ErpCar.class);
                erpCar.setId(carId);
                ValidatorUtils.validate(erpCar);
                carMapper.updateById(erpCar);
                successNum++;
                successMsg.append("<br/>").append(successNum).append("、车辆 ").append(erpCar.getPlateNumber()).append(" 更新成功");
            } else {
                failureNum++;
                failureMsg.append("<br/>").append(failureNum).append("、车辆 ").append(erpCar.getPlateNumber()).append(" 已存在");
            }
        } catch (Exception e) {
            failureNum++;
            String msg = "<br/>" + failureNum + "、车辆 " + erpCar.getPlateNumber() + " 导入失败：";
            failureMsg.append(msg).append(e.getMessage());
            log.error(msg, e);
        }

    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {

    }

    @Override
    public ExcelResult<ErpCarVo> getExcelResult() {
        return new ExcelResult<ErpCarVo>() {

            @Override
            public String getAnalysis() {
                if (failureNum > 0) {
                    failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
                    throw new ServiceException(failureMsg.toString());
                } else {
                    successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
                }
                return successMsg.toString();
            }

            @Override
            public List<ErpCarVo> getList() {
                return null;
            }

            @Override
            public List<String> getErrorList() {
                return null;
            }
        };
    }
}
