package com.dsk.cscec.listener;

import cn.hutool.core.util.StrUtil;
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.cscec.domain.vo.CbProjectExpenseSummaryImportVo;
import lombok.extern.slf4j.Slf4j;

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

/**
 * 其他项目自定义导入
 *
 * @author Lion Li
 */
@Slf4j
public class CbProjectExpenseSummaryImportListener extends AnalysisEventListener<CbProjectExpenseSummaryImportVo> implements ExcelListener<CbProjectExpenseSummaryImportVo> {

    private final Long projectId;
    private final Integer cbStage;
    private List<CbProjectExpenseSummaryImportVo> dataList = new ArrayList<>();
    private int successNum = 0;
    private int failureNum = 0;
    private final StringBuilder successMsg = new StringBuilder();
    private final StringBuilder failureMsg = new StringBuilder();

    public CbProjectExpenseSummaryImportListener(Long projectId, Integer cbStage) {
        this.cbStage = cbStage;
        this.projectId = projectId;
    }

    @Override
    public void invoke(CbProjectExpenseSummaryImportVo importVo, AnalysisContext context) {
        Integer rowIndex = context.readRowHolder().getRowIndex();
        if (StrUtil.isEmpty(importVo.getExpenseName())) {
            failureNum++;
            failureMsg.append("<br/>" + rowIndex + "行 解析失败：清单内容不能为空");
        }
        String number = importVo.getNumber();
        if (StrUtil.isEmpty(number)) {
            failureNum++;
            failureMsg.append("<br/>" + rowIndex + "行 解析失败：序号不能为空");
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
    }

    @Override
    public ExcelResult<CbProjectExpenseSummaryImportVo> getExcelResult() {
        return new ExcelResult<CbProjectExpenseSummaryImportVo>() {
            @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<CbProjectExpenseSummaryImportVo> getList() {
                return dataList;
            }
            @Override
            public List<String> getErrorList() {
                return null;
            }
        };
    }

}
