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.ErpGroup;
import com.maintain.business.domain.ErpPost;
import com.maintain.business.domain.ErpUser;
import com.maintain.business.domain.vo.ErpUserVo;
import com.maintain.business.mapper.ErpGroupMapper;
import com.maintain.business.mapper.ErpPostMapper;
import com.maintain.business.mapper.ErpUserMapper;
import com.maintain.common.core.domain.entity.SysDept;
import com.maintain.common.enums.IsEnableStatus;
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 ErpUserImportListener extends AnalysisEventListener<ErpUserVo> implements ExcelListener<ErpUserVo> {

    private final ErpUserMapper userMapper;
    private final SysDeptMapper deptMapper;
    private final ErpGroupMapper groupMapper;
    private final ErpPostMapper postMapper;

    private final Boolean isUpdateSupport;
    private final Integer type;

    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 ErpUserImportListener(Integer type, Boolean isUpdateSupport) {
        this.userMapper = SpringUtils.getBean(ErpUserMapper.class);
        this.deptMapper = SpringUtils.getBean(SysDeptMapper.class);
        this.groupMapper = SpringUtils.getBean(ErpGroupMapper.class);
        this.postMapper = SpringUtils.getBean(ErpPostMapper.class);
        this.isUpdateSupport = isUpdateSupport;
        this.type = type;
        this.operName = LoginHelper.getUsername();
    }

    @Override
    public void invoke(ErpUserVo userVo, AnalysisContext context) {
        LambdaQueryWrapper<ErpUser> userLambdaQueryWrapper = new LambdaQueryWrapper<>();
        userLambdaQueryWrapper.eq(ErpUser::getName, userVo.getName());
        ErpUser erpUser = this.userMapper.selectOne(userLambdaQueryWrapper);
        try {
            // 验证是否存在这个客户
            if (ObjectUtil.isNull(erpUser)) {
                erpUser = BeanUtil.toBean(userVo, ErpUser.class);
                ValidatorUtils.validate(erpUser);
                LambdaQueryWrapper<SysDept> deptLambdaQueryWrapper = new LambdaQueryWrapper<>();
                deptLambdaQueryWrapper.eq(SysDept::getDeptName, erpUser.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(erpUser.getDeptName());
                    dept.setStatus("0");
                    dept.setDelFlag("0");
                    deptMapper.insert(dept);
                    erpUser.setDeptId(dept.getDeptId());
                    erpUser.setDeptName(dept.getDeptName());
                    sysDept = dept;
                }else {
                    erpUser.setDeptId(sysDept.getDeptId());
                    erpUser.setDeptName(sysDept.getDeptName());
                }
                /* 班组不存在新增班组 */
                LambdaQueryWrapper<ErpGroup> groupLambdaQueryWrapper = new LambdaQueryWrapper<>();
                groupLambdaQueryWrapper.eq(ErpGroup::getName, erpUser.getSiteGroupName());
                ErpGroup erpGroup = groupMapper.selectOne(groupLambdaQueryWrapper);
                if (erpGroup == null) {
                    ErpGroup group = new ErpGroup();
                    group.setName(erpUser.getSiteGroupName());
                    group.setDeptId(sysDept.getDeptId());
                    group.setDeptName(sysDept.getDeptName());
                    group.setIsEnable(IsEnableStatus.YES.getCode());
                    group.setCreateDeptId(LoginHelper.getDeptId());
                    groupMapper.insert(group);
                }else {
                    erpUser.setSiteGroupId(erpGroup.getId());
                    erpUser.setDeptName(erpGroup.getName());
                }
                /* 岗位不存在新增岗位 */
                LambdaQueryWrapper<ErpPost> postLambdaQueryWrapper = new LambdaQueryWrapper<>();
                postLambdaQueryWrapper.eq(ErpPost::getName, erpUser.getPostName());
                ErpPost erpPost = postMapper.selectOne(postLambdaQueryWrapper);
                if (erpPost == null) {
                    ErpPost post = new ErpPost();
                    post.setName(erpUser.getPostName());
                    post.setType(1);
                    postMapper.insert(post);
                }else {
                    erpUser.setPostId(erpPost.getId());
                    erpUser.setPostName(erpPost.getName());
                }
                erpUser.setType(type);
                userMapper.insert(erpUser);
                successNum++;
                successMsg.append("<br/>").append(successNum).append("、维修人员 ").append(erpUser.getName()).append(" 导入成功");
            } else if (isUpdateSupport) {
                Long userId = erpUser.getId();
                erpUser = BeanUtil.toBean(userVo, ErpUser.class);
                erpUser.setId(userId);
                ValidatorUtils.validate(erpUser);
                userMapper.updateById(erpUser);
                successNum++;
                successMsg.append("<br/>").append(successNum).append("、维修人员 ").append(erpUser.getName()).append(" 更新成功");
            } else {
                failureNum++;
                failureMsg.append("<br/>").append(failureNum).append("、维修人员 ").append(erpUser.getName()).append(" 已存在");
            }
        } catch (Exception e) {
            failureNum++;
            String msg = "<br/>" + failureNum + "、维修人员 " + erpUser.getName() + " 导入失败：";
            failureMsg.append(msg).append(e.getMessage());
            log.error(msg, e);
        }

    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {

    }

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

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

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