package com.hz.pm.api.gov.utils;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.ningdatech.basic.util.StrPool;
import com.ningdatech.file.entity.File;
import com.ningdatech.file.service.FileService;
import com.hz.pm.api.common.model.constant.RegionConst;
import com.hz.pm.api.common.util.BizUtils;
import com.hz.pm.api.gov.enumeration.GovProjectClassifiedEnum;
import com.hz.pm.api.gov.model.vo.*;
import com.hz.pm.api.projectdeclared.model.vo.ContractVO;
import com.hz.pm.api.projectdeclared.model.vo.PaymentPlanVO;
import com.hz.pm.api.projectdeclared.model.vo.PurchaseVO;
import com.hz.pm.api.projectlib.model.enumeration.ProjectStatusEnum;
import com.hz.pm.api.projectlib.model.enumeration.ProjectTypeNewEnum;
import com.hz.pm.api.projectlib.model.vo.ProjectApplicationVO;
import com.hz.pm.api.projectlib.model.vo.ProjectDetailVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import java.math.BigDecimal;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @Classname ProjectCollectionUtil
 * @Description
 * @Date 2023/9/14 9:07
 * @Author PoffyZhang
 */
@Slf4j
public class ProjectConvertUtil {

    /**
     * 申报项目 转为 项目归集
     * @param project
     * @return
     */
    public static GovBizProjectDetailVO declaredToCollection(ProjectDetailVO project, FileService fileService){
        GovBizProjectDetailVO projectCollection = new GovBizProjectDetailVO();
        if(Objects.isNull(project)){
            return projectCollection;
        }
        String projectCode = project.getProjectCode();
        String projectName = project.getProjectName();
        projectCollection.setBaseProjId(projectCode);
        projectCollection.setBaseProjName(projectName);
        projectCollection.setBaseinfo(buildBaseinfo(project));
        projectCollection.setApply(buildApply(project));
        projectCollection.setApprove(buildApprove(project,fileService));
        String projectType = project.getProjectType();
        ProjectTypeNewEnum match = ProjectTypeNewEnum.match(projectType);
        if(Objects.nonNull(match)){
            switch (match){
                case SJ_BUILD:
                case FIRST_BUILD:
                case SZ_BUILD:
                    projectCollection.setCimplement(buildCim(project));
                    break;
                case NEW_OPERA:
                case XU_OPERA:
                    projectCollection.setMimplement(buildMim(project));
                    break;
                default:
                    break;
            }
        }
        projectCollection.setProcures(buildProcure(project));
        return projectCollection;
    }

    //转化基本信息
    private static GovBizProjectBaseinfoVO buildBaseinfo(ProjectDetailVO project) {
        GovBizProjectBaseinfoVO baseinfo = new GovBizProjectBaseinfoVO();
        baseinfo.setBaseProjId(project.getProjectCode());
        baseinfo.setBaseProjName(project.getProjectName());
        baseinfo.setAreaCode(RegionConst.RC_HZ);
        baseinfo.setBaseAreaCode(project.getAreaCode() + RegionConst.NINE_CODE_LAST);
        baseinfo.setBaseAreaName(project.getArea());
        baseinfo.setBaseBuildDeprt(project.getBuildOrgName());
        baseinfo.setBaseBuildDeprtDing(project.getBuildOrgCode());
        baseinfo.setBaseBuildDepartUsci(project.getOrgCreditCode());
        baseinfo.setBaseConstructionType(project.getBaseConstructionType());
        baseinfo.setBaseManDeprt(project.getSuperOrg());
        baseinfo.setBaseManDeprtDing(project.getSuperOrgCode());
        baseinfo.setBaseManDepartUsci(project.getSuperOrgCreditCode());
        baseinfo.setBaseProjContacts(project.getContactName());
        baseinfo.setBaseProjContactsCall(project.getContactPhone());
        baseinfo.setBaseProjIsConfidentiality(GovProjectClassifiedEnum.NOT_CLASSIFIED.getCode());
        baseinfo.setBaseProjPrincipal(project.getResponsibleMan());
        baseinfo.setBaseProjPrincipalCall(project.getResponsibleManMobile());
        baseinfo.setBaseProvManDeprt(project.getHigherSuperOrg());
        baseinfo.setBaseProvManDepartDing(project.getHigherSuperOrgCode());
        baseinfo.setBaseProvManDeprtType(project.getBaseProvManDeprtType());
        ProjectStatusEnum match = ProjectStatusEnum.match(project.getStatus());
        if(Objects.nonNull(match)){
            if(Objects.nonNull(match.getCollectionStatus())){
                baseinfo.setBaseProjSetProg(match.getCollectionStatus().getCode());
            }
        }
        baseinfo.setBaseProjType(project.getProjectType());
        baseinfo.setDeleted(Boolean.FALSE);
        return baseinfo;
    }

    //转化申报信息
    private static GovBizProjectApplyVO buildApply(ProjectDetailVO project) {
        GovBizProjectApplyVO apply = new GovBizProjectApplyVO();
//        apply.setBaseProjId(project.getProjectCode());
        apply.setBaseProjName(project.getProjectName());
        apply.setAreaCode(RegionConst.RC_HZ);
        apply.setBaseHistorProjId(project.getBaseHistorProjId());
        apply.setBaseBasisEstablish(project.getBaseBasisEstablish());
        List<ProjectApplicationVO> projectApplications = project.getProjectApplications();
        if(CollUtil.isNotEmpty(projectApplications)){
            String appName = projectApplications.stream().map(app -> {
                if (StringUtils.isNotBlank(app.getRelatedExistsApplication())) {
                    return app.getRelatedExistsApplication();
                }
                return app.getApplicationName();
            }).collect(Collectors.joining(StrPool.SEMICOLON_CHINA));
            String appCode = projectApplications.stream().map(app -> {
                if (StringUtils.isNotBlank(app.getRelatedExistsApplication())) {
                    return app.getRelatedExistsApplicationCode();
                }
                return app.getAppCode();
            }).collect(Collectors.joining(StrPool.SEMICOLON_CHINA));
            String accountName = projectApplications.stream()
                    .map(app -> StringUtils.isNotBlank(app.getAccountAppName()) ? app.getAccountAppName() : null)
                    .filter(Objects::nonNull)
                    .collect(Collectors.joining(StrPool.SEMICOLON_CHINA));
            apply.setBaseAccountAppName(accountName);
            apply.setBaseProjSys(appName);
            apply.setBaseProjSysCode(appCode);
        }
        apply.setBaseBasisAmountOri(project.getBaseBasisAmountOri());
        String coreBusiness = project.getCoreBusiness();
        if(StringUtils.isNotBlank(coreBusiness)){
            try{
                JSONArray coreJson = JSON.parseArray(coreBusiness);
                String matters = coreJson.stream().map(j -> {
                            JSONObject matterJson = JSON.parseObject(JSON.toJSONString(j));
                            return matterJson.getString("matterName");
                        }).filter(Objects::nonNull)
                        .collect(Collectors.joining(StrPool.SEMICOLON_CHINA));
                String matterCodes = coreJson.stream().map(j -> {
                            JSONObject matterJson = JSON.parseObject(JSON.toJSONString(j));
                            return matterJson.getString("oid");
                        }).filter(Objects::nonNull)
                        .collect(Collectors.joining(StrPool.SEMICOLON_CHINA));
                apply.setBaseCoreBusiness(matters);
                apply.setBaseCoreBusinessCode(matterCodes);
            }catch (Exception e){
                log.error("项目转化失败",e);
            }
        }
        apply.setBaseDevelopCode(project.getDevelopCode());
        apply.setBaseLowestLevel(project.getLowestLevel());
        apply.setBaseHistorProjName(project.getBaseHistorProjName());
        apply.setBaseHistorProjYear(project.getBaseHistorProjYear());
        apply.setBaseProjApplyFile(project.getProjectApplicationForm());
        String beginTime = project.getBeginTime();
        String endTime = project.getEndTime();
        if(StringUtils.isNotBlank(beginTime)){
            apply.setBaseProjStartTime(BizUtils.convertLocalDateTime(beginTime));
        }
        if(StringUtils.isNotBlank(endTime)){
            apply.setBaseProjEndTime(BizUtils.convertLocalDateTime(endTime));
        }
        if(StringUtils.isNotBlank(beginTime) && StringUtils.isNotBlank(endTime)){
            try{
                String yearEnd = endTime.split(StrPool.DASH)[0];
                String yearStart = beginTime.split(StrPool.DASH)[0];
                String monthEnd = endTime.split(StrPool.DASH)[1];
                String monthStart = beginTime.split(StrPool.DASH)[1];
                Integer duration = Integer.parseInt(monthEnd) - Integer.parseInt(monthStart) +
                        (Integer.parseInt(yearEnd) - Integer.parseInt(yearStart)) * 12;
                apply.setBaseProjDuration(String.valueOf(duration));
            }catch (Exception e){
                log.error("日期转换失败:",e);
            }
        }
        apply.setBaseProjConsClass(project.getBuildLevel());
        apply.setBaseProjIntro(project.getProjectIntroduction());
        apply.setBaseProjBasis(project.getBaseProjBasis());
        apply.setBaseProjBasisFile(project.getBaseProjBasisFile());
        apply.setBaseProjDeclAmount(project.getAnnualPlanAmount());
        apply.setBaseProjTotalAmount(project.getDeclareAmount());
        apply.setBaseProjSetYear(Objects.nonNull(project.getProjectYear())
                ? String.valueOf(project.getProjectYear()) : null);
        apply.setBaseProjRemark(project.getProjectRemarks());
        apply.setBaseProjOtherFile(project.getBaseProjOtherFile());
        apply.setBaseResearchReportFile(project.getBaseResearchReportFile());
        apply.setBeseExpectedResults(project.getBeseExpectedResults());
        apply.setSetProjCodeFinan(project.getFinancialCode());
        apply.setMissing(StringUtils.isNotBlank(project.getBaseHistorProjId()) ? Boolean.FALSE : Boolean.TRUE);
        return apply;
    }

    //转化审批信息
    private static GovBizProjectApproveVO buildApprove(ProjectDetailVO project,FileService fileService) {
        GovBizProjectApproveVO approve = new GovBizProjectApproveVO();
//        approve.setBaseProjId(project.getProjectCode());
        approve.setBaseProjName(project.getProjectName());
        File file = fileService.getById(project.getApprovedFile());
        if(Objects.nonNull(file)){
            approve.setApprovalFile(JSON.toJSONString(Lists.newArrayList(file)));
        }
        approve.setAreaCode(RegionConst.RC_HZ);
        approve.setDeleted(Boolean.FALSE);
        approve.setBaseDevelopCode(project.getDevelopCode());
        approve.setBaseExpertTotalMoney(project.getProposeTotalInvest());
        approve.setBaseExpertYearMoney(project.getProposeAnnualBudget());
        approve.setBaseInitialReviewTotalMoney(project.getApprovalAmount());
        approve.setBaseProjReplyAmount(project.getApprovalBudget());
        approve.setBaseReviewCommentsFile(project.getProposeAttachFiles());
        List<ProjectApplicationVO> projectApplications = project.getProjectApplications();
        if(CollUtil.isNotEmpty(projectApplications)){
            Integer max = 0;
            for(ProjectApplicationVO app : projectApplications){
                max = Math.max(app.getSecrecyGrade(),max);
            }
            if(max > 0){
                approve.setEqualProtectionLevel(String.format(StrPool.FORMAT_DATE_SINGLE_DIGITS,max));
            }
        }
        approve.setPreliminaryDesignScheme(project.getPreliminaryPlanFile());
        approve.setPreliminaryDesignFile(project.getPreliminaryInspectionMaterials());
        approve.setBaseReviewOpinion(project.getProposeAttach());
        if(Objects.nonNull(project.getBaseReviewResults())){
            approve.setBaseReviewResults(String.format(StrPool.FORMAT_DATE_SINGLE_DIGITS,
                    project.getBaseReviewResults()));
        }
        List<PurchaseVO> purchases = project.getPurchases();
        if(CollUtil.isNotEmpty(purchases)){
            purchases.stream().map(PurchaseVO::getTransactionAmount)
                    .filter(Objects::nonNull).reduce(BigDecimal::add)
                    .ifPresent(approve::setReleaseYearMoney);

        }
        return approve;
    }

    //转化建设 实施
    private static GovBizProjectCimplementVO buildCim(ProjectDetailVO project) {
        GovBizProjectCimplementVO cim = new GovBizProjectCimplementVO();
//        cim.setBaseProjId(project.getProjectCode());
        cim.setBaseProjName(project.getProjectName());
        cim.setBaseEngineerPostpoFile(project.getSupportingMaterialsFile());
        cim.setAreaCode(RegionConst.RC_HZ);
        cim.setDeleted(Boolean.FALSE);
        cim.setBaseDevelopCode(project.getDevelopCode());
        //总结报告
        cim.setBaseSummReportFile(searchReportFile(project,5,2));
        //监理总结报告
        cim.setBaseEstaSummFile(searchReportFile(project,5,3));
        //建设核查表
        cim.setBaseCheckFile(searchReportFile(project,3,2));
        cim.setBaseThirdAcceptFile(searchReportFile(project,5,4));
        cim.setBaseInitialOpinionFile(searchReportFile(project,5,5));
        List<ProjectApplicationVO> projectApplications = project.getProjectApplications();
        if(CollUtil.isNotEmpty(projectApplications)){
            String appCode = projectApplications.stream().map(app -> {
                if (StringUtils.isNotBlank(app.getRelatedExistsApplication())) {
                    return app.getRelatedExistsApplicationCode();
                }
                return app.getAppCode();
            }).collect(Collectors.joining(StrPool.SEMICOLON_CHINA));
            cim.setBaseProjSysCode(appCode);
        }
        return cim;
    }

    //转化运维实施
    private static GovBizProjectMimplementVO buildMim(ProjectDetailVO project) {
        GovBizProjectMimplementVO mim = new GovBizProjectMimplementVO();
//        mim.setBaseProjId(project.getProjectCode());
        mim.setBaseProjName(project.getProjectName());
        mim.setBaseEngineerPostpoFile(project.getSupportingMaterialsFile());
        mim.setAreaCode(RegionConst.RC_HZ);
        mim.setDeleted(Boolean.FALSE);
        mim.setBaseDevelopCode(project.getDevelopCode());
        //监理总结报告
        mim.setBaseEstaSummFile(searchReportFile(project,5,3));
        //建设核查表
//        mim.setBaseCheckFile(searchReportFile(project,3,2));
        mim.setBaseThirdAcceptFile(searchReportFile(project,5,4));
//        mim.setBaseInitialOpinionFile(searchReportFile(project,5,5));
        List<ProjectApplicationVO> projectApplications = project.getProjectApplications();
        if(CollUtil.isNotEmpty(projectApplications)){
            String appCode = projectApplications.stream().map(app -> {
                if (StringUtils.isNotBlank(app.getRelatedExistsApplication())) {
                    return app.getRelatedExistsApplicationCode();
                }
                return app.getAppCode();
            }).collect(Collectors.joining(StrPool.SEMICOLON_CHINA));
            mim.setBaseProjSysCode(appCode);
        }
        return mim;
    }

    //转化采购信息
    private static List<GovBizProjectProcureVO> buildProcure(ProjectDetailVO project) {
        List<PurchaseVO> purchases = project.getPurchases();
        ContractVO contract = project.getContract();
        final BigDecimal[] paymentTotal = {BigDecimal.ZERO};
        if(Objects.nonNull(contract)){
            List<PaymentPlanVO> payments = contract.getPayments();
            payments.stream().map(PaymentPlanVO::getPaymentAmount)
                    .reduce(BigDecimal::add)
                    .ifPresent(b -> paymentTotal[0] = b);
        }
        if(CollUtil.isNotEmpty(purchases)){
            return purchases.stream().map(p -> {
                GovBizProjectProcureVO purchase = new GovBizProjectProcureVO();
                purchase.setBaseProjName(project.getProjectName());
                purchase.setAreaCode(RegionConst.RC_HZ);
                purchase.setDeleted(Boolean.FALSE);
                purchase.setBaseBidName(p.getBidName());
                purchase.setBasePurchasingAgencies(p.getAgency());
                purchase.setBaseUnifiedCreditCode(p.getPurchaseSocialCreditCode());
                purchase.setBaseConsDeprt(p.getSupplier());
                purchase.setBaseConsDeprtUsci(p.getSupplierSocialCreditCode());
                purchase.setBasePaymentTime(p.getTransactionTime());
                purchase.setBaseProjPurchaseAmount(p.getTransactionAmount());
                purchase.setBaseProjPurchaseWay(p.getPurchaseMethod());
                purchase.setBasePurchaseCode(p.getBudgetExecConfirmNo());
                purchase.setBaseWinningBidTime(p.getTransactionTime());
                purchase.setBiddingFile(p.getAcceptanceLetter());
                purchase.setPaymentProgress(paymentTotal[0]);
                if(Objects.nonNull(contract)){
                    purchase.setPurchaseContract(contract.getAttachment());
                }
                purchase.setSetProjCodeFinan(project.getFinancialCode());
                purchase.setPurchaseFile(p.getBidDoc());
                return purchase;
            }).collect(Collectors.toList());
        }
        return Collections.emptyList();
    }

    /**
     * 查询项目 初验终验的 报告
     * @param project
     * @return
     */
    private static String searchReportFile(ProjectDetailVO project,Integer firstIndex,Integer secondIndex) {
        if(Objects.isNull(project)){
            return null;
        }
        if(StringUtils.isNotBlank(project.getFinalAcceptanceMaterials())){
            return searchReportFileInner(project.getFinalAcceptanceMaterials(),firstIndex,secondIndex);
        }else if(StringUtils.isNotBlank(project.getPreliminaryInspectionMaterials())){
            return searchReportFileInner(project.getFinalAcceptanceMaterials(),firstIndex,secondIndex);
        }
        return null;
    }

    private static String searchReportFileInner(String fileStr,Integer firstIndex,Integer secondIndex) {
        try{
            JSONArray jsonArray = JSON.parseArray(fileStr);
            JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(jsonArray.get(firstIndex - 1)));
            JSONArray data = jsonObject.getJSONArray("data");
            JSONObject wangong = JSON.parseObject(JSON.toJSONString(data.get(secondIndex - 1)));
            JSONArray files = wangong.getJSONArray("files");
            return JSON.toJSONString(files);
        }catch (Exception e){
            log.error("解析文件失败:",e);
        }
        return null;
    }
}
