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.ErpExamineProject;
import com.maintain.business.domain.ErpMalfunctionProject;
import com.maintain.business.domain.ErpProjectType;
import com.maintain.business.domain.vo.ErpExamineProjectImportVo;
import com.maintain.business.domain.vo.ErpMalfunctionProjectImportVo;
import com.maintain.business.mapper.ErpExamineProjectMapper;
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.StringUtils;
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 ErpExamineProjectImportListener extends AnalysisEventListener<ErpExamineProjectImportVo> implements ExcelListener<ErpExamineProjectImportVo> {

    private final ErpExamineProjectMapper examineProjectMapper;
    private final ErpProjectTypeMapper typeMapper;

    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 ErpExamineProjectImportListener(Boolean isUpdateSupport) {
        this.examineProjectMapper = SpringUtils.getBean(ErpExamineProjectMapper.class);
        this.typeMapper = SpringUtils.getBean(ErpProjectTypeMapper.class);
        this.isUpdateSupport = isUpdateSupport;
        this.operName = LoginHelper.getUsername();
    }

    @Override
    public void invoke(ErpExamineProjectImportVo projectImportVo, AnalysisContext context) {
        LambdaQueryWrapper<ErpExamineProject> lqw = new LambdaQueryWrapper<>();
        lqw.eq(ErpExamineProject::getExamineCode, projectImportVo.getExamineCode())
            .eq(ErpExamineProject::getExamineName, projectImportVo.getExamineName());
        ErpExamineProject erpExamineProject = examineProjectMapper.selectOne(lqw);
        try {
            // 验证是否存在
            if (ObjectUtil.isNull(erpExamineProject)) {
                erpExamineProject = BeanUtil.toBean(projectImportVo, ErpExamineProject.class);
                ValidatorUtils.validate(erpExamineProject);
                ErpProjectType projectType = typeMapper.selectOne(
                    new LambdaQueryWrapper<ErpProjectType>().eq(ErpProjectType::getTypeName, erpExamineProject.getTypeName())
                    .eq(ErpProjectType::getType, ProjectType.EXAMINE.getCode()));
                if (null == projectType) {
                    ErpProjectType type = new ErpProjectType();
                    type.setTypeName(erpExamineProject.getTypeName());
                    type.setParentId(Long.valueOf(ProjectType.EXAMINE.getCode()));
                    type.setAncestors("0" + StringUtils.SEPARATOR + ProjectType.EXAMINE.getCode());
                    type.setType(ProjectType.EXAMINE.getCode());
                    typeMapper.insert(type);
                    erpExamineProject.setTypeId(type.getTypeId());
                    erpExamineProject.setTypeName(type.getTypeName());
                }else {
                    erpExamineProject.setTypeId(projectType.getTypeId());
                    erpExamineProject.setTypeName(projectType.getTypeName());
                }
                examineProjectMapper.insert(erpExamineProject);
                successNum++;
                successMsg.append("<br/>").append(successNum).append("、检测项目 ").append(erpExamineProject.getExamineCode()).append(" 导入成功");
            } else if (isUpdateSupport) {
                Long examineProjectId = erpExamineProject.getId();
                erpExamineProject = BeanUtil.toBean(projectImportVo, ErpExamineProject.class);
                erpExamineProject.setId(examineProjectId);
                ValidatorUtils.validate(erpExamineProject);
                examineProjectMapper.updateById(erpExamineProject);
                successNum++;
                successMsg.append("<br/>").append(successNum).append("、检测项目 ").append(erpExamineProject.getExamineCode()).append(" 更新成功");
            } else {
                failureNum++;
                failureMsg.append("<br/>").append(failureNum).append("、检测项目 ").append(erpExamineProject.getExamineCode()).append(" 已存在");
            }
        } catch (Exception e) {
            failureNum++;
            String msg = "<br/>" + failureNum + "、检测项目 " + erpExamineProject.getExamineCode() + " 导入失败：";
            failureMsg.append(msg).append(e.getMessage());
            log.error(msg, e);
        }

    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {

    }

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

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

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