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.ErpMaintainProject;
import com.maintain.business.domain.ErpProjectType;
import com.maintain.business.domain.vo.ErpMaintainProjectImportVo;
import com.maintain.business.domain.vo.ErpMaintainProjectVo;
import com.maintain.business.mapper.ErpMaintainProjectMapper;
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 ErpMaintainProjectImportListener extends AnalysisEventListener<ErpMaintainProjectVo> implements ExcelListener<ErpMaintainProjectVo> {

    private final ErpMaintainProjectMapper projectMapper;

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

    @Override
    public void invoke(ErpMaintainProjectVo projectImportVo, AnalysisContext context) {
        LambdaQueryWrapper<ErpMaintainProject> lqw = new LambdaQueryWrapper<>();
        lqw.eq(ErpMaintainProject::getProjectCode, projectImportVo.getProjectCode())
            .eq(ErpMaintainProject::getProjectName, projectImportVo.getProjectName());
        ErpMaintainProject maintainProject = projectMapper.selectOne(lqw);
        try {
            // 验证是否存在这个维修项目
            if (ObjectUtil.isNull(maintainProject)) {
                maintainProject = BeanUtil.toBean(projectImportVo, ErpMaintainProject.class);
                ValidatorUtils.validate(maintainProject);
                if (StringUtils.isNotEmpty(maintainProject.getTypeName())) {
                    ErpProjectType projectType = projectTypeMapper.selectOne(new LambdaQueryWrapper<ErpProjectType>().eq(ErpProjectType::getTypeName, maintainProject.getTypeName()).eq(ErpProjectType::getType, ProjectType.MAINTAIN.getCode()));
                    if (null == projectType) {
                        ErpProjectType erpProjectType = new ErpProjectType();
                        erpProjectType.setTypeName(maintainProject.getTypeName());
                        erpProjectType.setParentId(Long.valueOf(ProjectType.MAINTAIN.getCode()));
                        erpProjectType.setAncestors("0" + StringUtils.SEPARATOR + ProjectType.MAINTAIN.getCode());
                        erpProjectType.setType(ProjectType.MAINTAIN.getCode());
                        projectTypeMapper.insert(erpProjectType);
                        maintainProject.setTypeId(erpProjectType.getTypeId());
                    }else {
                        maintainProject.setTypeId(projectType.getTypeId());
                    }
                }
                projectMapper.insert(maintainProject);
                successNum++;
                successMsg.append("<br/>").append(successNum).append("、维修项目 ").append(maintainProject.getProjectName()).append(" 导入成功");
            } else if (isUpdateSupport) {
                Long maintainProjectId = maintainProject.getId();
                maintainProject = BeanUtil.toBean(projectImportVo, ErpMaintainProject.class);
                maintainProject.setId(maintainProjectId);
                ValidatorUtils.validate(maintainProject);
                projectMapper.updateById(maintainProject);
                successNum++;
                successMsg.append("<br/>").append(successNum).append("、维修项目 ").append(maintainProject.getProjectName()).append(" 更新成功");
            } else {
                failureNum++;
                failureMsg.append("<br/>").append(failureNum).append("、维修项目 ").append(maintainProject.getProjectName()).append(" 已存在");
            }
        } catch (Exception e) {
            failureNum++;
            String msg = "<br/>" + failureNum + "、维修项目 " + maintainProject.getProjectName() + " 导入失败：";
            failureMsg.append(msg).append(e.getMessage());
            log.error(msg, e);
        }

    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {

    }

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

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

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