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.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.maintain.business.domain.ErpGroup;
import com.maintain.business.domain.vo.ErpGroupVo;
import com.maintain.business.mapper.ErpGroupMapper;
import com.maintain.common.core.domain.entity.SysDept;
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 com.maintain.system.mapper.SysDeptMapper;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

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

    private final ErpGroupMapper groupMapper;
    private final SysDeptMapper deptMapper;

    private final Boolean isUpdateSupport;

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

    public ErpGroupImportListener(Boolean isUpdateSupport) {
        this.groupMapper = SpringUtils.getBean(ErpGroupMapper.class);
        this.deptMapper = SpringUtils.getBean(SysDeptMapper.class);
        this.isUpdateSupport = isUpdateSupport;
    }

    @Override
    public void invoke(ErpGroupVo groupVo, AnalysisContext context) {
        LambdaQueryWrapper<ErpGroup> groupLambdaQueryWrapper = new LambdaQueryWrapper<>();
        groupLambdaQueryWrapper.eq(ErpGroup::getCode, groupVo.getCode()).eq(ErpGroup::getName, groupVo.getName());
        ErpGroup siteGroup = this.groupMapper.selectOne(groupLambdaQueryWrapper);
        try {
            // 验证是否存在这个班组
            if (ObjectUtil.isNull(siteGroup)) {
                siteGroup = BeanUtil.toBean(groupVo, ErpGroup.class);
                ValidatorUtils.validate(siteGroup);
                LambdaQueryWrapper<SysDept> deptLambdaQueryWrapper = new LambdaQueryWrapper<>();
                deptLambdaQueryWrapper.eq(SysDept::getDeptName, siteGroup.getDeptName());
                SysDept sysDept = deptMapper.selectOne(deptLambdaQueryWrapper);
                if (sysDept == null) {
                    SysDept dept = new SysDept();
                    dept.setParentId(100L);
                    dept.setAncestors("0,100");
                    dept.setOrderNum(1);
                    dept.setDeptName(siteGroup.getDeptName());
                    dept.setStatus("0");
                    dept.setDelFlag("0");
                    if (deptMapper.insert(dept) > 0) {
                        siteGroup.setDeptId(dept.getDeptId());
                        siteGroup.setDeptName(dept.getDeptName());
                    }
                }else {
                    siteGroup.setDeptId(sysDept.getDeptId());
                    siteGroup.setDeptName(sysDept.getDeptName());
                }
                siteGroup.setCreateDeptId(LoginHelper.getDeptId());
                groupMapper.insert(siteGroup);
                successNum++;
                successMsg.append("<br/>").append(successNum).append("、班组 ").append(siteGroup.getName()).append(" 导入成功");
            } else if (isUpdateSupport) {
                Long groupId = siteGroup.getId();
                siteGroup = BeanUtil.toBean(siteGroup, ErpGroup.class);
                siteGroup.setId(groupId);
                ValidatorUtils.validate(siteGroup);
                groupMapper.updateById(siteGroup);
                successNum++;
                successMsg.append("<br/>").append(successNum).append("、班组 ").append(siteGroup.getName()).append(" 更新成功");
            } else {
                failureNum++;
                failureMsg.append("<br/>").append(failureNum).append("、班组 ").append(siteGroup.getName()).append(" 已存在");
            }
        } catch (Exception e) {
            failureNum++;
            String msg = "<br/>" + failureNum + "、班组 " + siteGroup.getName() + " 导入失败：";
            failureMsg.append(msg).append(e.getMessage());
            log.error(msg, e);
        }

    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {

    }

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

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

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