package com.dsk.system.listener;

import cn.dev33.satoken.secure.BCrypt;
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.dsk.common.excel.ExcelListener;
import com.dsk.common.excel.ExcelResult;
import com.dsk.common.exception.ServiceException;
import com.dsk.common.helper.LoginHelper;
import com.dsk.common.utils.ValidatorUtils;
import com.dsk.common.utils.spring.SpringUtils;
import com.dsk.system.domain.SysDept;
import com.dsk.system.domain.SysRole;
import com.dsk.system.domain.SysUser;
import com.dsk.system.domain.vo.SysUserImportVo;
import com.dsk.system.service.ISysConfigService;
import com.dsk.system.service.ISysDeptService;
import com.dsk.system.service.ISysRoleService;
import com.dsk.system.service.ISysUserService;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;

/**
 * 系统用户自定义导入
 *
 * @author Lion Li
 */
@Slf4j
public class SysUserImportListener extends AnalysisEventListener<SysUserImportVo> implements ExcelListener<SysUserImportVo> {

    private final ISysUserService userService;
    private final ISysDeptService deptService;
    private final ISysRoleService roleService;

    private final String password;

    private final Boolean isUpdateSupport;

    private final String operName;
    private ArrayList<SysUserImportVo> resultList = new ArrayList<>();
    private int successNum = 0;
    private int failureNum = 0;
    private final StringBuilder successMsg = new StringBuilder();
    private final StringBuilder failureMsg = new StringBuilder();

    public SysUserImportListener(Boolean isUpdateSupport) {
        String initPassword = SpringUtils.getBean(ISysConfigService.class).selectConfigValueByKey("sys.user.initPassword");
        this.userService = SpringUtils.getBean(ISysUserService.class);
        this.deptService = SpringUtils.getBean(ISysDeptService.class);
        this.roleService = SpringUtils.getBean(ISysRoleService.class);
        this.password = BCrypt.hashpw(initPassword);
        this.isUpdateSupport = isUpdateSupport;
        this.operName = LoginHelper.getUsername();
    }

    @Override
    public void invoke(SysUserImportVo userVo, AnalysisContext context) {
        SysUser user = this.userService.selectUserByPhonenumber(userVo.getPhonenumber());
        SysDept dept = this.deptService.selectDeptByDeptName(userVo.getDeptName());
        SysRole role = this.roleService.selectRoleByRoleName(userVo.getRoleName());
        try {
            if (ObjectUtil.isNull(dept)) {
                throw new ServiceException("部门不存在");
            }
            if (ObjectUtil.isNull(role)) {
                throw new ServiceException("角色不存在");
            }
            // 验证是否存在这个用户
            if (ObjectUtil.isNull(user)) {
                user = BeanUtil.toBean(userVo, SysUser.class);
                user.setUserName(userVo.getPhonenumber());
                user.setDeptId(dept.getDeptId());
                user.setDept(dept);
                user.setRoleId(role.getRoleId());
                user.setRoleIds(new Long[]{role.getRoleId()});
                ValidatorUtils.validate(user);
                user.setCreateBy(operName);
                userService.insertUser(user);
                successNum++;
                successMsg.append("<br/>").append(successNum).append("、账号 ").append(user.getUserName()).append(" 导入成功");
            } else if (isUpdateSupport) {
                Long userId = user.getUserId();
                user = BeanUtil.toBean(userVo, SysUser.class);
                user.setUserId(userId);
                user.setUserName(userVo.getPhonenumber());
                user.setDeptId(dept.getDeptId());
                user.setDept(dept);
                user.setRoleId(role.getRoleId());
                user.setRoleIds(new Long[]{role.getRoleId()});
                ValidatorUtils.validate(user);
                userService.checkUserAllowed(user);
                userService.checkUserDataScope(user.getUserId());
                user.setUpdateBy(operName);
                userService.updateUser(user);
                successNum++;
                successMsg.append("<br/>").append(successNum).append("、账号 ").append(user.getUserName()).append(" 更新成功");
            } else {
                failureNum++;
                failureMsg.append("<br/>").append(failureNum).append("、账号 ").append(user.getUserName()).append(" 已存在");
                userVo.setFailReason("手机号已存在");
                resultList.add(userVo);
            }
        } catch (Exception e) {
            failureNum++;
            String msg = "<br/>" + failureNum + "、账号 " + userVo.getPhonenumber() + " 导入失败：";
            failureMsg.append(msg).append(e.getMessage());
            userVo.setFailReason(e.getMessage());
            resultList.add(userVo);
            log.error(msg, e);
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {

    }

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

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

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