/**
 * 管理后台 数字看板  孵化器看板 价值分析 主要逻辑
 * 作者:lxm
 */

import { findTeamDataByParams } from "../../../../data/enterprise/quarterTask/team";
import * as i18nRegisterData from "../../../../data/fuHuaQi/instituQualify/i18nRegister";
import * as icrData from "../../../../data/fuHuaQi/instituQualify/icr";
import { findFinancingList } from "../../../../data/fuHuaQi/monthTask/financing";
import { findBusinessDataByParam } from "../../../../data/fuHuaQi/quarterTask/businessData";

export async function getValueStats(uscc) {
    const ThisYear = new Date().getFullYear();
    let i18nCount = await i18nRegisterData.getCount(uscc);//国际合作/大企业合作机构数
    let icrCount = await icrData.getCount(uscc); //大学/科研院所合作机构

    let businessData = await findBusinessDataByParam({fuHuaQiUscc:uscc, year:ThisYear });
    businessData.sort((a, b)=>{return a.quarter - b.quarter});
  
    let queryDataMap = {
        1:{TP:0, member:0},
        2:{TP:0, member:0},
        3:{TP:0, member:0},
        4:{TP:0, member:0}
    };
    businessData.forEach(info => {
        let {quarter, TP} = info;
        queryDataMap[quarter].TP = TP;
    });

    let teamData = await findTeamDataByParams({fuHuaQiUscc:uscc, year:ThisYear });
    teamData.forEach(info => {
        let { quarter } = info;
        let quarterDataCount = 0;
        quarterDataCount += info.doctor || 0;//博士
        quarterDataCount += info.master || 0;//硕士
        quarterDataCount += info.undergraduate || 0;//本科
        quarterDataCount += info.juniorCollege || 0;//专科
        quarterDataCount += info.other || 0;//其他
        queryDataMap[quarter].member += quarterDataCount;
    });

    let tpList = [];
    let jyrsqsList = [];
    let queryList = [];
    for (let key in queryDataMap) {
        queryList.push(parseInt(key));
        tpList.push( queryDataMap[key].TP );
        jyrsqsList.push( queryDataMap[key].member );
    }

    /**融资企业数量趋势 */
    let startTime = new Date(`${ThisYear}-01-01 00:00:00`).valueOf();
    let endTime = new Date(`${ThisYear+1}-01-01 00:00:00`).valueOf();
    let financingData = await findFinancingList({fuHuaQiUscc:uscc, timeToObtainInvestment:{"$gt":startTime, "$lt":endTime} });

    let financingMap = {};//结构 {month:{distinctKey:0,}  }
    financingData.forEach(info => {
        let { uscc, investmentInstitutionsName, timeToObtainInvestment } = info;
        let distinctKey = uscc + investmentInstitutionsName + timeToObtainInvestment;
        let month = new Date(timeToObtainInvestment).getMonth() + 1;
        if ( !financingMap[month] ) financingMap[month] = {};
        financingMap[month][distinctKey] = 1;
    });
    let rzqyslqs = [];
    for (let key in financingMap) {
        let count = Object.keys(financingMap[key]);
        rzqyslqs.push({
            month:parseInt(key),
            count
        });
    }

    return { jyrsqs:{jyrsqsList, queryList}, i18nCount, icrCount, rzqyslqs, tpInfo:{tpList, queryList} };
}
