package com.hotwj.platform.config.questionBank.listener;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.idev.excel.context.AnalysisContext;
import cn.idev.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.excel.core.ExcelListener;
import org.dromara.common.excel.core.ExcelResult;
import com.hotwj.platform.config.questionBank.domain.bo.HotQuestionBankBo;
import com.hotwj.platform.config.questionBank.domain.vo.HotQuestionBankImportVo;
import com.hotwj.platform.config.questionBank.service.IHotQuestionBankService;

import java.util.List;

@Slf4j
public class HotQuestionBankImportListener extends AnalysisEventListener<HotQuestionBankImportVo> implements ExcelListener<HotQuestionBankImportVo> {

    private final IHotQuestionBankService questionBankService;

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

    public HotQuestionBankImportListener() {
        this.questionBankService = SpringUtils.getBean(IHotQuestionBankService.class);
    }

    @Override
    public void invoke(HotQuestionBankImportVo vo, AnalysisContext context) {
        try {
            HotQuestionBankBo bo = BeanUtil.toBean(vo, HotQuestionBankBo.class);
            questionBankService.insertByBo(bo);
            successNum++;
            successMsg.append("<br/>").append(successNum).append("、题目 ").append(ObjectUtil.defaultIfNull(vo.getQuestionDesc(), "")).append(" 导入成功");
        } catch (Exception e) {
            failureNum++;
            String msg = "<br/>" + failureNum + "、题目 导入失败：";
            failureMsg.append(msg).append(e.getMessage());
            log.error(msg, e);
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
    }

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

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

