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.QfFinanceBsBudgetMDao;
import com.artfess.cqlt.manager.QfEnterpriseInfoManager;
import com.artfess.cqlt.manager.QfFinanceBsBudgetDManager;
import com.artfess.cqlt.manager.QfFinanceBsBudgetMManager;
import com.artfess.cqlt.manager.QfFinanceBsBudgetSManager;
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.QfFinanceBsBudgetD;
import com.artfess.cqlt.model.QfFinanceBsBudgetM;
import com.artfess.cqlt.model.QfFinanceBsBudgetS;
import com.artfess.cqlt.model.QfFinanceBsM;
import com.artfess.cqlt.model.QfFinanceBsS;
import com.artfess.cqlt.model.QfFinanceCfBudgetS;
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 QfFinanceBsBudgetMManagerImpl extends BaseManagerImpl<QfFinanceBsBudgetMDao, QfFinanceBsBudgetM> implements QfFinanceBsBudgetMManager {

    @Autowired
    private QfFinanceBsBudgetDManager financeBsBudgetDManager;

    @Autowired
    private QfFinanceBsBudgetSManager financeBsBudgetSManager;

    @Autowired
    private QfSubjectInternationalInfoManager subjectInternationalInfoManager;

    @Autowired
    private QfEnterpriseInfoManager enterpriseInfoManager;

    @Autowired
    private QfFinancialStatisticalManager qfFinancialStatisticalManager;

    @Resource(name = "bmpExecutorService")
    private ExecutorService executorService;

    @Autowired
    private QfReportLogManager reportLogManager;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean insertInfo(QfFinanceBsBudgetM t) {
        QueryWrapper<QfFinanceBsBudgetM> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("fill_year_", t.getFillYear());
        queryWrapper.eq("fill_month_", t.getFillMonth());
        queryWrapper.eq("report_id_", t.getReportId());
        List<QfFinanceBsBudgetM> QfFinanceBsBudgetMS = this.baseMapper.selectList(queryWrapper);
        if (!CollectionUtils.isEmpty(QfFinanceBsBudgetMS)) {
            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(QfFinanceBsBudgetM t) {
        QueryWrapper<QfFinanceBsBudgetM> 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<QfFinanceBsBudgetM> QfFinanceBsBudgetMS = this.baseMapper.selectList(queryWrapper);
        if (!CollectionUtils.isEmpty(QfFinanceBsBudgetMS)) {
            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(QfFinanceBsBudgetM t) {
        QfFinanceBsBudgetM QfFinanceBsBudgetM = baseMapper.selectById(t.getId());
        if (null == QfFinanceBsBudgetM) {
            return false;
        }
        QfFinanceBsBudgetM.setStatus(QfFinanceBsBudgetM.getStatus() == 0 ? 1 : 0);
        int i = this.baseMapper.updateById(QfFinanceBsBudgetM);
        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;
        }
        QfFinanceBsBudgetM 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<QfFinanceBsBudgetD>> historyMap = this.historyList(mainInfo);
        //获取财务相关国际科目
        Map<String, QfSubjectInternationalInfo> subjectMap = subjectInternationalInfoManager.getSubjectCodeMap("BS");
        //获取境外企业
        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();
        for (HeaderNode headerNode : subjectCodes) {
            subjectCodeMap.put(headerNode.getRow(), headerNode.getHeaderName());
        }
        Set<String> subjectCodeList = Sets.newHashSet();
        int maxColumn = detailMap.size();
        List<QfFinanceBsBudgetD> 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<QfFinanceBsBudgetD> 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) {
            //todo
//            throw new BaseException(sb.substring(1) + I18nUtil.getMessage("code.notExist", LocaleContextHolder.getLocale()));
        }
        List<QfFinanceBsBudgetS> totalList = getQfFinanceBsBudgetS(mainInfo, subjectMap, new ArrayList<>(subjectCodeList), totalInfo);
        financeBsBudgetSManager.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(QfFinanceBsBudgetM budgetM, List<QfFinanceBsBudgetD> list, List<QfFinanceBsBudgetS> totalList) {
        executorService.execute(() -> {
            String msg = null;
            String reportStatus = "0";
            try {
                saveFinancialVo(budgetM, list, totalList);
                reportStatus = "1";
            } catch (Exception e) {
                msg = e.getMessage();
                log.error("财务大屏报表实际数据生成失败:{}", e.getMessage());
            }
            reportLogManager.saveReportInfo(reportStatus, msg, ReportTypeEnum.BS_BUDGET.getType(), budgetM.getFillYear(), budgetM.getFillMonth());
        });
    }

    private void partitionSave(List<QfFinanceBsBudgetD> detailList) throws InterruptedException {
        List<List<QfFinanceBsBudgetD>> 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<QfFinanceBsBudgetD> importParamDTOList = partition.get(finalI);
                financeBsBudgetDManager.saveOrUpdateBatch(importParamDTOList);
                countDownLatch.countDown();
            });
        }
        countDownLatch.await();
        //关闭线程池
        executorService.shutdown();
    }

    private void saveFinancialVo(QfFinanceBsBudgetM mainInfo, List<QfFinanceBsBudgetD> detailList, List<QfFinanceBsBudgetS> totalList) {
        QfEnterpriseInfo group = enterpriseInfoManager.getGroup();
        //获取上个月的利润信息
        Map<String, QfFinanceBsBudgetS> 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())) {
                QfFinanceBsBudgetS 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 List<QfFinanceBsBudgetS> getQfFinanceBsBudgetS(QfFinanceBsBudgetM mainInfo, Map<String, QfSubjectInternationalInfo> subjectMap, List<String> subjectCodeList, JSONObject totalInfo) {
        List<QfFinanceBsBudgetS> totalList = Lists.newArrayList();
        subjectCodeList.forEach(subjectCode -> {
            QfFinanceBsBudgetS plS = new QfFinanceBsBudgetS();
            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);
            totalList.add(plS);

        });
        return totalList;
    }

    private void createDetail(String mainId, QfFinanceBsBudgetM mainInfo,
                              Map<String, QfSubjectInternationalInfo> subjectMap,
                              Map<String, QfEnterpriseInfo> enterpriseInfoMap,
                              StringBuffer sb,
                              Map<Integer, String> subjectCodeMap,
                              List<QfFinanceBsBudgetD> detailList,
                              String enterpriseCode,
                              List<QfFinanceBsBudgetD> historyDetailList,
                              HeaderNode node) {
        try {
            QfFinanceBsBudgetD qfFinanceBsBudgetD = new QfFinanceBsBudgetD();
            qfFinanceBsBudgetD.setMainId(mainId);
            qfFinanceBsBudgetD.setSn(node.getRow());
            qfFinanceBsBudgetD.setColumn(node.getColumn());
            qfFinanceBsBudgetD.setFillDate(mainInfo.getFillDate());
            qfFinanceBsBudgetD.setEnterpriseCode(enterpriseCode);
            qfFinanceBsBudgetD.setSubjectCode(subjectCodeMap.get(node.getRow()));
            //处理课目 todo
            if (!subjectMap.containsKey(qfFinanceBsBudgetD.getSubjectCode())) {
                sb.append(",");
                sb.append(qfFinanceBsBudgetD.getSubjectCode());
                return;
            } else {
                QfSubjectInternationalInfo subjectInternationalInfo = subjectMap.get(qfFinanceBsBudgetD.getSubjectCode());
                qfFinanceBsBudgetD.setSubjectNameEn(subjectInternationalInfo.getNameEn());
                qfFinanceBsBudgetD.setSubjectUnit(subjectInternationalInfo.getUnit());
                qfFinanceBsBudgetD.setSubjectName(subjectInternationalInfo.getName());
                if (!StringUtils.isEmpty(subjectInternationalInfo.getLevel())) {
                    qfFinanceBsBudgetD.setSubjectLevel(Integer.parseInt(subjectInternationalInfo.getLevel()));
                }
                //利润表 数据值 需要转换正负数 正数转负数 负数转正数
                if (subjectInternationalInfo.getType().equals(SubjectTypeEnum.CBFY.getType())) {
                    qfFinanceBsBudgetD.setBudgetYtd(new BigDecimal(node.getHeaderName()).multiply(new BigDecimal(-1)));
                } else {
                    qfFinanceBsBudgetD.setBudgetYtd(new BigDecimal(node.getHeaderName()));
                }
            }

            // TODO 当年实际值
            Map<String, QfFinanceBsBudgetD> historyDetailMap = historyDetailList.stream().collect(Collectors.toMap(item -> item.getSubjectCode(), item -> item));
            if (historyDetailMap.containsKey(qfFinanceBsBudgetD.getSubjectCode())) {
                QfFinanceBsBudgetD historyDetail = historyDetailMap.get(qfFinanceBsBudgetD.getSubjectCode());
                qfFinanceBsBudgetD.setBudget(qfFinanceBsBudgetD.getBudgetYtd().subtract(historyDetail.getBudgetYtd()));
            } else {
                qfFinanceBsBudgetD.setBudget(qfFinanceBsBudgetD.getBudgetYtd());
            }

            //处理企业
            if (enterpriseInfoMap.containsKey(qfFinanceBsBudgetD.getEnterpriseCode())) {
                QfEnterpriseInfo qfEnterpriseInfo = enterpriseInfoMap.get(qfFinanceBsBudgetD.getEnterpriseCode());
                qfFinanceBsBudgetD.setEnterpriseName(qfEnterpriseInfo.getName());
                qfFinanceBsBudgetD.setEnterpriseNameEn(qfEnterpriseInfo.getNameEn());
            }
            detailList.add(qfFinanceBsBudgetD);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void removeInfo(String mainId) {
        QueryWrapper<QfFinanceBsBudgetD> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("main_id_", mainId);
        financeBsBudgetDManager.remove(queryWrapper);

        QueryWrapper<QfFinanceBsBudgetS> query = new QueryWrapper<>();
        query.eq("main_id_", mainId);
        financeBsBudgetSManager.remove(query);
    }

    private Map<String, List<QfFinanceBsBudgetD>> historyList(QfFinanceBsBudgetM QfFinanceBsBudgetM) {
        //获取上个月的累计销售额数据
        List<QfFinanceBsBudgetD> historyList = this.baseMapper.historyList(QfFinanceBsBudgetM.getFillMonth() - 1, QfFinanceBsBudgetM.getFillYear());

        if (CollectionUtils.isEmpty(historyList)) {
            return Maps.newHashMap();
        }
        return historyList.stream().collect(Collectors.groupingBy(QfFinanceBsBudgetD::getEnterpriseCode));
    }

    private Map<String, QfFinanceBsBudgetS> historyTotalList(QfFinanceBsBudgetM mainInfo) {
        //获取上个月的累计销售额数据
        List<QfFinanceBsBudgetS> 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));
    }
}
