package com.artfess.cqlt.manager.impl;

import com.alibaba.fastjson.JSONObject;
import com.artfess.base.enums.DelStatusEnum;
import com.artfess.base.manager.impl.BaseManagerImpl;
import com.artfess.cqlt.dao.QfEnterpriseInfoDao;
import com.artfess.cqlt.dao.QfFinanceReportingSummaryDDao;
import com.artfess.cqlt.dao.QfFinanceReportingSummaryMDao;
import com.artfess.cqlt.manager.QfFinanceReportingSummaryDManager;
import com.artfess.cqlt.manager.QfFinanceReportingSummarySManager;
import com.artfess.cqlt.model.QfEnterpriseInfo;
import com.artfess.cqlt.model.QfFinanceReportingSummaryD;
import com.artfess.cqlt.model.QfFinanceReportingSummaryM;
import com.artfess.cqlt.model.QfFinanceReportingSummaryS;
import com.artfess.cqlt.vo.ReportDataVo;
import com.artfess.i18n.util.I18nUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.api.client.util.Lists;
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 javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 财务-国资委资产负债和利润填报详情表 服务实现类
 *
 * @company 阿特菲斯信息技术有限公司
 * @author min.wu
 * @since 2023-03-06
 */
@Service
public class QfFinanceReportingSummaryDManagerImpl extends BaseManagerImpl<QfFinanceReportingSummaryDDao, QfFinanceReportingSummaryD> implements QfFinanceReportingSummaryDManager {

    @Resource
    private QfEnterpriseInfoDao enterpriseInfoDao;

    @Resource
    private QfFinanceReportingSummaryMDao financeReportingSummaryMDao;

    @Resource
    private QfFinanceReportingSummarySManager financeReportingSummarySManager;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean batchUpdate(QfFinanceReportingSummaryM t) {
        Assert.hasText(t.getId(), I18nUtil.getMessage("QfOperationKpiM.reportId", LocaleContextHolder.getLocale()));
        QfFinanceReportingSummaryM financePlM = financeReportingSummaryMDao.selectById(t.getId());
        Assert.notNull(financePlM, I18nUtil.getMessage("filldata.notExist", LocaleContextHolder.getLocale()));
        Assert.isTrue(!"1".equals(financePlM.getStatus()),  I18nUtil.getMessage("data_operate", LocaleContextHolder.getLocale()));
        List<QfFinanceReportingSummaryD> list = Lists.newArrayList();
        List<QfFinanceReportingSummaryS> totalList = Lists.newArrayList();
        QueryWrapper<QfEnterpriseInfo> enterpriseInfoQuery = new QueryWrapper<>();
        enterpriseInfoQuery.eq("IS_DELE_", DelStatusEnum.N.getType());
        List<QfEnterpriseInfo> enterpriseInfoList = enterpriseInfoDao.selectList(enterpriseInfoQuery);
        Map<String, QfEnterpriseInfo> enterpriseInfoMap = enterpriseInfoList.stream().collect(Collectors.toMap(item -> item.getCode(), item -> item));
        t.getList().forEach(detail -> {
            detail.setFillDate(financePlM.getFillDate());
            detail.setMainId(t.getId());
            QueryWrapper<QfFinanceReportingSummaryD> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("subject_code_", detail.getSubjectCode());
            queryWrapper.eq("main_id_", t.getId());
            queryWrapper.eq("enterprise_code_", detail.getEnterpriseCode());
            QfFinanceReportingSummaryD QfFinanceReportingSummaryD = this.baseMapper.selectOne(queryWrapper);
            if (null != QfFinanceReportingSummaryD) {
                QfFinanceReportingSummaryD.setActualYtd(detail.getActualYtd());
                list.add(QfFinanceReportingSummaryD);
            } else {
                detail.setSubjectNameEn(detail.getSubjectNameEn());
                detail.setSubjectUnit(detail.getSubjectUnit());
                detail.setSubjectCode(detail.getSubjectCode());
                //处理企业
                if (enterpriseInfoMap.containsKey(detail.getEnterpriseCode())) {
                    QfEnterpriseInfo qfEnterpriseInfo = enterpriseInfoMap.get(detail.getEnterpriseCode());
                    detail.setEnterpriseName(qfEnterpriseInfo.getName());
                    detail.setEnterpriseNameEn(qfEnterpriseInfo.getNameEn());
                }
                list.add(detail);
            }
        });

        t.getTotalList().forEach(detail -> {
            QueryWrapper<QfFinanceReportingSummaryS> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("subject_code_", detail.getSubjectCode());
            queryWrapper.eq("main_id_", t.getId());
            QfFinanceReportingSummaryS financePlActualS = financeReportingSummarySManager.getBaseMapper().selectOne(queryWrapper);
            if (null != financePlActualS) {
                if(null != detail.getActualTotal()) {
                    financePlActualS.setActualTotal(detail.getActualTotal());
                }
                if(null != detail.getActualPosting()) {
                    financePlActualS.setActualPosting(detail.getActualPosting());
                }
                if(null != detail.getActualConsolidated()) {
                    financePlActualS.setActualConsolidated(detail.getActualConsolidated());
                }
                totalList.add(financePlActualS);
            } else {
                detail.setFillDate(financePlM.getFillDate());
                detail.setFillQuarter(financePlM.getFillQuarter());
                detail.setFillMonth(financePlM.getFillMonth());
                detail.setFillYear(financePlM.getFillYear());
                detail.setMainId(t.getId());
                totalList.add(detail);
            }
        });
        if (!CollectionUtils.isEmpty(list)) {
            this.saveOrUpdateBatch(list);
        }
        if (!CollectionUtils.isEmpty(totalList)) {
            financeReportingSummarySManager.saveOrUpdateBatch(totalList);
        }

        return true;
    }

    @Override
    public List<JSONObject> detailQuery(List<QfFinanceReportingSummaryD> list) {
        if (CollectionUtils.isEmpty(list)) {
            return Lists.newArrayList();
        }
        String mainId = list.get(0).getMainId();
        QueryWrapper<QfFinanceReportingSummaryS> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("main_id_", mainId);
        List<QfFinanceReportingSummaryS> financePlSList = financeReportingSummarySManager.getBaseMapper().selectList(queryWrapper);
        List<String> enterpriseCodeHeader = this.baseMapper.getEnterpriseCodeHeader(mainId);

        List<String> subjectCodes = this.baseMapper.getSubjectCodes(mainId);

        List<JSONObject> detailList = Lists.newArrayList();

        JSONObject detail = new JSONObject(true);
        detail.put("subjectNameEn", "subjectNameEn");
        detail.put("subjectCode", "subjectCode");
//        detail.put("subjectUnit", "subjectUnit");
        enterpriseCodeHeader.forEach(code -> {
            detail.put(code, code);
        });
        detail.put("Total", "Total");
        detail.put("Consolidation Posting", "Consolidation Posting");
        detail.put("Consolidated Financial Statement", "Consolidated Financial Statement");
        detailList.add(detail);
        for (String subjectCode : subjectCodes) {
            JSONObject data = new JSONObject(true);
            data.put("subjectCode", subjectCode);
            for (QfFinanceReportingSummaryD pld : list) {
                if (pld.getSubjectCode().equals(subjectCode)) {
                    data.put("subjectNameEn", pld.getSubjectNameEn());
//                    data.put("subjectUnit", pld.getSubjectUnit());
                    data.put(pld.getEnterpriseCode(), pld.getActualYtd());
                }
            }
            for (QfFinanceReportingSummaryS pls : financePlSList) {
                if (pls.getSubjectCode().equals(subjectCode)) {
                    data.put("Total", pls.getActualTotal());
                    data.put("Consolidation Posting", pls.getActualPosting());
                    data.put("Consolidated Financial Statement", pls.getActualConsolidated());
                }
            }
            detailList.add(data);
        }

        return detailList;
    }

    @Override
    public List<ReportDataVo> getDataList(List<String> subjectCodes, Integer fillYear, Integer endMonth) {
        return baseMapper.getDataList(subjectCodes,fillYear, endMonth);
    }
}
