package com.artfess.cqlt.manager.impl;

import com.alibaba.fastjson.JSONObject;
import com.artfess.base.enums.ReportTypeEnum;
import com.artfess.base.enums.SubjectTypeEnum;
import com.artfess.base.exception.BaseException;
import com.artfess.base.manager.impl.BaseManagerImpl;
import com.artfess.base.util.BeanUtils;
import com.artfess.cqlt.dao.QfFinanceCfBudgetMDao;
import com.artfess.cqlt.manager.QfEnterpriseInfoManager;
import com.artfess.cqlt.manager.QfFinanceCfBudgetDManager;
import com.artfess.cqlt.manager.QfFinanceCfBudgetMManager;
import com.artfess.cqlt.manager.QfFinanceCfBudgetSManager;
import com.artfess.cqlt.manager.QfFinancialStatisticalManager;
import com.artfess.cqlt.manager.QfReportLogManager;
import com.artfess.cqlt.manager.QfSubjectInternationalInfoManager;
import com.artfess.cqlt.model.QfEnterpriseInfo;
import com.artfess.cqlt.model.QfFinanceCfBudgetD;
import com.artfess.cqlt.model.QfFinanceCfBudgetM;
import com.artfess.cqlt.model.QfFinanceCfBudgetS;
import com.artfess.cqlt.model.QfFinanceCfS;
import com.artfess.cqlt.model.QfFinancePlBudgetS;
import com.artfess.cqlt.model.QfSubjectInternationalInfo;
import com.artfess.cqlt.vo.DataInfoVo;
import com.artfess.cqlt.vo.ReportVo;
import com.artfess.i18n.util.I18nUtil;
import com.artfess.poi.util.HeaderNode;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.api.client.util.Sets;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.Collectors;

/**
 * 财务--现金流量预算填报主表 服务实现类
 *
 * @author min.wu
 * @company 阿特菲斯信息技术有限公司
 * @since 2023-03-02
 */
@Slf4j
@Service
public class QfFinanceCfBudgetMManagerImpl extends BaseManagerImpl<QfFinanceCfBudgetMDao, QfFinanceCfBudgetM> implements QfFinanceCfBudgetMManager {

    @Autowired
    private QfFinanceCfBudgetDManager financeCfBudgetDManager;

    @Autowired
    private QfFinanceCfBudgetSManager financeCfBudgetSManager;

    @Autowired
    private QfSubjectInternationalInfoManager subjectInternationalInfoManager;

    @Autowired
    private QfEnterpriseInfoManager enterpriseInfoManager;

    @Autowired
    private QfFinancialStatisticalManager qfFinancialStatisticalManager;

    @Autowired
    private QfReportLogManager reportLogManager;

    @Resource(name = "bmpExecutorService")
    private ExecutorService executorService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean insertInfo(QfFinanceCfBudgetM t) {
        QueryWrapper<QfFinanceCfBudgetM> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("fill_year_", t.getFillYear());
        queryWrapper.eq("fill_month_", t.getFillMonth());
        queryWrapper.eq("report_id_", t.getReportId());
        List<QfFinanceCfBudgetM> QfFinanceCfBudgetMS = this.baseMapper.selectList(queryWrapper);
        if (!CollectionUtils.isEmpty(QfFinanceCfBudgetMS)) {
            throw new BaseException(I18nUtil.getMessage("QfOperationKpiM.repeat", LocaleContextHolder.getLocale()));
        }
        int insert = this.baseMapper.insert(t);
        if (insert > 0) {
            return true;
        }
        return false;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateInfo(QfFinanceCfBudgetM t) {
        QueryWrapper<QfFinanceCfBudgetM> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("fill_year_", t.getFillYear());
        queryWrapper.eq("fill_month_", t.getFillMonth());
        queryWrapper.eq("report_id_", t.getReportId());
        queryWrapper.ne("id_", t.getId());
        List<QfFinanceCfBudgetM> QfFinanceCfBudgetMS = this.baseMapper.selectList(queryWrapper);
        if (!CollectionUtils.isEmpty(QfFinanceCfBudgetMS)) {
            throw new BaseException(I18nUtil.getMessage("QfOperationKpiM.repeat", LocaleContextHolder.getLocale()));
        }
        int insert = this.baseMapper.updateById(t);
        if (insert > 0) {
            return true;
        }
        return false;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateStatus(QfFinanceCfBudgetM t) {
        QfFinanceCfBudgetM QfFinanceCfBudgetM = baseMapper.selectById(t.getId());
        if (null == QfFinanceCfBudgetM) {
            return false;
        }
        QfFinanceCfBudgetM.setStatus(QfFinanceCfBudgetM.getStatus() == 0 ? 1 : 0);
        int i = this.baseMapper.updateById(QfFinanceCfBudgetM);
        if (i > 0) {
            return true;
        }
        return false;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean importExcel(List<HeaderNode> list, String mainId) {
        if (CollectionUtils.isEmpty(list)) {
            return false;
        }
        QfFinanceCfBudgetM mainInfo = this.baseMapper.selectById(mainId);
        Assert.notNull(mainInfo, I18nUtil.getMessage("filldata.notExist", LocaleContextHolder.getLocale()));
        Assert.isTrue(!"1".equals(mainInfo.getStatus()),  I18nUtil.getMessage("data_operate", LocaleContextHolder.getLocale()));
        this.removeInfo(mainId);

        //获取上个月的利润信息
        Map<String, List<QfFinanceCfBudgetD>> historyMap = this.historyList(mainInfo);
        //获取财务相关国际科目
        Map<String, QfSubjectInternationalInfo> subjectMap = subjectInternationalInfoManager.getSubjectCodeMap("CF");
        //获取境外企业
        Map<String, QfEnterpriseInfo> enterpriseInfoMap = enterpriseInfoManager.getEnterpriseInfoMap(null);

        StringBuffer sb = new StringBuffer();
        List<HeaderNode> headerNodeList = list.stream().collect(Collectors.groupingBy(HeaderNode::getRow)).get(0);
        Map<Integer, String> headerMap = Maps.newHashMap();
        for (HeaderNode headerNode : headerNodeList) {
            headerMap.put(headerNode.getColumn(), headerNode.getHeaderName());
        }

        //获取科目所在行 以及科目编码信息
        Map<Integer, List<HeaderNode>> detailMap = list.stream().collect(Collectors.groupingBy(HeaderNode::getColumn));
        List<HeaderNode> subjectCodes = detailMap.get(1);
        Map<Integer, String> subjectCodeMap = Maps.newHashMap();
        Map<String, Integer> subjectCodeRowMap =Maps.newHashMap();
        for (HeaderNode headerNode : subjectCodes) {
            subjectCodeMap.put(headerNode.getRow(), headerNode.getHeaderName());
            subjectCodeRowMap.put(headerNode.getHeaderName(),headerNode.getRow());
        }
        Set<String> subjectCodeList = Sets.newHashSet();
        int maxColumn = detailMap.size();
        List<QfFinanceCfBudgetD> detailList = Lists.newArrayList();
        JSONObject totalInfo = new JSONObject();
        for (Map.Entry<Integer, List<HeaderNode>> entry : detailMap.entrySet()) {
            Integer column = entry.getKey();
            List<HeaderNode> nodes = entry.getValue();
            //获取企业编码
            String enterpriseCode = headerMap.get(column);
            List<QfFinanceCfBudgetD> historyDetailList = Lists.newArrayList();
            if(historyMap.containsKey(enterpriseCode)){
                historyDetailList = historyMap.get(enterpriseCode);
            }

            for (HeaderNode node : nodes) {
                if (0 == node.getRow()) {
                    continue;
                }
                String subjectCode = subjectCodeMap.get(node.getRow());
                subjectCodeList.add(subjectCode);
                if (node.getColumn() > 1 && node.getColumn() < maxColumn - 3 && !StringUtils.isEmpty(node.getHeaderName())) {
                    createDetail(mainId, mainInfo, subjectMap, enterpriseInfoMap, sb, subjectCodeMap, detailList, enterpriseCode, historyDetailList, node);
                }else if(node.getColumn() >= maxColumn - 3 && !StringUtils.isEmpty(node.getHeaderName())){
                    if(node.getColumn() == maxColumn - 1) {
                        totalInfo.put(subjectCode+":budgetConsolidated", node.getHeaderName());
                    }else if(node.getColumn() == maxColumn - 2) {
                        totalInfo.put(subjectCode+":budgetPosting", node.getHeaderName());
                    }else if(node.getColumn() == maxColumn - 3) {
                        totalInfo.put(subjectCode+":budgetTotal", node.getHeaderName());
                    }
                }

            }
        }
        if (sb.length() > 0) {
            throw new BaseException(sb.substring(1) + I18nUtil.getMessage("code.notExist", LocaleContextHolder.getLocale()));
        }
        List<QfFinanceCfBudgetS> totalList = getQfFinanceCfBudgetS(mainInfo, subjectMap, new ArrayList<>(subjectCodeList), totalInfo,subjectCodeRowMap);
        financeCfBudgetSManager.saveBatch(totalList);
        try {
            partitionSave(detailList);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("导入例如报表数据失败:{}", e.getMessage());
            return false;
        }

        asyncReportInfo(mainInfo, detailList, totalList);
        return true;
    }

    private void asyncReportInfo(QfFinanceCfBudgetM mainInfo, List<QfFinanceCfBudgetD> list, List<QfFinanceCfBudgetS> totalList) {
        executorService.execute(() -> {
            String msg = null;
            String reportStatus = "0";
            try {
                saveFinancialVo(mainInfo, list, totalList);
                reportStatus = "1";
            } catch (Exception e) {
                msg = e.getMessage();
                log.error("财务大屏报表实际数据生成失败:{}", e.getMessage());
            }
            reportLogManager.saveReportInfo(reportStatus, msg, ReportTypeEnum.CF_BUDGET.getType(), mainInfo.getFillYear(), mainInfo.getFillMonth());
        });
    }

    private void partitionSave(List<QfFinanceCfBudgetD> detailList) throws InterruptedException {
        if(detailList.isEmpty()) {
            return;
        }
        List<List<QfFinanceCfBudgetD>> partition = BeanUtils.partition(detailList, detailList.size()/10);
        // 创建线程池
        ExecutorService executorService = Executors.newFixedThreadPool(partition.size());
        // 声明线程计数器 记录单个任务的执行次数
        CountDownLatch countDownLatch = new CountDownLatch(partition.size());
        // 遍历处理拆分的list数据
        for (int i = 0; i < partition.size(); i++) {
            int finalI = i;
            executorService.execute(() -> {
                // 业务处理部分
                List<QfFinanceCfBudgetD> importParamDTOList = partition.get(finalI);
                financeCfBudgetDManager.saveOrUpdateBatch(importParamDTOList);
                countDownLatch.countDown();
            });
        }
        countDownLatch.await();
        //关闭线程池
        executorService.shutdown();
    }

    private void saveFinancialVo(QfFinanceCfBudgetM mainInfo, List<QfFinanceCfBudgetD> detailList, List<QfFinanceCfBudgetS> totalList) {
        QfEnterpriseInfo group = enterpriseInfoManager.getGroup();
        //获取上个月的利润信息
        Map<String, QfFinanceCfBudgetS> historyMap = this.historyTotalList(mainInfo);
        List<ReportVo> financialVoList = Lists.newArrayList();
        DataInfoVo dataInfoVo = new DataInfoVo();
        dataInfoVo.setYear(mainInfo.getFillYear());
        dataInfoVo.setMonth(mainInfo.getFillMonth());
        dataInfoVo.setQuarter(mainInfo.getFillQuarter());
        detailList.forEach(detail -> {
            ReportVo financialVo = new ReportVo();
            financialVo.setEnterpriseCode(detail.getEnterpriseCode());
            financialVo.setBudget(detail.getBudget());
            financialVo.setBudgetYtd(detail.getBudgetYtd());
            financialVo.setSubjectCode(detail.getSubjectCode());
            financialVoList.add(financialVo);
        });

        totalList.forEach(detail->{
            ReportVo financialVo = new ReportVo();
            financialVo.setEnterpriseCode(group.getCode());
            financialVo.setBudgetYtd(detail.getBudgetConsolidated());
            if(historyMap.containsKey(detail.getSubjectCode())) {
                QfFinanceCfBudgetS plS = historyMap.get(detail.getSubjectCode());
                if(null == financialVo.getBudgetYtd()) {
                    financialVo.setBudgetYtd(BigDecimal.ZERO);
                }
                if(null == plS || null == plS.getBudgetConsolidated()) {
                    financialVo.setBudget(financialVo.getBudgetYtd());
                }else {
                    financialVo.setBudget(financialVo.getBudgetYtd().subtract(historyMap.get(detail.getSubjectCode()).getBudgetConsolidated()));
                }
            }else{
                financialVo.setBudget(financialVo.getBudgetYtd());
            }
            financialVo.setSubjectCode(detail.getSubjectCode());
            financialVoList.add(financialVo);
        });

        qfFinancialStatisticalManager.saveData(financialVoList, dataInfoVo, 2);
    }

    private Map<String, QfFinanceCfBudgetS> historyTotalList(QfFinanceCfBudgetM mainInfo) {
        //获取上个月的累计销售额数据
        List<QfFinanceCfBudgetS> historyList = this.baseMapper.historyTotalList(mainInfo.getFillMonth() - 1, mainInfo.getFillYear());

        if (CollectionUtils.isEmpty(historyList)) {
            return Maps.newHashMap();
        }
        return historyList.stream().collect(Collectors.toMap(item -> item.getSubjectCode(), item -> item));
    }

    private List<QfFinanceCfBudgetS> getQfFinanceCfBudgetS(QfFinanceCfBudgetM mainInfo, Map<String, QfSubjectInternationalInfo> subjectMap,
                                                           List<String> subjectCodeList, JSONObject totalInfo,Map<String, Integer> subjectCodeRowMap) {
        List<QfFinanceCfBudgetS> totalList = Lists.newArrayList();
        subjectCodeList.forEach(subjectCode -> {
            QfFinanceCfBudgetS plS = new QfFinanceCfBudgetS();
            plS.setMainId(mainInfo.getId());
            QfSubjectInternationalInfo subjectInternationalInfo = subjectMap.get(subjectCode);
            if(null == subjectInternationalInfo) {
                return;
            }
            //处理课目
            plS.setSubjectNameEn(subjectInternationalInfo.getNameEn());
            plS.setSubjectUnit(subjectInternationalInfo.getUnit());
            plS.setSubjectName(subjectInternationalInfo.getName());
            if(totalInfo.containsKey(subjectCode+":budgetConsolidated")) {
                plS.setBudgetConsolidated(totalInfo.getBigDecimal(subjectCode+":budgetConsolidated"));
            }
            if(totalInfo.containsKey(subjectCode+":budgetPosting")) {
                plS.setBudgetPosting(totalInfo.getBigDecimal(subjectCode+":budgetPosting"));
            }
            if(totalInfo.containsKey(subjectCode+":budgetTotal")) {
                plS.setBudgetTotal(totalInfo.getBigDecimal(subjectCode+":budgetTotal"));
            }
            plS.setFillYear(mainInfo.getFillYear());
            plS.setFillMonth(mainInfo.getFillMonth());
            plS.setFillDate(mainInfo.getFillDate());
            plS.setFillQuarter(mainInfo.getFillQuarter());
            plS.setSubjectCode(subjectCode);
            plS.setSn(subjectCodeRowMap.get(subjectCode));
            totalList.add(plS);

        });
        return totalList;
    }

    private void createDetail(String mainId, QfFinanceCfBudgetM mainInfo, Map<String, QfSubjectInternationalInfo> subjectMap, Map<String, QfEnterpriseInfo> enterpriseInfoMap, StringBuffer sb, Map<Integer, String> subjectCodeMap, List<QfFinanceCfBudgetD> detailList, String enterpriseCode, List<QfFinanceCfBudgetD> historyDetailList, HeaderNode node) {
        QfFinanceCfBudgetD QfFinanceCfBudgetD = new QfFinanceCfBudgetD();
        QfFinanceCfBudgetD.setMainId(mainId);
        QfFinanceCfBudgetD.setSn(node.getRow());
        QfFinanceCfBudgetD.setColumn(node.getColumn());
        QfFinanceCfBudgetD.setFillDate(mainInfo.getFillDate());
        QfFinanceCfBudgetD.setEnterpriseCode(enterpriseCode);
        QfFinanceCfBudgetD.setSubjectCode(subjectCodeMap.get(node.getRow()));
        //处理课目
        if (!subjectMap.containsKey(QfFinanceCfBudgetD.getSubjectCode())) {
            sb.append(",");
            sb.append(QfFinanceCfBudgetD.getSubjectCode());
        } else {
            QfSubjectInternationalInfo subjectInternationalInfo = subjectMap.get(QfFinanceCfBudgetD.getSubjectCode());
            QfFinanceCfBudgetD.setSubjectNameEn(subjectInternationalInfo.getNameEn());
            QfFinanceCfBudgetD.setSubjectUnit(subjectInternationalInfo.getUnit());
            QfFinanceCfBudgetD.setSubjectName(subjectInternationalInfo.getName());
            if(!StringUtils.isEmpty(subjectInternationalInfo.getLevel())) {
                QfFinanceCfBudgetD.setSubjectLevel(Integer.parseInt(subjectInternationalInfo.getLevel()));
            }
            //利润表 数据值 需要转换正负数 正数转负数 负数转正数
            if(subjectInternationalInfo.getType().equals(SubjectTypeEnum.CBFY.getType())) {
                QfFinanceCfBudgetD.setBudgetYtd(new BigDecimal(node.getHeaderName()).multiply(new BigDecimal(-1)));
            }else{
                QfFinanceCfBudgetD.setBudgetYtd(new BigDecimal(node.getHeaderName()));
            }
        }
        //  TODO  当年实际值
        Map<String, QfFinanceCfBudgetD> historyDetailMap = historyDetailList.stream().collect(Collectors.toMap(item -> item.getSubjectCode(), item -> item));
        if(historyDetailMap.containsKey(QfFinanceCfBudgetD.getSubjectCode())) {
            QfFinanceCfBudgetD historyDetail = historyDetailMap.get(QfFinanceCfBudgetD.getSubjectCode());
            QfFinanceCfBudgetD.setBudget(QfFinanceCfBudgetD.getBudgetYtd().subtract(historyDetail.getBudgetYtd()));
        }else {
            QfFinanceCfBudgetD.setBudget(QfFinanceCfBudgetD.getBudgetYtd());
        }


        //处理企业
        if (enterpriseInfoMap.containsKey(QfFinanceCfBudgetD.getEnterpriseCode())) {
            QfEnterpriseInfo qfEnterpriseInfo = enterpriseInfoMap.get(QfFinanceCfBudgetD.getEnterpriseCode());
            QfFinanceCfBudgetD.setEnterpriseName(qfEnterpriseInfo.getName());
            QfFinanceCfBudgetD.setEnterpriseNameEn(qfEnterpriseInfo.getNameEn());
        }
        detailList.add(QfFinanceCfBudgetD);
    }

    private void removeInfo(String mainId) {
        QueryWrapper<QfFinanceCfBudgetD> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("main_id_", mainId);
        financeCfBudgetDManager.remove(queryWrapper);

        QueryWrapper<QfFinanceCfBudgetS> query = new QueryWrapper<>();
        query.eq("main_id_", mainId);
        financeCfBudgetSManager.remove(query);
    }

    private Map<String, List<QfFinanceCfBudgetD>> historyList(QfFinanceCfBudgetM QfFinanceCfBudgetM) {
        //获取上个月的累计销售额数据
        List<QfFinanceCfBudgetD> historyList = this.baseMapper.historyList(QfFinanceCfBudgetM.getFillMonth() - 1, QfFinanceCfBudgetM.getFillYear());

        if(CollectionUtils.isEmpty(historyList)) {
            return Maps.newHashMap();
        }
        return historyList.stream().collect(Collectors.groupingBy(QfFinanceCfBudgetD::getEnterpriseCode));
    }
}
