/**
 * 数据指标池
 */

import { ENTERPRISETEAM, FUHUAINDUSTRY, FUHUASTATE, INDUSTRY, SPECIALITY, STATEENUM } from "../../config/enum";
import { FUHUAQINODEENUM } from "../../config/pointConfig";
import { findEnterpriseByUscc, findEnterpriseCount, statsEnterpriseCycxfx, statsEnterpriseIndustry, statsEnterpriseIntellectualPropertyInfo, statsEnterpriseQualification } from "../../data/enterprise/enterprise";
import { selectFinancingCountByParams, selectFinancingListByParams, statsEnterpriseFinancingAmount, statsEnterpriseFinancingMaxAmount, statsEnterpriseFinancingRounds, statsFinancingEnterprise } from "../../data/enterprise/financingInfo";
import { statsEnterpriseBusinessInfo, statsEnterpriseQuerterBusinessInfo } from "../../data/enterprise/quarterTask/businessdata";
import { statsEnterpriseNewTeamCount } from "../../data/enterprise/quarterTask/team";
import { findFuHuaQiList } from "../../data/fuHuaQi/fuhuaqi";
import { getI18nRegisterCountByParam } from "../../data/fuHuaQi/instituQualify/i18nRegister";
import * as startupTeacherData  from "../../data/fuHuaQi/instituQualify/startupTeacher";
import { statsFHQBusiness, statsFHQQuerterBusinessInfo } from "../../data/fuHuaQi/quarterTask/businessData";
import { changeEnumValue } from "../../util/verificationEnum";
import { TARGET } from "./enum";

//企业经营数据
//





/**指标池缓存
 * 格式 :{枚举值:数据结构  }
*/
let indicatiorPoolQuerery = {};

export function getIndicationValueStr(enumValue:number, unit?) {
    let {type, value} = indicatiorPoolQuerery[enumValue];
    let str = '';
    if (type == "Number") {
        str = `${value}`;
        if (unit) str += unit;
    }
    else {
        for (let key in value) {
            if (unit) {
                str += `、${key}${value[key]}${unit}`;
            } else {
                str += `、${key}:${value[key]}`;
            }
        }
        str = str.replace("、","");
    }
    return str;
}

export function getIndicationValue(enumValue:number) {
    let {type, value} = indicatiorPoolQuerery[enumValue];
    return value
}

export function getIndicationRate(enumValue:number) {
    let {type, value} = indicatiorPoolQuerery[enumValue];
    let str = '';
    let count = 0;
    for (let key in value) {
        count += value[key];
    }
    for (let key in value) {
        str += `、${key}占比${Math.ceil(value[key]/count*10000)/100}%`
    }
    str = str.replace("、","");
    return str;
}


/**
 * 初始化指标池
 */
export async function initPool() {
    let fuHuaQiList = await findFuHuaQiList({uscc:{"$ne":"123456789123456789"}});//刨去测试账号
    const ThisYear = new Date().getFullYear();
    /**----------------------    孵化器指标         */
    indicatiorPoolQuerery[TARGET.孵化器数量] = {type:'Number', value:fuHuaQiList.length}; 
    indicatiorPoolQuerery[TARGET.孵化器孵化领域分布] = {type:'Map', value:{}};
    indicatiorPoolQuerery[TARGET.国际一流人才与国内一流人才占比] = {type:'Map', value:{}};
    indicatiorPoolQuerery[TARGET.布局新模式孵化器占比] = {type:'Map', value:{"新模式":0, "旧模式":0}};
    let isProfessionalTechnologyCount = 0;
    indicatiorPoolQuerery[TARGET.创投基金数量] = {type:"Number", value:0};
    indicatiorPoolQuerery[TARGET.孵化器具备投资功能的数量和占比] = {type:"Number", value:0};
   
    fuHuaQiList.forEach(info => {
        let {industry, foundingTeam, foundingTeamType, operationModel, isProfessionalTechnology, isCreatePTP, isParticipateInPTP} = info;

        /**孵化器孵化领域分布 */
        industry.forEach(item => {
            let industryStr = changeEnumValue(FUHUAINDUSTRY, item);
            if (!indicatiorPoolQuerery[TARGET.孵化器孵化领域分布].value[industryStr]) {
                indicatiorPoolQuerery[TARGET.孵化器孵化领域分布].value[industryStr] = 0;
            }
            indicatiorPoolQuerery[TARGET.孵化器孵化领域分布].value[industryStr] += 1; 
        });

        /**国际一流人才与国内一流人才占比 */
        let foundingTeamCount = foundingTeam.length;
        if (foundingTeamCount) {
            let foundingTeamTypeStr = changeEnumValue(ENTERPRISETEAM, foundingTeamType);
            if (!indicatiorPoolQuerery[TARGET.国际一流人才与国内一流人才占比].value[foundingTeamTypeStr]) {
                indicatiorPoolQuerery[TARGET.国际一流人才与国内一流人才占比].value[foundingTeamTypeStr] = 0;
            }
            indicatiorPoolQuerery[TARGET.国际一流人才与国内一流人才占比].value[foundingTeamTypeStr] += foundingTeamCount;
        }

        /**布局新模式孵化器占比 */
        if (operationModel) {
            indicatiorPoolQuerery[TARGET.布局新模式孵化器占比].value["新模式"] += 1;
        } else {
            indicatiorPoolQuerery[TARGET.布局新模式孵化器占比].value["旧模式"] += 1;
        }

        /**搭建专业技术平台的数量 */
        if (isProfessionalTechnology)  isProfessionalTechnologyCount += 1;

        /**创投基金数量 */
        if ( isCreatePTP == STATEENUM.是) indicatiorPoolQuerery[TARGET.创投基金数量].value += 1;

        /**孵化器具备投资功能的数量和占比 */
        if ( isParticipateInPTP ) indicatiorPoolQuerery[TARGET.孵化器具备投资功能的数量和占比].value += 1;
    });

    /**专业技术平台 */
    indicatiorPoolQuerery[TARGET.搭建专业技术平台的数量] = {type:"Number", value:isProfessionalTechnologyCount};
    indicatiorPoolQuerery[TARGET.搭建专业技术平台的占比] = { type:"Number",  value: 0};
    if (isProfessionalTechnologyCount) {
        indicatiorPoolQuerery[TARGET.搭建专业技术平台的占比].value = `${Math.ceil(isProfessionalTechnologyCount/fuHuaQiList.length*10000)/100}%`;
    }
    
    /**孵化器投融资金额 */
    indicatiorPoolQuerery[TARGET.孵化器投融资金额] = {type:"Number", value:0};
    let fuHuaQiFinancList = await selectFinancingListByParams({fuHuaQiInvestment:true});
    fuHuaQiFinancList.forEach(info => {
        let { fuHuaQiInvestmentAmount } = info;
        indicatiorPoolQuerery[TARGET.孵化器投融资金额].value += fuHuaQiInvestmentAmount;
    });

    /**在孵企业就业人数 */
    indicatiorPoolQuerery[TARGET.在孵企业就业人数] = {type:"Number", value:await statsEnterpriseNewTeamCount() };
    
    /**孵化器经营情况 */
    let fhqBusinessData = await statsFHQBusiness(ThisYear);
    let fhqQuerterBusiness = await statsFHQQuerterBusinessInfo(ThisYear);
    let misAndRRMap = {};
    for (let key in fhqQuerterBusiness.MISMap) {
        misAndRRMap[key] = fhqQuerterBusiness.MISMap[key] + fhqQuerterBusiness.RRMap[key];
    }
    indicatiorPoolQuerery[TARGET.孵化器营收总金额] = {type:"Number", value:fhqBusinessData.MIS + fhqBusinessData.RR };
    indicatiorPoolQuerery[TARGET.孵化器营收季度趋势] = {type:"Map", value:misAndRRMap};
    indicatiorPoolQuerery[TARGET.孵化器纳税金额] = {type:"Number", value:fhqBusinessData.TP};
    indicatiorPoolQuerery[TARGET.孵化器纳税季度趋势] = {type:"Map", value:fhqQuerterBusiness.TPMap};

    /**国际化合作 */
    indicatiorPoolQuerery[TARGET.国际化合作数量] = {type:"Number", value:await getI18nRegisterCountByParam({})};
    
    /**创业导师 */
    let teacherList = await startupTeacherData.findListDataByParam({});
    let teacherTypeMap = {};
    teacherList.forEach(info => {
        let { speciality } = info;
        speciality.forEach(item => {
            let specialityStr = changeEnumValue(SPECIALITY, item);
            if (!teacherTypeMap[specialityStr]) teacherTypeMap[specialityStr] = 0;
            teacherTypeMap[specialityStr] += 1;
        });
       
    });
    indicatiorPoolQuerery[TARGET.创业导师数量] = {type:"Number", value:teacherList.length};
    indicatiorPoolQuerery[TARGET.创业导师专业分布] = {type:"Map", value:teacherTypeMap};

    /**----------------------       企业指标        */

    /**企业基础信息 */
    indicatiorPoolQuerery[TARGET.企业总数] = {type:"Number", value:await findEnterpriseCount({}) }
    indicatiorPoolQuerery[TARGET.行业领域分布] = {type:"Map", value:await statsEnterpriseIndustry() };
    indicatiorPoolQuerery[TARGET.创业创新方向各类型占比] = {type:"Map", value:await statsEnterpriseCycxfx() };

    /**企业融资相关 */
    const FinancingAmout = await statsEnterpriseFinancingAmount();
    indicatiorPoolQuerery[TARGET.企业融资数量] = {type:"Number", value:await selectFinancingCountByParams({}) };
    indicatiorPoolQuerery[TARGET.企业融资金额] = {type:"Number", value:FinancingAmout};
    const MaxFinancingAmout = await statsEnterpriseFinancingMaxAmount();
    indicatiorPoolQuerery[TARGET.融资最多企业金额和占比] = {type:"Number", value:0};
    if (MaxFinancingAmout) {
        indicatiorPoolQuerery[TARGET.融资最多企业金额和占比].value = `${Math.ceil(MaxFinancingAmout/FinancingAmout*10000)/100}%`;
    }
    indicatiorPoolQuerery[TARGET.融资企业的融资轮次分布] = {type:"Map", value:await statsEnterpriseFinancingRounds() };
    
    let {industryAmountMap, industryCountInfo} = await enterpriseFinancingIndustry();
    indicatiorPoolQuerery[TARGET.融资行业领域占比] = {type:"Map", value:industryAmountMap};
    indicatiorPoolQuerery[TARGET.融资事件最多的领域] = {type:"Map", value:industryCountInfo};

    /**企业上市情况 */
    const BeOnTheMarketCount = await findEnterpriseCount({
        state:{"$ne":FUHUASTATE.迁出},
        "qualification.isBeOnTheMarket":true,
        "$or":[{"$and":[{"draftLock":true}, {"taskId":{"$ne":null}}]}, {"$and":[{"draftLock":false}, {"taskId":null}]}],
    });
    indicatiorPoolQuerery[TARGET.上市企业数量] = {type:"Number", value:BeOnTheMarketCount};
   
    /**经营情况 */
    let enterpriseBusinessInfo = await statsEnterpriseBusinessInfo(ThisYear); 
    let enterpriseQuerterBusinessInfo = await statsEnterpriseQuerterBusinessInfo(ThisYear);
    indicatiorPoolQuerery[TARGET.在孵企业营收总金额] = {type:"Number", value:enterpriseBusinessInfo.BI};
    indicatiorPoolQuerery[TARGET.在孵企业营收季度趋势] = {type:"Map", value:enterpriseQuerterBusinessInfo.biMap};
    indicatiorPoolQuerery[TARGET.在孵企业纳税金额] = {type:"Number", value:enterpriseBusinessInfo.TXP};
    indicatiorPoolQuerery[TARGET.在孵企业纳税季度趋势] = {type:"Map", value:enterpriseQuerterBusinessInfo.txpMap};
    indicatiorPoolQuerery[TARGET.在孵企业研发投入金额] ={type:"Number", value:enterpriseBusinessInfo.RD};
    indicatiorPoolQuerery[TARGET.在孵企业研发投入季度趋势] = {type:"Map", value:enterpriseQuerterBusinessInfo.rdMap};

    /**企业资质 */
    let enterpriseQualificationInfo:any = await statsEnterpriseQualification();
    indicatiorPoolQuerery[TARGET.企业资质占比] = {type:"Map", value:{
        "高新技术企业":enterpriseQualificationInfo.isHighTech,
        "专精特新企业":enterpriseQualificationInfo.isZjtx,
        "小巨人培育企业":enterpriseQualificationInfo.isXjrpy,
        "小巨人企业":enterpriseQualificationInfo.isXjr
    }};
    let enterpriseIntellectualInfo = await statsEnterpriseIntellectualPropertyInfo();
    indicatiorPoolQuerery[TARGET.企业专利占比] = {type:"Map", value:enterpriseIntellectualInfo};
    console.log("指标库更新完成");
}


/**
 * 企业融资领域数据统计
 * @returns 
 */
async function enterpriseFinancingIndustry() {
    let enterpriseList = await statsFinancingEnterprise();
    let industryAmountMap = {};
    let industryCountMap = {};
    for (let i = 0; i < enterpriseList.length; i++) {
        let {uscc, count} = enterpriseList[i];
        let {industry} = await findEnterpriseByUscc(uscc);
        if (industry) {
            industry.forEach(item => {
                let str = changeEnumValue( INDUSTRY, item);
                if (!industryAmountMap[str]) industryAmountMap[str] = 0;
                industryAmountMap[str] += count;
                if (!industryCountMap[str]) industryCountMap[str] = 0;
                industryCountMap[str] += 1;
            })
        }
    }
    let max = 0;
    let maxCountIndustry = "";
    for (let str in industryCountMap) {
        let count = industryCountMap[str];
        if (count > max) {
            maxCountIndustry = str;
            max = count;
        }
    }

    return {industryAmountMap, industryCountInfo:{"领域":maxCountIndustry, "次数":max} };
}
