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

import moment = require("moment");
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";
import { findOneFuHuaQiMonthTaskData } from "../../../../data/fuHuaQi/monthTask/task";
import { TASKTYPEENUM } from "../../../../config/enum";

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

    /**季度任务查询条件 */
    let queryDataMap = { };//格式 {"YYYY-季度":{TP:0, member:0, index:1}},
    let quarterTaskParam:any = {fuHuaQiUscc:uscc};
    let {declarationYear, declarationQuarter} = getDeclarationTime();
    if (ThisYear != declarationYear) {
        quarterTaskParam.year = declarationYear;
        for (let i = 1; i <= 4; i++ ) {
            let key = `${declarationYear}-Q${i}`;
            queryDataMap[key] = {key, TP:0, member:0,index:i};
        }
    } else {
        quarterTaskParam["$or"] = [
            {year:ThisYear},
            {year:declarationYear, declarationQuarter:{"$gte":declarationQuarter+1}}
        ];
        for (let i = 4; i >= (declarationQuarter+1); i--) {
            let key = `${declarationYear-1}-Q${i}`;
            queryDataMap[key] = {key, TP:0, member:0,index:4-i};
        }
        for (let i =1; i < (declarationQuarter+1); i++) {
            let key = `${ThisYear}-Q${i}`;
            queryDataMap[key] = {key, TP:0, member:0,index:4+i};
        }
    }

    let businessData = await findBusinessDataByParam(quarterTaskParam);
    businessData.forEach(info => {
        let {quarter,year, TP, draftLock} = info;
        queryDataMap[`${year}-Q${quarter}`].TP = draftLock ? TP : '未填报';
    });

    let teamData = await findTeamDataByParams(quarterTaskParam);
    //获取未填报
    let notSubmitMap = {};
    teamData.forEach(info => {
        let {year, quarter, isSubmit, fhqIsSubmit} = info;
        if (!notSubmitMap[`${year}-Q${quarter}`]) notSubmitMap[`${year}-Q${quarter}`] = -1;
        if ((isSubmit == true || fhqIsSubmit == true) && notSubmitMap[`${year}-Q${quarter}`] == -1 ) {
            notSubmitMap[`${year}-Q${quarter}`] = 1;
        } 
    });
    teamData.forEach(info => {
        let { year, 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[`${year}-Q${quarter}`].member += quarterDataCount;
    });
    let quaryDataRank = Object.values(queryDataMap).sort((a:any, b:any) => {return a.index - b.index});

    let tpList = [];
    let jyrsqsList = [];
    let queryList = [];
    quaryDataRank.forEach((info:any) => {
        queryList.push(info.key);
        tpList.push( info.TP );
        if (notSubmitMap[info.key] == -1) jyrsqsList.push( '未填报' );
        else jyrsqsList.push( info.member );
    });

    /**融资企业数量趋势 */
    let startTime = new Date(moment().subtract(6, 'months').format("YYYY-MM")+"-01 00:00:00").valueOf();
    let financingData = await findFinancingList({fuHuaQiUscc:uscc, timeToObtainInvestment:{"$gt":startTime} });
    
    let financingMap = {};//结构 {"YYYY-MM":{distinctKey:0,}  }

    for (let i = 1; i <= 6; i++) {
        let itemDate = moment().subtract(i, 'months');
        let key = itemDate.format("YYYY-MM");
        let selectMonth = itemDate.month()+1;
        let selectYear = itemDate.year();
        let itemData = await findOneFuHuaQiMonthTaskData({fuHuaQiUscc:uscc, type:TASKTYPEENUM.融资企业填报,month:selectMonth, year:selectYear});
        let ms = moment().subtract(i, 'months').valueOf();
        financingMap[key]={ms, key, data:{}, fuHuaQiSubmit:itemData && itemData.isSubmit==true};
    }
    
    financingData.forEach(info => {
        let { uscc, investmentInstitutionsName, timeToObtainInvestment, draftLock } = info;
        let distinctKey = uscc + investmentInstitutionsName + timeToObtainInvestment;
        let month = moment(timeToObtainInvestment).format("YYYY-MM");
        if (financingMap[month]) financingMap[month].data[distinctKey] = 1;
    });
    let financingRankList = Object.values(financingMap).sort((a:any, b:any) => {return a.ms - b.ms});
    let rzqyslqs = [];
    financingRankList.forEach((info:any) => {
        let {data, ms, key, fuHuaQiSubmit} = info;
        let count = fuHuaQiSubmit ? Object.keys(data || {}).length : "未填报";
        rzqyslqs.push({
            month:key,
            count
        });
    });
    //识别 rzqyslqs 中的未填报数据


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


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};
}