package com.dsk.cscec.listener;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.ReUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.read.metadata.holder.ReadSheetHolder;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.dsk.common.excel.ExcelListener;
import com.dsk.common.excel.ExcelResult;
import com.dsk.common.exception.ServiceException;
import com.dsk.common.utils.spring.SpringUtils;
import com.dsk.cscec.domain.CbCostMeasure;
import com.dsk.cscec.domain.vo.CbCostMeasuresImportVo;
import com.dsk.cscec.service.impl.CbCostMeasureServiceImpl;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 系统用户自定义导入
 *
 * @author Lion Li
 */
@Slf4j
public class ProjectCostMeasureImportListener extends AnalysisEventListener<CbCostMeasuresImportVo> implements ExcelListener<CbCostMeasuresImportVo> {

    private final CbCostMeasureServiceImpl cbCostMeasureService;
    private final Long projectId;

    private List<CbCostMeasuresImportVo> dataList = new ArrayList<>();

    private List<String> errList = new ArrayList<>();

//    private final String operName;

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

    public ProjectCostMeasureImportListener(Long projectId) {
        this.cbCostMeasureService = SpringUtils.getBean(CbCostMeasureServiceImpl.class);
        this.projectId = projectId;
//        this.operName = LoginHelper.getUsername();
    }

    @Override
    public void invoke(CbCostMeasuresImportVo importVo, AnalysisContext context) {
        Integer rowIndex = context.readRowHolder().getRowIndex();

        if (StrUtil.isEmpty(importVo.getItemContent())) {
            failureNum++;
            failureMsg.append("<br/>" + rowIndex + "行 解析失败：清单内容不能为空");
            errList.add(failureMsg.toString());
            return;
        }
        String number = importVo.getNumber();
        if (StrUtil.isEmpty(number)) {
            failureNum++;
            failureMsg.append("<br/>" + rowIndex + "行 解析失败：序号不能为空");
            errList.add(failureMsg.toString());
        }

        Boolean numberMatch = false;
        String regex = "[\\(（]*[一|二|三|四|五|六|七|八|九|十]+[\\)）]*";
        Pattern pattern = Pattern.compile("^\\d+(\\.\\d+)*$");
        Pattern pattern3 = Pattern.compile("^([1-9][0-9]*|0)$");

        if (ReUtil.isMatch(regex, number) || ReUtil.isMatch(pattern, number)||ReUtil.isMatch(pattern3, number)) {
            numberMatch = true;
        } else {
            failureNum++;
            failureMsg.append("<br/>" + rowIndex + "行 解析失败：序号格式错误");
            errList.add(failureMsg.toString());
        }



        if(numberMatch){
            if (ReUtil.isMatch(regex, number)){
                String replace = number.replaceAll("[\\\\(（]|[\\\\)）]", "");
                int no = Convert.chineseToNumber(replace);
                importVo.setNo(String.valueOf(no));
            }else{
                importVo.setNo(importVo.getNumber());
            }
            dataList.add(importVo);
        }

//        JSONConfig jsonConfig=new JSONConfig();
//        jsonConfig.setIgnoreNullValue(false);
//        System.out.println(JSONUtil.toJsonStr(importVo,jsonConfig));
//
//
//        Integer parentId=null;
//
        //保存sheet为一级节点

//        ReadSheetHolder readSheetHolder = context.readSheetHolder();
//        CbCostMeasure rootCbCostMeasure=new CbCostMeasure();
//        rootCbCostMeasure.setItemContent(readSheetHolder.getSheetName());
//        rootCbCostMeasure.setLevel(0);
//        rootCbCostMeasure.setCbProjectId(projectId);
//        rootCbCostMeasure.setCbStage(cbStage);
//        LambdaQueryWrapper<CbCostMeasure> tWrapper = Wrappers.lambdaQuery(rootCbCostMeasure);
//        CbCostMeasure rootMeasure = cbCostMeasureService.getOne(tWrapper);
//        if(ObjectUtil.isEmpty(rootMeasure)){
//            cbCostMeasureService.save(rootCbCostMeasure);
//        }

//        //保存下级节点
//        String itemContent = importVo.getItemContent();
//        String number = importVo.getNumber();
//
//
//        //判断是否二级节点
//        String regex = "[\\(（][一|二|三|四|五|六|七|八|九|十]+[\\)）]";
//        if(StrUtil.isNotEmpty(itemContent)&& ReUtil.isMatch(regex,itemContent)&&StrUtil.isEmpty(importVo.getTaxType())){
//            CbCostMeasure firstCbCostMeasure=new CbCostMeasure();
//            firstCbCostMeasure.setItemContent(itemContent);
//            firstCbCostMeasure.setLevel(1);
//            firstCbCostMeasure.setProjectId(projectId);
//            firstCbCostMeasure.setCbStage(cbStage);
//            LambdaQueryWrapper<CbCostMeasure> firstWrapper = Wrappers.lambdaQuery(firstCbCostMeasure);
//            CbCostMeasure firstMeasure = cbCostMeasureService.getOne(firstWrapper);
//            if(ObjectUtil.isEmpty(firstMeasure)){
//                cbCostMeasureService.save(firstMeasure);
//                parentId=rootCbCostMeasure.getId();
//            }
//        }

//        cbCostMeasureService.save();


//        SysUser user = this.userService.selectUserByUserName(userVo.getUserName());
//        try {
//            // 验证是否存在这个用户
//            if (ObjectUtil.isNull(user)) {
//                user = BeanUtil.toBean(userVo, SysUser.class);
//                ValidatorUtils.validate(user);
//                user.setPassword(password);
//                user.setCreateBy(operName);
//                userService.insertUser(user);
//                successNum++;
//                successMsg.append("<br/>").append(successNum).append("、账号 ").append(user.getUserName()).append(" 导入成功");
//            } else if (isUpdateSupport) {
//                Long userId = user.getUserId();
//                user = BeanUtil.toBean(userVo, SysUser.class);
//                user.setUserId(userId);
//                ValidatorUtils.validate(user);
//                userService.checkUserAllowed(user);
//                userService.checkUserDataScope(user.getUserId());
//                user.setUpdateBy(operName);
//                userService.updateUser(user);
//                successNum++;
//                successMsg.append("<br/>").append(successNum).append("、账号 ").append(user.getUserName()).append(" 更新成功");
//            } else {
//                failureNum++;
//                failureMsg.append("<br/>").append(failureNum).append("、账号 ").append(user.getUserName()).append(" 已存在");
//            }
//        } catch (Exception e) {
//            failureNum++;
//            String msg = "<br/>" + failureNum + "、账号 " + user.getUserName() + " 导入失败：";
//            failureMsg.append(msg).append(e.getMessage());
//            log.error(msg, e);
//        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {

    }

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

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

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

}
