package com.ruoyi.clock.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.ruoyi.clock.domain.Agent;
import com.ruoyi.clock.domain.Employee;
import com.ruoyi.clock.domain.Shop;
import com.ruoyi.clock.domain.bo.EmployeeBo;
import com.ruoyi.clock.domain.bo.EmployeeImportBo;
import com.ruoyi.clock.enums.EmployStatusEnum;
import com.ruoyi.clock.service.IAgentService;
import com.ruoyi.clock.service.IEmployeeService;
import com.ruoyi.clock.service.IShopService;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.excel.ExcelListener;
import com.ruoyi.common.excel.ExcelResult;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.helper.LoginHelper;
import com.ruoyi.common.utils.ValidatorUtils;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.system.domain.vo.SysUserImportVo;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.system.service.ISysUserService;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

/**
 * 店员用户自定义导入
 *
 * @author pengc
 */
@Slf4j
public class EmployeeImportListener extends AnalysisEventListener<EmployeeImportBo> implements ExcelListener<EmployeeImportBo> {

    private final IEmployeeService employeeService;

    private final IAgentService agentService;

    private final IShopService shopService;

    private final String password;

    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 EmployeeImportListener(Boolean isUpdateSupport) {
        String initPassword = SpringUtils.getBean(ISysConfigService.class).selectConfigByKey("sys.user.initPassword");
        this.employeeService = SpringUtils.getBean(IEmployeeService.class);
        this.agentService = SpringUtils.getBean(IAgentService.class);
        this.shopService = SpringUtils.getBean(IShopService.class);

        this.password = BCrypt.hashpw(initPassword);
        this.isUpdateSupport = isUpdateSupport;
        this.operName = LoginHelper.getUsername();
    }

    @Override
    public void invoke(EmployeeImportBo userVo, AnalysisContext context) {

        String phonenumber = userVo.getPhonenumber();
        String agentName = userVo.getAgentName();
        String shopName = userVo.getShopName();
        Employee user = this.employeeService.selectUserByUserName(phonenumber);
        try {
            Agent agent = agentService.getAgentByName(agentName);
            if(ObjectUtil.isEmpty(agent)){
                failureNum++;
                failureMsg.append("<br/>").append(failureNum).append("、所属代理商 ").append(agentName).append(" 不存在");
                return;
            }
            Shop shop = shopService.getShopByName(shopName);
            if(ObjectUtil.isEmpty(shop)){
                failureNum++;
                failureMsg.append("<br/>").append(failureNum).append("、所属门店 ").append(shopName).append(" 不存在");
                return;
            }

            // 验证是否存在这个用户
            if (ObjectUtil.isNull(user)) {
                EmployeeBo employeeBo = new EmployeeBo();
                BeanUtil.copyProperties(userVo, employeeBo);
                employeeBo.setAgentId(agent.getAgentId());
                employeeBo.setShopId(shop.getShopId());
                employeeBo.setStatus(EmployStatusEnum.NORMAL.getCode());
                employeeBo.setPassword(password);
                employeeBo.setCreateBy(operName);
                employeeService.insertByBo(employeeBo);
                successNum++;
                successMsg.append("<br/>").append(successNum).append("、账号 ").append(user.getEmployeeName()).append(" 导入成功");
            } else {
                EmployeeBo employeeBo = new EmployeeBo();
                employeeBo.setEmployeeId(user.getEmployeeId());
                employeeBo.setAgentId(agent.getAgentId());
                employeeBo.setShopId(shop.getShopId());
                employeeBo.setStatus(EmployStatusEnum.NORMAL.getCode());
                user.setUpdateBy(operName);
                employeeService.updateByBo(employeeBo);
                successNum++;
                successMsg.append("<br/>").append(successNum).append("、账号 ").append(user.getEmployeeName()).append(" 更新成功");
            }
        } catch (Exception e) {
            failureNum++;
            String msg = "<br/>" + failureNum + "、账号 " + user.getEmployeeName() + " 导入失败：";
            failureMsg.append(msg).append(e.getMessage());
            log.error(msg, e);
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {

    }

    @Override
    public ExcelResult<EmployeeImportBo> getExcelResult() {
        return new ExcelResult<EmployeeImportBo>() {
            @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<EmployeeImportBo> getList() {
                return null;
            }

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