package com.dsk.cscec.listener;

import cn.hutool.core.util.ObjectUtil;
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.CbSummaryProjectImportVo;
import jodd.util.StringUtil;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;

/**
 * 成本汇总-项目汇总自定义导入
 *
 * @author cyf
 */
@Slf4j
public class CbSummaryProjectImportListener extends AnalysisEventListener<CbSummaryProjectImportVo> implements ExcelListener<CbSummaryProjectImportVo> {

//    private final CbSummaryService cbSummaryService;

    private final Long projectId;
    private final Long fileId;

    private ArrayList<CbSummaryProjectImportVo> resultList = new ArrayList<>();
    private int sort = 0;
    private int successNum = 0;
    private int failureNum = 0;
    private final StringBuilder successMsg = new StringBuilder();
    private final StringBuilder failureMsg = new StringBuilder();

    public CbSummaryProjectImportListener(Long projectId, Long fileId) {
//        this.cbSummaryService = SpringUtils.getBean(CbSummaryService.class);

        this.projectId = projectId;
        this.fileId = fileId;
    }

    @Override
    public void invoke(CbSummaryProjectImportVo importVo, AnalysisContext context) {
        //名称不能为空
        if (StringUtil.isBlank(importVo.getCbName())) {
//            failureNum++;
//            failureMsg.append("<br/>").append("第" + sort + "条数据名称为空");
//            return;
            throw new ServiceException("表格中存在'名称'列为空数据!");
        }
        //添加父级数据
        if (sort == 0) {
            CbSummaryProjectImportVo firstVo = new CbSummaryProjectImportVo();
            firstVo.setLevel(0);
            firstVo.setCbName("成本汇总");
            firstVo.setProjectId(projectId);
            firstVo.setCbProjectFileId(fileId);
            firstVo.setSort(sort);
            resultList.add(firstVo);
        }

        importVo.setProjectId(projectId);
        importVo.setCbProjectFileId(fileId);
        importVo.setSort(++sort);
        //层级处理
        if (StringUtil.isBlank(importVo.getNumber())) {//序号为空则为上一个序号不为空的子级
            //按sort倒序取number不为空的最大level
            Object[] objects = resultList.stream().sorted(Comparator.comparingInt(CbSummaryProjectImportVo::getSort).reversed())
                    .filter(vo -> StringUtil.isNotBlank(vo.getNumber())).limit(1).map(CbSummaryProjectImportVo::getLevel).toArray();
            //数据序号错误
            if (ObjectUtil.isEmpty(objects)) {
//                failureNum++;
//                failureMsg.append("<br/>").append("第" + sort + "条数据序号错误");
//                return;
                throw new ServiceException("'序号'列数据错误，无法匹配层级!");
            }

            Integer lastLevel = (Integer) objects[0];
            importVo.setLevel(lastLevel + 1);
        } else if (importVo.getNumber().matches("[\u4E00-\u9FA5]+")) {//判断是否为中文，如果是中文则为一级
            importVo.setLevel(1);
        } else if (importVo.getNumber().matches("^[0-9]*[1-9][0-9]*$")) {//判断是否为正整数
            importVo.setLevel(Integer.valueOf(importVo.getNumber()));
            //判断上一条数据level是否与当前一致或为上一级
            Optional<CbSummaryProjectImportVo> max = resultList.stream().max(Comparator.comparing(CbSummaryProjectImportVo::getSort));
            CbSummaryProjectImportVo preImportVo = null;
            if (max.isPresent()) {
                preImportVo = max.get();
            } else {
                throw new ServiceException("'序号'列数据错误，无法匹配层级!");
            }
            if (importVo.getLevel() > preImportVo.getLevel() && importVo.getLevel() != preImportVo.getLevel() + 1) {
                throw new ServiceException("'序号'列数据错误，无法匹配层级!");
            }
        }


        resultList.add(importVo);

    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {

    }

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

            @Override
            public String getAnalysis() {
                if (failureNum > 0) {
                    failureMsg.insert(0, "共 " + failureNum + " 条数据格式不正确，错误如下：");
                    throw new ServiceException(failureMsg.toString());
                } else {
                    successMsg.insert(0, "项目汇总数据已全部解析成功！共 " + getList().size() + " 条");
                }
                return successMsg.toString();
            }

            @Override
            public List<CbSummaryProjectImportVo> getList() {
                return resultList;
            }

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