package org.dromara.business.listener;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import lombok.extern.slf4j.Slf4j;
import org.dromara.business.domain.bo.CaseImportUserBo;
import org.dromara.business.domain.vo.CaseExcelImportUserVo;
import org.dromara.business.service.ICaseImportUserService;
import org.dromara.common.core.constant.UserConstants;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.core.utils.SpringUtils;
import org.dromara.common.core.utils.ValidatorUtils;
import org.dromara.common.excel.core.ExcelListener;
import org.dromara.common.excel.core.ExcelResult;
import org.dromara.common.satoken.utils.LoginHelper;

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

/**
 * 病例用户自定义导入
 *
 * @author wuzhigang
 */
@Slf4j
public class CaseUserImportListener extends AnalysisEventListener<CaseExcelImportUserVo> implements ExcelListener<CaseExcelImportUserVo> {

    private final ICaseImportUserService caseImportUserService;
    private final List<String> phoneList;
    private final Long loginUserId;
    private final String loginIdentity;

    private List<CaseExcelImportUserVo> dataList = new ArrayList<>();
    private int successNum = 0;
    private int failureNum = 0;
    private int count = 1;
    private String userCodeStr = "H0UID" + DateUtil.format(new DateTime(), "yyyyMMddHHmmss");
    private String importBatch;
    private final StringBuilder successMsg = new StringBuilder();
    private final StringBuilder failureMsg = new StringBuilder();

    /**
     *
     * @param phoneList
     * @param importBatch
     * @param loginIdentity
     */
    public CaseUserImportListener(List<String> phoneList,String importBatch,String loginIdentity) {
        this.caseImportUserService = SpringUtils.getBean(ICaseImportUserService.class);
        this.loginUserId = LoginHelper.getUserId();
        this.loginIdentity = loginIdentity;
        this.phoneList = phoneList;
        this.importBatch = importBatch;
    }

    @Override
    public void invoke(CaseExcelImportUserVo userVo, AnalysisContext context) {
        try {
            dataList.add(userVo);

            CaseImportUserBo user = BeanUtil.toBean(userVo, CaseImportUserBo.class);

            if(phoneList.contains(userVo.getPhonenumber())){
                // 电话号码匹配，用户已存在
                user.setUserStatus(UserConstants.IMPORT_UPDATE);
            }else{
                // 用户新增
                user.setUserStatus(UserConstants.IMPORT_ADD);
            }
            ValidatorUtils.validate(user);
            // 用户编码
            user.setUserCode(userCodeStr+String.format("%05d", count));
            // 手机号作为用户账号
            user.setUserName(userVo.getPhonenumber());
            // 身份
            user.setLoginIdentity(loginIdentity);
            // 导入批次
            user.setImportBatch(importBatch);
            // 导入状态
            user.setImportStatus(UserConstants.NOT_IMPORTED);
            // 创建用户
            user.setCreateBy(loginUserId);
            caseImportUserService.insertByBo(user);
            successNum++;
            successMsg.append("<br/>").append(successNum).append("、账号 ").append(user.getPhonenumber()).append(" 导入成功");
        } catch (Exception e) {
            failureNum++;
            String msg = "<br/>" + failureNum + "、账号 " + userVo.getPhonenumber() + " 导入失败：";
            failureMsg.append(msg).append(e.getMessage());
            log.error(msg, e);
        }
        count++;
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {

    }

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

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

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