package org.dromara.ygpassport.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 lombok.extern.slf4j.Slf4j;
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 org.dromara.ygpassport.domain.bo.ResearchBo;
import org.dromara.ygpassport.domain.vo.ResearchVo;
import org.dromara.ygpassport.service.IResearchService;

import java.util.List;

/**
 描述：单表导入监听
 使用：目前只支持单表导入，可参考，项目中相关接口有使用该监听器
 **/
@Slf4j
public class ResearchImportListener extends AnalysisEventListener<ResearchVo> implements ExcelListener<ResearchVo> {

    private final IResearchService researchService;

    private final Boolean isUpdateSupport;

    private final Long operUserId;

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

    public ResearchImportListener(Boolean isUpdateSupport) {
        this.researchService = SpringUtils.getBean(IResearchService.class);
        this.isUpdateSupport = isUpdateSupport;
        this.operUserId = LoginHelper.getUserId();
    }


    @Override
    public void invoke(ResearchVo researchVo, AnalysisContext analysisContext) {
        ResearchVo researchList = this.researchService.queryById(researchVo.getId());

        try {
            // 验证是否存在这条数据
            if (ObjectUtil.isNull(researchList)) {
                ResearchBo researchInfo = BeanUtil.toBean(researchVo, ResearchBo.class);
                ValidatorUtils.validate(researchInfo);
                researchInfo.setCreateBy(operUserId);
                researchService.insertByBo(researchInfo);
                successNum++;
                successMsg.append("<br/>").append(successNum).append("、科研信息 ").append(researchList.getId()).append(" 导入成功");
            } else if (isUpdateSupport) {
                Long stuId = researchList.getId();
                ResearchBo researchInfo = BeanUtil.toBean(researchVo, ResearchBo.class);
                researchInfo.setId(stuId);
                researchService.updateByBo(researchInfo);
                successNum++;
                successMsg.append("<br/>").append(successNum).append("、科研信息 ").append(researchList.getId()).append(" 更新成功");
            } else {
                failureNum++;
                failureMsg.append("<br/>").append(failureNum).append("、科研信息 ").append(researchList.getId()).append(" 已存在");
            }
        } catch (Exception e) {
            failureNum++;
            String msg = "<br/>" + failureNum + "、科研信息 " + researchList.getId() + " 导入失败：";
            failureMsg.append(msg).append(e.getMessage());
            log.error(msg, e);
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }

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

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