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.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.maintain.business.domain.ErpMaintainProject;
import com.maintain.business.domain.ErpMalfunctionProject;
import com.maintain.business.domain.ErpProjectType;
import com.maintain.business.domain.vo.ErpMaintainProjectImportVo;
import com.maintain.business.domain.vo.ErpMalfunctionProjectImportVo;
import com.maintain.business.domain.vo.ErpMalfunctionProjectVo;
import com.maintain.business.mapper.ErpMaintainProjectMapper;
import com.maintain.business.mapper.ErpMalfunctionProjectMapper;
import com.maintain.business.mapper.ErpProjectTypeMapper;
import com.maintain.common.enums.ProjectType;
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 ErpMalfunctionProjectImportListener extends AnalysisEventListener<ErpMalfunctionProjectImportVo> implements ExcelListener<ErpMalfunctionProjectImportVo> {

    private final ErpMalfunctionProjectMapper malfunctionProjectMapper;
    private final ErpProjectTypeMapper projectTypeMapper;

    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 ErpMalfunctionProjectImportListener(Boolean isUpdateSupport) {
        this.malfunctionProjectMapper = SpringUtils.getBean(ErpMalfunctionProjectMapper.class);
        this.projectTypeMapper = SpringUtils.getBean(ErpProjectTypeMapper.class);
        this.isUpdateSupport = isUpdateSupport;
        this.operName = LoginHelper.getUsername();
    }

    @Override
    public void invoke(ErpMalfunctionProjectImportVo projectImportVo, AnalysisContext context) {
        LambdaQueryWrapper<ErpMalfunctionProject> lqw = new LambdaQueryWrapper<>();
        lqw.eq(ErpMalfunctionProject::getMalfunctionCode, projectImportVo.getMalfunctionCode())
            .eq(ErpMalfunctionProject::getMalfunctionCode, projectImportVo.getMalfunctionCode());
        ErpMalfunctionProject malfunctionProject = malfunctionProjectMapper.selectOne(lqw);
        try {
            // 验证是否存在
            if (ObjectUtil.isNull(malfunctionProject)) {
                malfunctionProject = BeanUtil.toBean(projectImportVo, ErpMalfunctionProject.class);
                ValidatorUtils.validate(malfunctionProject);
                LambdaQueryWrapper<ErpProjectType> projectTypeLambdaQueryWrapper = Wrappers.lambdaQuery();
                projectTypeLambdaQueryWrapper.eq(ErpProjectType::getTypeName, malfunctionProject.getTypeName()).eq(ErpProjectType::getType, ProjectType.MALFUNCTION.getCode());
                ErpProjectType erpProjectType = projectTypeMapper.selectOne(projectTypeLambdaQueryWrapper);
                if (erpProjectType == null) {
                    ErpProjectType projectType = new ErpProjectType();
                    projectType.setTypeName(malfunctionProject.getTypeName());
                    projectType.setParentId(2L);
                    projectType.setAncestors("0,2");
                    projectType.setType(ProjectType.MALFUNCTION.getCode());
                    projectTypeMapper.insert(projectType);
                    malfunctionProject.setTypeId(projectType.getTypeId());
                    malfunctionProject.setTypeName(projectType.getTypeName());
                }else {
                    malfunctionProject.setTypeId(erpProjectType.getTypeId());
                    malfunctionProject.setTypeName(erpProjectType.getTypeName());
                }
                malfunctionProjectMapper.insert(malfunctionProject);
                successNum++;
                successMsg.append("<br/>").append(successNum).append("、故障项目 ").append(malfunctionProject.getMalfunctionCode()).append(" 导入成功");
            } else if (isUpdateSupport) {
                Long maintainProjectId = malfunctionProject.getId();
                malfunctionProject = BeanUtil.toBean(projectImportVo, ErpMalfunctionProject.class);
                malfunctionProject.setId(maintainProjectId);
                ValidatorUtils.validate(malfunctionProject);
                malfunctionProjectMapper.updateById(malfunctionProject);
                successNum++;
                successMsg.append("<br/>").append(successNum).append("、故障项目 ").append(malfunctionProject.getMalfunctionCode()).append(" 更新成功");
            } else {
                failureNum++;
                failureMsg.append("<br/>").append(failureNum).append("、故障项目 ").append(malfunctionProject.getMalfunctionCode()).append(" 已存在");
            }
        } catch (Exception e) {
            failureNum++;
            String msg = "<br/>" + failureNum + "、故障项目 " + malfunctionProject.getMalfunctionCode() + " 导入失败：";
            failureMsg.append(msg).append(e.getMessage());
            log.error(msg, e);
        }

    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {

    }

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

            @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<ErpMalfunctionProjectImportVo> getList() {
                return null;
            }

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