/**
 * 管理后台 数据看板 张江看板 企业信息
 */

import moment = require("moment");
import { ENTERPRISETEAM, FINANCINGROUNDS, FUHUASTATE } from "../../../../config/enum";
import { findEnterpriseCount, statsIntellectualPropertyData, findEnterpriseList } from "../../../../data/enterprise/enterprise";
import { statsEnterpriseFinancing, statsEnterpriseFinancingByTime } from "../../../../data/enterprise/financingInfo";
import { statsBusinessDataByParam } from "../../../../data/enterprise/quarterTask/businessdata";
import { changeEnumValue } from "../../../../util/verificationEnum";
import { statsEnterpriseTeamData } from "../../../../data/enterprise/quarterTask/team";
import { statsEnterpriseInitalTeamsType } from "../../../../data/enterprise/initialTeam";
import { findI18nRegisterListByParam } from "../../../../data/fuHuaQi/instituQualify/i18nRegister";
import { getIcrCountByParam } from "../../../../data/fuHuaQi/instituQualify/icr";
import { findFinancingList } from "../../../../data/fuHuaQi/monthTask/financing";


export async function enterpriseBaseData() {
    let dqstqy = await findEnterpriseCount({state:FUHUASTATE.实体孵化});//当前实孵企业
    let dqxnqy = await findEnterpriseCount({state:FUHUASTATE.虚拟孵化});//当前虚拟企业

    let businessData = await statsBusinessDataByParam();
    let businessDataList = [ //经营数据
        {key:"营业收入", count:Math.round(businessData.BICount/10000)}, //营业收入
        {key:"研发投入", count:Math.round(businessData.RDCount/10000)}, //研发投入
        {key:"纳税", count:Math.round(businessData.TXPCount/10000)} //纳税
    ];

    let intellectualPropertyData = await statsIntellectualPropertyData();
    let intellectualPropertyDataList = [//专利数据
        {key:"海外专利", count:intellectualPropertyData.alienPatent}, //海外专利
        {key:"一类专利", count:intellectualPropertyData.classIPatent}, //一类专利
        {key:"二类专利", count:intellectualPropertyData.secondClassPatent} //二类专利
    ];

    let gnylcrCount = 0;//国内一流人才
    let gjylcrCount = 0;//国际一流人才
    let initalTeamsList = await statsEnterpriseInitalTeamsType();
    initalTeamsList.forEach(item => {
        if (item._id == ENTERPRISETEAM.国内一流人才) gnylcrCount += item.count;
        else if (item._id == ENTERPRISETEAM.国际一流人才) gjylcrCount += item.count;
    });
    let gnylrczb = Math.round( gjylcrCount/(gjylcrCount + gnylcrCount) *100)/100
    let gjylrczb = 1 - gnylrczb;
    let initalTeamsData = {gnylrczb, gjylrczb};

    let financingRoundsDataList = await statsEnterpriseFinancing();
    let financingRoundsList = [];//融资轮次
    financingRoundsDataList.forEach(info => {
        financingRoundsList.push({
            key:changeEnumValue(FINANCINGROUNDS, info._id),
            count:info.count
        });
    });

    let financingStatsStartTime = moment().subtract(12, 'months').format("YYYY-MM")+'-01 00:00:00';
    let financingStatsList:any = await statsEnterpriseFinancingByTime(new Date(financingStatsStartTime).valueOf());
    financingStatsList.sort((a, b) => {return a.ms - b.ms});
    let financingTrendList = [];//融资趋势
    financingStatsList.forEach(info => {
        let month = new Date(info.ms).getMonth() + 1;
        financingTrendList.push({
            key:month+'月',
            count:info.count
        });
    });


    /**从业人员数 */
    let {declarationQuarter, declarationYear} = getDeclarationTime();
    let enterpriseTeamData = await statsEnterpriseTeamData(declarationYear, declarationQuarter);
    let enterpriseTeamDataList = [//从业人员数
        {key:"博士", count:enterpriseTeamData.doctorCount},//博士
        {key:"硕士", count:enterpriseTeamData.masterCount},//硕士
        {key:"本科", count:enterpriseTeamData.undergraduateCount},//本科
        {key:"专科", count:enterpriseTeamData.juniorCollegeCount},//专科
        {key:"其他", count:enterpriseTeamData.otherCount},//其他
    ];
    
    return {dqstqy, dqxnqy, businessDataList, intellectualPropertyDataList, initalTeamsData, financingRoundsList, financingTrendList, enterpriseTeamDataList};
}

function getDeclarationTime() {
    let thisYear = new Date().getFullYear();
    let thisQuarter = moment().quarter();//当月填报季度
    if ( (thisQuarter - 1) < 1 ) {
        thisYear = moment().subtract(1, 'years').year();
        thisQuarter = 4;
    } else thisQuarter = thisQuarter - 1;
    return {declarationYear:thisYear, declarationQuarter:thisQuarter};
}



export async function enterpriseNumberChnageInfo(year) {
    let param = {
        taskId:{"$regex":/^\d{18}2024\d{1,2}$/},
        draftLock:true,
    };
    let dbList = await findEnterpriseList(param);

    let map = {};

    dbList.forEach(info => {
        let { taskId, isCreate } = info;
        const match = taskId.match(/^\d{18}(\d{4})(\d{1,2})$/);
        let year = parseInt(match[1]);
        let month = parseInt(match[2]);

        let quarter = Math.ceil(month / 3);

        if (!map[quarter]) {
            map[quarter] = { quarter:`第${quarter}季度`, moveIn:0, register:0 };
        }

        if ( isCreate ) {
            map[quarter].register += 1;
        } else {
            map[quarter].moveIn += 1;
        }

    });

    let dataList = [];
    for (let key in map) {
        dataList.push(map[key]);
    }

    return {dataList}
}


export async function valueAnalysisStatis(uscc) {
    let param = { uscc };

    let i18dbList = await findI18nRegisterListByParam(param);
    let partnersCount = i18dbList.length();
    let cooperateCount = await getIcrCountByParam(param);

    let dbList = await findFinancingList({fuHuaQiUscc:uscc});
    let map = {};
    let montyMap = {};

    dbList.forEach(info => {
        let {taskId, fuHuaQiInvestmentAmount} = info;

        const match = taskId.match(/^\d{18}(\d{4})(\d{1,2})$/);
        let month = parseInt(match[2]);

        if (!map[month]) map[month] = 0;
        if (!montyMap[month]) montyMap[month] = 0;

        map[month] += 1;
        montyMap[month] += fuHuaQiInvestmentAmount;

    });

    let countList = [];
    let montyList = [];
    for (let i = 1; i <= 12; i++) {
        countList.push({
            month:`${i}月`,
            value:map[i]||0
        });

        montyList.push({
            month:`${i}月`,
            value:montyMap[i]||0
        });
    }

    return {countList, montyList, partnersCount, cooperateCount};
}


