package com.dsk.cscec.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.io.file.FileNameUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.ReUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dsk.common.core.domain.PageQuery;
import com.dsk.common.core.domain.entity.SysDictData;
import com.dsk.common.core.page.TableDataInfo;
import com.dsk.common.excel.ExcelResult;
import com.dsk.common.helper.LoginHelper;
import com.dsk.common.utils.JsonUtils;
import com.dsk.common.utils.StringUtils;
import com.dsk.common.utils.poi.ExcelUtil;
import com.dsk.cscec.domain.CbCostMeasureActual;
import com.dsk.cscec.domain.CbProjectRecord;
import com.dsk.cscec.domain.DCustomer;
import com.dsk.cscec.domain.bo.CbCostMeasureActualBo;
import com.dsk.cscec.domain.bo.CbCostMeasureActualPushBo;
import com.dsk.cscec.domain.bo.CbCostMeasureActualSaveBo;
import com.dsk.cscec.domain.vo.CbCostMeasureActualVo;
import com.dsk.cscec.domain.vo.CbCostMeasuresImportVo;
import com.dsk.cscec.domain.vo.CbCostMeasuresItemVo;
import com.dsk.cscec.domain.vo.CbProjectExpenseSummaryImportVo;
import com.dsk.cscec.listener.ProjectCostMeasureImportListener;
import com.dsk.cscec.listener.ProjectCostMeasureSummaryImportListener;
import com.dsk.cscec.mapper.CbCostMeasureActualMapper;
import com.dsk.cscec.service.CbProjectRecordService;
import com.dsk.cscec.service.ICbCostMeasureActualService;
import com.dsk.cscec.service.ICbCostMeasureService;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.dsk.cscec.mapper.CbCostMeasureMapper;
import com.dsk.cscec.domain.CbCostMeasure;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

@Slf4j
@Service
public class CbCostMeasureServiceImpl extends ServiceImpl<CbCostMeasureMapper, CbCostMeasure> implements ICbCostMeasureService {


    private final String firstPattern = "[\\(（]*[一|二|三|四|五|六|七|八|九|十]+[\\)）]*";
    private final Pattern secondPattern = Pattern.compile("^\\d+(\\.\\d+)*$");
    private final Pattern pattern3 = Pattern.compile("^([1-9][0-9]*|0)$");

    @Autowired
    private CbProjectRecordService cbProjectRecordService;


    @Autowired
    private ICbCostMeasureActualService cbCostMeasureActualService;


    @SneakyThrows
    @Override
    public void importExcelData(MultipartFile file, Long projectId) {
        String name = file.getOriginalFilename();
        name = FileNameUtil.getPrefix(name);

        CbProjectRecord byId = cbProjectRecordService.getById(projectId);
        Assert.notNull(byId, "项目信息不能为空");
        Integer cbStage = byId.getCbStage();
        ProjectCostMeasureImportListener importListener = new ProjectCostMeasureImportListener(projectId, cbStage);
        EasyExcel.read(file.getInputStream(), CbCostMeasuresImportVo.class, importListener).sheet().doRead();
        ExcelResult<CbCostMeasuresImportVo> result = importListener.getExcelResult();
        String analysis = result.getAnalysis();
        List<CbCostMeasuresImportVo> list = result.getList();
        if (CollectionUtil.isEmpty(list)) {
            //解析失败
            log.debug(">>>>解析失败" + list.size());
            //todo 解析失败更新文件备注

            return;
        }
        log.debug(">>>>" + list.size());
        CbCostMeasure rootCbCostMeasure = new CbCostMeasure();
        rootCbCostMeasure.setItemContent(name);
        rootCbCostMeasure.setLevel(0);
        rootCbCostMeasure.setParentId(0L);
        rootCbCostMeasure.setProjectId(projectId);
        rootCbCostMeasure.setCbStage(cbStage);

        LambdaQueryWrapper<CbCostMeasure> tWrapper = Wrappers.lambdaQuery(rootCbCostMeasure);
        CbCostMeasure rootMeasure = this.getOne(tWrapper);
        if (ObjectUtil.isEmpty(rootMeasure)) {
            this.save(rootCbCostMeasure);
            rootCbCostMeasure.setNo(String.valueOf(rootCbCostMeasure.getId()));
            this.updateById(rootCbCostMeasure);
        }

        Long rootMeasuresId = rootCbCostMeasure.getId();
        if (CollectionUtil.isNotEmpty(list)) {
            for (CbCostMeasuresImportVo importVo : list) {
                String number = importVo.getNumber();

                CbCostMeasure cbCostMeasure = new CbCostMeasure();
                cbCostMeasure.setProjectId(projectId);
                cbCostMeasure.setCbStage(cbStage);
                //保存一级节点
                if (ReUtil.isMatch(firstPattern, number) || ReUtil.isMatch(pattern3, number)) {
                    BeanUtil.copyProperties(importVo, cbCostMeasure);
                    cbCostMeasure.setParentId(rootMeasuresId);
                    cbCostMeasure.setLevel(1);

                } else if (ReUtil.isMatch(secondPattern, number)) {
                    BeanUtil.copyProperties(importVo, cbCostMeasure);
                    // 根据no查询父级节点
                    CbCostMeasure parentCbCostMeasure = getCbCostMeasure(rootMeasuresId, number, projectId, cbStage);
                    String[] split = number.split("\\.");
                    cbCostMeasure.setLevel(split.length);
                    cbCostMeasure.setParentId(parentCbCostMeasure.getId());
                }
                String newNo = String.valueOf(rootMeasuresId).concat(".").concat(cbCostMeasure.getNo());
                cbCostMeasure.setNo(newNo);
                this.save(cbCostMeasure);
            }
        }

    }

    @Override
    public List<Map<String, Object>> listByLevel(Long projectId, int i) {

        CbProjectRecord byId = cbProjectRecordService.getById(projectId);
        Assert.notNull(byId, "项目信息不能为空");

        CbCostMeasure rootCbCostMeasure = new CbCostMeasure();
        rootCbCostMeasure.setParentId(0L);
        rootCbCostMeasure.setProjectId(projectId);
        rootCbCostMeasure.setCbStage(byId.getCbStage());

        QueryWrapper<CbCostMeasure> tWrapper = Wrappers.query(rootCbCostMeasure);
        tWrapper.select("id","item_content as itemContent");
        tWrapper.orderByAsc("id");
        List<Map<String, Object>> mapList = this.listMaps(tWrapper);

        return mapList;
    }

    @Override
    public List<CbCostMeasureActualVo> selectDataList(CbCostMeasureActualBo costMeasureActualBo) {
        List<CbCostMeasureActualVo> dataList = new ArrayList<>();

        Assert.notNull(costMeasureActualBo.getProjectId(), "项目ID不能为空");
        CbProjectRecord byId = cbProjectRecordService.getById(costMeasureActualBo.getProjectId());
        Assert.notNull(byId, "项目信息不能为空");
        costMeasureActualBo.setCbStage(byId.getCbStage());

        //查询项目某项措施费所有计划成本
        dataList = baseMapper.selectListByProjectAndNo(costMeasureActualBo);
//        if (CollectionUtil.isEmpty(dataList)) {
//            return dataList;
//        }
//        // 查询项目某项措施费某月所有实际成本
//       List<CbCostMeasureActualVo> actualVoList= cbCostMeasureActualMapper.selectDataList(costMeasureActualBo);
//        if (CollectionUtil.isEmpty(actualVoList)) {
//            return dataList;
//        }
//        for (CbCostMeasureActualVo cbCostMeasureActualVo : actualVoList) {
//
//        }

        return dataList;
    }

    @Override
    public void saveBatchCostMeasureActual(List<CbCostMeasureActualSaveBo> boList) {
        List<CbCostMeasureActual> saveList=new ArrayList<>();
        for (CbCostMeasureActualSaveBo cbCostMeasureActualSaveBo : boList) {
            CbCostMeasureActual cbCostMeasureActual =new CbCostMeasureActual();
            BeanUtil.copyProperties(cbCostMeasureActualSaveBo,cbCostMeasureActual);
            cbCostMeasureActual.setDelFlag(0);
            cbCostMeasureActual.setUpdateId(LoginHelper.getUserId());
            cbCostMeasureActual.setUpdateUser(LoginHelper.getUsername());
            saveList.add(cbCostMeasureActual);
        }
        cbCostMeasureActualService.saveOrUpdateBatch(saveList);
    }

    @Override
    public void pushCostMeasureActual(CbCostMeasureActualPushBo pushBo) {

        //todo 推送到Ipm系统


        CbCostMeasureActual cbCostMeasureActual =new CbCostMeasureActual();
        cbCostMeasureActual.setId(pushBo.getId());
        cbCostMeasureActual.setPushTime(new Date());
        cbCostMeasureActual.setPushDataJson(JsonUtils.toJsonString(pushBo));
        cbCostMeasureActualService.updateById(cbCostMeasureActual);
    }

    @SneakyThrows
    @Override
    public void importExcelSummaryData(MultipartFile file, Long projectId,Integer dataType) {
        CbProjectRecord byId = cbProjectRecordService.getById(projectId);
        Assert.notNull(byId, "项目信息不能为空");
        Integer cbStage = byId.getCbStage();
        ExcelUtil.importExcel(file.getInputStream(), CbProjectExpenseSummaryImportVo.class,new ProjectCostMeasureSummaryImportListener(projectId,cbStage,dataType));

    }


    /**
     * 根据当前序号、项目id、成本阶段查询父级信息
     *
     * @param number
     * @param projectId
     * @param cbStage
     * @return
     */
    public CbCostMeasure getCbCostMeasure(Long rootMeasuresId, String number, Long projectId, Integer cbStage) {
        String parentNo = number.substring(0, number.lastIndexOf('.'));
        parentNo = String.valueOf(rootMeasuresId).concat(".").concat(parentNo);
        CbCostMeasure rootCbCostMeasure = new CbCostMeasure();
        rootCbCostMeasure.setNo(parentNo);
        rootCbCostMeasure.setProjectId(projectId);
        rootCbCostMeasure.setCbStage(cbStage);
        LambdaQueryWrapper<CbCostMeasure> tWrapper = Wrappers.lambdaQuery(rootCbCostMeasure);
        CbCostMeasure rootMeasure = this.getOne(tWrapper);
        return rootMeasure;
    }


}
