package com.artfess.cqlt.manager.impl;

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.QfHrPersonMDao;
import com.artfess.cqlt.manager.QfEnterpriseInfoManager;
import com.artfess.cqlt.manager.QfFinancePlDManager;
import com.artfess.cqlt.manager.QfFinancePlSManager;
import com.artfess.cqlt.manager.QfFinancialStatisticalManager;
import com.artfess.cqlt.manager.QfHrPersonDManager;
import com.artfess.cqlt.manager.QfHrPersonMManager;
import com.artfess.cqlt.manager.QfReportLogManager;
import com.artfess.cqlt.manager.QfRzStatisticalManager;
import com.artfess.cqlt.manager.QfSubjectInternationalInfoManager;
import com.artfess.cqlt.model.QfEnterpriseInfo;
import com.artfess.cqlt.model.QfFinancePlD;
import com.artfess.cqlt.model.QfFinancePlS;
import com.artfess.cqlt.model.QfHrPersonD;
import com.artfess.cqlt.model.QfHrPersonM;
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.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-02-27
 */
@Slf4j
@Service
public class QfHrPersonMManagerImpl extends BaseManagerImpl<QfHrPersonMDao, QfHrPersonM> implements QfHrPersonMManager {

    private final static String HR030000s = "HR030000s";

    private final static String PL3300S = "PL3300S";

    @Autowired
    private QfHrPersonDManager personDManager;

    @Autowired
    private QfSubjectInternationalInfoManager subjectInternationalInfoManager;

    @Autowired
    private QfEnterpriseInfoManager enterpriseInfoManager;

    @Autowired
    private QfReportLogManager reportLogManager;

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

    @Autowired
    private QfRzStatisticalManager rzStatisticalManager;

    @Autowired
    private QfFinancialStatisticalManager financialStatisticalManager;

    @Autowired
    private QfFinancePlDManager plDManager;

    @Autowired
    private QfFinancePlSManager plSManager;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean importExcel(List<HeaderNode> list, String mainId) {

        QfHrPersonM 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()));
        QueryWrapper<QfHrPersonD> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("main_id_", mainId);
        personDManager.remove(queryWrapper);
        if (CollectionUtils.isEmpty(list)) {
            return false;
        }

        //获取财务相关国际科目
        Map<String, QfSubjectInternationalInfo> subjectMap = subjectInternationalInfoManager.getSubjectCodeMap("HR");
        //获取境外企业
        Map<String, QfEnterpriseInfo> enterpriseInfoMap = enterpriseInfoManager.getEnterpriseInfoMap(null);

        //获取上个月的人资薪酬相关指标信息
        Map<String, List<QfHrPersonD>> historyMap = this.historyList(mainInfo);

        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());
        }
        List<QfHrPersonD> detailList = Lists.newArrayList();
        for (Map.Entry<Integer, List<HeaderNode>> entry : detailMap.entrySet()) {
            Integer column = entry.getKey();
            List<HeaderNode> nodes = entry.getValue();
            //获取企业编码
            String enterpriseCode = headerMap.get(column);
            if("All".equals(headerMap.get(column))){
                enterpriseCode = "CIGR";
            }
            List<QfHrPersonD> historyDetailList = Lists.newArrayList();
            if (historyMap.containsKey(enterpriseCode)) {
                historyDetailList = historyMap.get(enterpriseCode);
            }
            for (HeaderNode node : nodes) {
                QfHrPersonD qfHrPersonD = new QfHrPersonD();
                if (0 == node.getRow()) {
                    continue;
                }
                if (node.getColumn() > 1 && !StringUtils.isEmpty(node.getHeaderName())) {
                    qfHrPersonD.setMainId(mainId);
                    qfHrPersonD.setActual(new BigDecimal(node.getHeaderName()));
                    qfHrPersonD.setActualYtd(qfHrPersonD.getActual());
                    qfHrPersonD.setFillDate(mainInfo.getFillDate());
                    qfHrPersonD.setEnterpriseCode(enterpriseCode);
                    qfHrPersonD.setSubjectCode(subjectCodeMap.get(node.getRow()));
                    qfHrPersonD.setSn(node.getRow());
                    qfHrPersonD.setColumn(node.getColumn());
                    //处理课目
                    if (!subjectMap.containsKey(qfHrPersonD.getSubjectCode())) {
                        noexitSubjectCodes.add(qfHrPersonD.getSubjectCode());
                    } else {
                        QfSubjectInternationalInfo subjectInternationalInfo = subjectMap.get(qfHrPersonD.getSubjectCode());
                        qfHrPersonD.setSubjectNameEn(subjectInternationalInfo.getNameEn());
                        qfHrPersonD.setSubjectUnit(subjectInternationalInfo.getUnit());
                        qfHrPersonD.setSubjectName(subjectInternationalInfo.getName());
                        if(!StringUtils.isEmpty(subjectInternationalInfo.getLevel())) {
                            qfHrPersonD.setSubjectLevel(Integer.parseInt(subjectInternationalInfo.getLevel()));
                        }
                        //欧元
                        Map<String, QfHrPersonD> historyDetailMap = historyDetailList.stream().collect(Collectors.toMap(item -> item.getSubjectCode(), item -> item));

                        //
                        if (historyDetailMap.containsKey(qfHrPersonD.getSubjectCode()) &&  subjectInternationalInfo.getType().equals(SubjectTypeEnum.RZJE.getType())) {
                            QfHrPersonD historyDetail = historyDetailMap.get(qfHrPersonD.getSubjectCode());
                            qfHrPersonD.setActualYtd(qfHrPersonD.getActual().add(historyDetail.getActualYtd()));
                        }

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

            }
        }
        if (!CollectionUtils.isEmpty(noexitSubjectCodes)) {
            throw new BaseException(noexitSubjectCodes.toString() + I18nUtil.getMessage("code.notExist", LocaleContextHolder.getLocale()));
        }

        try {
            partitionSave(detailList);
        } catch (Exception e) {
            log.error("导入例如报表数据失败:{}", e.getMessage());
            e.printStackTrace();
            return false;
        }

        asyncReportInfo(mainInfo, detailList);
        return true;
    }

    private void asyncReportInfo(QfHrPersonM mainInfo, List<QfHrPersonD> list) {
        executorService.execute(() -> {
            String msg = null;
            String reportStatus = "0";
            try {
                saveHrVo(mainInfo, list);
                reportStatus = "1";
            } catch (Exception e) {
                msg = e.getMessage();
                log.error("人资大屏报表实际数据生成失败:{}", e.getMessage());
            }
            reportLogManager.saveReportInfo(reportStatus, msg, ReportTypeEnum.HR_ACTUAL.getType(), mainInfo.getFillYear(), mainInfo.getFillMonth());
        });
    }

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

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

    /**
     * 获取销售收入PL3300S
     * @param mainInfo
     * @param detailList
     */
    private void saveHrVo(QfHrPersonM mainInfo, List<QfHrPersonD> detailList) {
        List<ReportVo> financialVoList = Lists.newArrayList();
        DataInfoVo dataInfoVo = new DataInfoVo();
        dataInfoVo.setYear(mainInfo.getFillYear());
        dataInfoVo.setMonth(mainInfo.getFillMonth());
        dataInfoVo.setQuarter(mainInfo.getFillQuarter());
        List<ReportVo> hrList = Lists.newArrayList();
        detailList.forEach(detail -> {
            ReportVo hrVo = new ReportVo();
            hrVo.setEnterpriseCode(detail.getEnterpriseCode());
            hrVo.setActual(detail.getActual());
            hrVo.setActualYtd(detail.getActualYtd());
            hrVo.setSubjectCode(detail.getSubjectCode());
            financialVoList.add(hrVo);
            if(HR030000s.equals(hrVo.getSubjectCode())) {
                hrList.add(hrVo);
            }
        });
        QueryWrapper<QfFinancePlD> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("fill_year_", mainInfo.getFillYear());
        queryWrapper.eq("fill_month_", mainInfo.getFillMonth());
        queryWrapper.eq("subject_code_", PL3300S);
        List<QfFinancePlD> plDList = plDManager.getQfDetailList(mainInfo, PL3300S);
        plDList.forEach(detail -> {
            ReportVo hrVo = new ReportVo();
            hrVo.setEnterpriseCode(detail.getEnterpriseCode());
            hrVo.setActual(detail.getActual());
            hrVo.setActualYtd(detail.getActualYtd());
            hrVo.setSubjectCode(detail.getSubjectCode());
            financialVoList.add(hrVo);
        });
        //todo 处理集团层面数据
        QfEnterpriseInfo group = enterpriseInfoManager.getGroup();
        QueryWrapper<QfFinancePlS> query = new QueryWrapper<>();
        query.eq("fill_year_", mainInfo.getFillYear());
        query.eq("fill_month_", mainInfo.getFillMonth());
        query.eq("subject_code_", PL3300S);
        List<QfFinancePlS> totalList = plSManager.list(query);
        query = new QueryWrapper<>();
        query.eq("fill_year_", mainInfo.getFillYear());
        query.eq("fill_month_", mainInfo.getFillMonth() - 1);
        query.eq("subject_code_", PL3300S);
        List<QfFinancePlS> historyList = plSManager.list(query);
        Map<String, QfFinancePlS> historyMap = historyList.stream().collect(Collectors.toMap(item -> item.getSubjectCode(), item -> item));
        totalList.forEach(detail->{
            ReportVo financialVo = new ReportVo();
            financialVo.setEnterpriseCode(group.getCode());
            financialVo.setActualYtd(detail.getActualConsolidated());
            if(historyMap.containsKey(detail.getSubjectCode())) {
                QfFinancePlS 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);
        });
        rzStatisticalManager.saveData(financialVoList, dataInfoVo);
        dataInfoVo.setFlag(true);
        financialStatisticalManager.saveData(hrList, dataInfoVo, 1);
    }


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

    @Override
    public boolean updateStatus(QfHrPersonM t) {
        QfHrPersonM QfHrPersonM = baseMapper.selectById(t.getId());
        if (null == QfHrPersonM) {
            return false;
        }
        QfHrPersonM.setStatus(QfHrPersonM.getStatus() == 0 ? 1 : 0);
        int i = this.baseMapper.updateById(QfHrPersonM);
        if (i > 0) {
            return true;
        }
        return false;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean insertInfo(QfHrPersonM t) {
        QueryWrapper<QfHrPersonM> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("fill_year_", t.getFillYear());
        queryWrapper.eq("fill_month_", t.getFillMonth());
        queryWrapper.eq("report_id_", t.getReportId());
        List<QfHrPersonM> QfHrPersonMS = this.baseMapper.selectList(queryWrapper);
        if (!CollectionUtils.isEmpty(QfHrPersonMS)) {
            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(QfHrPersonM t) {
        QueryWrapper<QfHrPersonM> 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<QfHrPersonM> QfHrPersonMS = this.baseMapper.selectList(queryWrapper);
        if (!CollectionUtils.isEmpty(QfHrPersonMS)) {
            throw new BaseException(I18nUtil.getMessage("QfOperationKpiM.repeat", LocaleContextHolder.getLocale()));
        }
        int insert = this.baseMapper.updateById(t);
        if (insert > 0) {
            return true;
        }
        return false;
    }

    /**
     *
     * @param dataInfoVo
     * @param subjectCode
     * @return
     */
    @Override
    public List<ReportVo> getHrReportVo(DataInfoVo dataInfoVo, String subjectCode){

        List<QfHrPersonD> personDList = personDManager.findBySubjectCode(dataInfoVo, subjectCode);
        if(CollectionUtils.isEmpty(personDList)) {
            return Lists.newArrayList();
        }
        List<ReportVo> list = Lists.newArrayList();
        personDList.forEach(personInfo -> {
            ReportVo reportVo = new ReportVo();
            reportVo.setActual(personInfo.getActual());
            reportVo.setActualYtd(personInfo.getActualYtd());
            reportVo.setEnterpriseCode(personInfo.getEnterpriseCode());
            reportVo.setSubjectCode(subjectCode);
            list.add(reportVo);
        });
        return list;
    }

}
