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.QfFinanceCfMDao;
import com.artfess.cqlt.manager.QfEnterpriseInfoManager;
import com.artfess.cqlt.manager.QfFinanceCfDManager;
import com.artfess.cqlt.manager.QfFinanceCfMManager;
import com.artfess.cqlt.manager.QfFinanceCfSManager;
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.QfFinanceCfD;
import com.artfess.cqlt.model.QfFinanceCfM;
import com.artfess.cqlt.model.QfFinanceCfS;
import com.artfess.cqlt.model.QfFinancePlS;
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;

/**
 * 财务--现金流量填报主表 服务实现类
 *
 * @company 阿特菲斯信息技术有限公司
 * @author min.wu
 * @since 2023-03-02
 */
@Slf4j
@Service
public class QfFinanceCfMManagerImpl extends BaseManagerImpl<QfFinanceCfMDao, QfFinanceCfM> implements QfFinanceCfMManager {

    @Autowired
    private QfFinanceCfDManager detailManager;

    @Autowired
    private QfFinanceCfSManager sumManager;

    @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(QfFinanceCfM t) {
        QueryWrapper<QfFinanceCfM> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("fill_year_", t.getFillYear());
        queryWrapper.eq("fill_month_", t.getFillMonth());
        queryWrapper.eq("report_id_", t.getReportId());
        List<QfFinanceCfM> QfFinanceCfMS = this.baseMapper.selectList(queryWrapper);
        if (!CollectionUtils.isEmpty(QfFinanceCfMS)) {
            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(QfFinanceCfM t) {
        QueryWrapper<QfFinanceCfM> 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<QfFinanceCfM> QfFinanceCfMS = this.baseMapper.selectList(queryWrapper);
        if (!CollectionUtils.isEmpty(QfFinanceCfMS)) {
            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(QfFinanceCfM t) {
        QfFinanceCfM QfFinanceCfM = baseMapper.selectById(t.getId());
        if (null == QfFinanceCfM) {
            return false;
        }
        QfFinanceCfM.setStatus(QfFinanceCfM.getStatus() == 0 ? 1 : 0);
        int i = this.baseMapper.updateById(QfFinanceCfM);
        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;
        }
        QfFinanceCfM 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<QfFinanceCfD>> historyMap = this.historyList(mainInfo);
        //获取财务相关国际科目
        Map<String, QfSubjectInternationalInfo> subjectMap = subjectInternationalInfoManager.getSubjectCodeMap("CF");
        //获取境外企业
        Map<String, QfEnterpriseInfo> enterpriseInfoMap = enterpriseInfoManager.getEnterpriseInfoMap(null);

        Set<String> noexitSubjectCodes = Sets.newHashSet();
        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<QfFinanceCfD> 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<QfFinanceCfD> 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, noexitSubjectCodes, subjectCodeMap, detailList, enterpriseCode, historyDetailList, node);
                }else if(node.getColumn() >= maxColumn - 3 && !StringUtils.isEmpty(node.getHeaderName())){
                    if(node.getColumn() == maxColumn - 1) {
                        totalInfo.put(subjectCode+":actualConsolidated", node.getHeaderName());
                    }else if(node.getColumn() == maxColumn - 2) {
                        totalInfo.put(subjectCode+":actualPosting", node.getHeaderName());
                    }else if(node.getColumn() == maxColumn - 3) {
                        totalInfo.put(subjectCode+":actualTotal", node.getHeaderName());
                    }
                }
            }
        }

        if (!CollectionUtils.isEmpty(noexitSubjectCodes)) {
            throw new BaseException(noexitSubjectCodes.toString() + I18nUtil.getMessage("code.notExist", LocaleContextHolder.getLocale()));
        }
        List<QfFinanceCfS> totalList = getQfFinanceCfS(mainInfo, subjectMap, new ArrayList<>(subjectCodeList), totalInfo);
        sumManager.saveBatch(totalList);
        try {
            partitionSave(detailList);
        } catch (Exception e) {
            log.error("导入例如报表数据失败:{}", e.getMessage());
            return false;
        }

        asyncReportInfo(mainInfo, detailList, totalList);
        return true;
    }

    private void asyncReportInfo(QfFinanceCfM mainInfo, List<QfFinanceCfD> list, List<QfFinanceCfS> 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_ACTUAL.getType(), mainInfo.getFillYear(), mainInfo.getFillMonth());
        });
    }

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

    private void saveFinancialVo(QfFinanceCfM mainInfo, List<QfFinanceCfD> detailList, List<QfFinanceCfS> totalList) {
        QfEnterpriseInfo group = enterpriseInfoManager.getGroup();
        //获取上个月的利润信息
        Map<String, QfFinanceCfS> 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.setActual(detail.getActual());
            financialVo.setActualYtd(detail.getActualYtd());
            financialVo.setSubjectCode(detail.getSubjectCode());
            financialVoList.add(financialVo);
        });
        totalList.forEach(detail->{
            ReportVo financialVo = new ReportVo();
            financialVo.setEnterpriseCode(group.getCode());
            financialVo.setActualYtd(detail.getActualConsolidated());
            if(historyMap.containsKey(detail.getSubjectCode())) {
                QfFinanceCfS plS = historyMap.get(detail.getSubjectCode());
                if(null == financialVo.getActualYtd()) {
                    financialVo.setActualYtd(BigDecimal.ZERO);
                }
                if(null == plS || null == plS.getActualConsolidated()) {
                    financialVo.setActual(financialVo.getActualYtd());
                }else {
                    financialVo.setActual(financialVo.getActualYtd().subtract(historyMap.get(detail.getSubjectCode()).getActualConsolidated()));
                }
            }else{
                financialVo.setActual(financialVo.getActualYtd());
            }
            financialVo.setSubjectCode(detail.getSubjectCode());
            financialVoList.add(financialVo);
        });

        qfFinancialStatisticalManager.saveData(financialVoList, dataInfoVo, 1);
    }



    private List<QfFinanceCfS> getQfFinanceCfS(QfFinanceCfM mainInfo, Map<String, QfSubjectInternationalInfo> subjectMap, List<String> subjectCodeList, JSONObject totalInfo) {
        List<QfFinanceCfS> totalList = Lists.newArrayList();
        subjectCodeList.forEach(subjectCode -> {
            QfFinanceCfS plS = new QfFinanceCfS();
            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+":actualConsolidated")) {
                plS.setActualConsolidated(totalInfo.getBigDecimal(subjectCode+":actualConsolidated"));
            }
            if(totalInfo.containsKey(subjectCode+":actualPosting")) {
                plS.setActualPosting(totalInfo.getBigDecimal(subjectCode+":actualPosting"));
            }
            if(totalInfo.containsKey(subjectCode+":actualTotal")) {
                plS.setActualTotal(totalInfo.getBigDecimal(subjectCode+":actualTotal"));
            }
            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, QfFinanceCfM mainInfo, Map<String, QfSubjectInternationalInfo> subjectMap, Map<String, QfEnterpriseInfo> enterpriseInfoMap, Set<String> noexitSubjectCodes, Map<Integer, String> subjectCodeMap, List<QfFinanceCfD> detailList, String enterpriseCode, List<QfFinanceCfD> historyDetailList, HeaderNode node) {
        try {
            QfFinanceCfD financeCfD = new QfFinanceCfD();
            financeCfD.setMainId(mainId);
            financeCfD.setSn(node.getRow());
            financeCfD.setColumn(node.getColumn());
            financeCfD.setFillDate(mainInfo.getFillDate());
            financeCfD.setEnterpriseCode(enterpriseCode);
            financeCfD.setSubjectCode(subjectCodeMap.get(node.getRow()));
            //处理课目
            if (!subjectMap.containsKey(financeCfD.getSubjectCode())) {
                noexitSubjectCodes.add(financeCfD.getSubjectCode());
            } else {
                QfSubjectInternationalInfo subjectInternationalInfo = subjectMap.get(financeCfD.getSubjectCode());
                financeCfD.setSubjectNameEn(subjectInternationalInfo.getNameEn());
                financeCfD.setSubjectUnit(subjectInternationalInfo.getUnit());
                financeCfD.setSubjectName(subjectInternationalInfo.getName());
                if(!StringUtils.isEmpty(subjectInternationalInfo.getLevel())) {
                    financeCfD.setSubjectLevel(Integer.parseInt(subjectInternationalInfo.getLevel()));
                }
                //利润表 数据值 需要转换正负数 正数转负数 负数转正数
                if(subjectInternationalInfo.getType().equals(SubjectTypeEnum.CBFY.getType())) {
                    financeCfD.setActualYtd(new BigDecimal(node.getHeaderName()).multiply(new BigDecimal(-1)));
                }else{
                    financeCfD.setActualYtd(new BigDecimal(node.getHeaderName()));
                }
            }
            //  TODO  当年实际值
            Map<String, QfFinanceCfD> historyDetailMap = historyDetailList.stream().collect(Collectors.toMap(item -> item.getSubjectCode(), item -> item));
            if(historyDetailMap.containsKey(financeCfD.getSubjectCode())) {
                QfFinanceCfD historyDetail = historyDetailMap.get(financeCfD.getSubjectCode());
                financeCfD.setActual(financeCfD.getActualYtd().subtract(historyDetail.getActualYtd()));
            }else {
                financeCfD.setActual(financeCfD.getActualYtd());
            }

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

    }

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

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

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

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

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