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

import moment = require("moment");
import { ENTERPRISETEAM, FUHUASTATE, INDUSTRY, MOVEOUTTYPE, STATEENUM } from "../../../../config/enum";
import { ENTERPRISENODEENUM, FUHUAQINODEENUM, POINTTYPEENUM } from "../../../../config/pointConfig";
import { findEnterpriseCount, findEnterpriseCountByFuHuaQiUscc, findEnterpriseList } from "../../../../data/enterprise/enterprise";
import { findMonthTableList } from "../../../../data/fuHuaQi/monthTask/monthTable";
import { getPointDataByParam } from "../../../point";
import { findBusinessDataByParam } from "../../../../data/fuHuaQi/quarterTask/businessData";
import { changeEnumValue } from "../../../../util/verificationEnum";


/**
 * 孵化器运营分析
 * @param uscc 
 */
export async function fuHuaQiOperateStats(uscc:string, year:number) {
    let enterpriseTotal = await findEnterpriseCountByFuHuaQiUscc(uscc); //非迁出企业总数
    let virtualEnterpriseNum = await findEnterpriseCount({fuHuaQiUscc:uscc, state:FUHUASTATE.虚拟孵化, draftLock:true}) || 0; //虚拟孵化

    let monthTableDataList = await findMonthTableList({uscc, year});
    monthTableDataList.sort((a, b) => {return a.month - b.month});

    let czlbhqs = {monthList:[], dataList:[]};
    monthTableDataList.forEach(info => {
        let {month, occupancyRate} = info;
        czlbhqs.monthList.push(month);
        czlbhqs.dataList.push(occupancyRate);
    });

    let zfqyqs = await getFuHuaQiOwnEnterpriseCountStats(uscc, year);

    let byqyslbhqs = await getFuHuaQiOwnEnterpriseGraduateCountStats(uscc, year);

    let enterpriseIndustryList = await getEnterpriseIndustry(uscc, year);

    let businessDbList = await findBusinessDataByParam({fuHuaQiUscc:uscc, draftLock:true, year});
    let businessMap = {
        TR:{key:"综合收入", count:0}, 
        ROR:{key:"投资收入", count:0}, 
        RR:{key:"租金收入", count:0}, 
        FS:{key:"财政补贴", count:0}, 
        MIS:{key:"其他", count:0}
    };
    businessDbList.forEach(info => { 
        let {TR, ROR, RR, FS, MIS } = info;
        if ( TR ) businessMap["TR"].count += TR;
        if ( ROR ) businessMap["ROR"].count += ROR;
        if ( RR ) businessMap["RR"].count += RR;
        if ( FS ) businessMap["FS"].count += FS;
        if ( MIS ) businessMap["MIS"].count += MIS;
    });
    let businessList = Object.values(businessMap);

    return {enterpriseTotal, virtualEnterpriseNum, zfqyqs, byqyslbhqs, businessList, czlbhqs, enterpriseIndustryList};
}


/**
 * 孵化器拥有企业数量趋势
 * @param uscc 
 */
async function getFuHuaQiOwnEnterpriseCountStats(uscc:string, year:number) {
    let dataStartMs = new Date().valueOf();
    let dataEndMs = new Date().valueOf();
    if (year!= new Date().getFullYear()) {
        dataStartMs = new Date(year+"-01-01 00:00:00").valueOf();
        dataEndMs = new Date((year+1)+"-01-01 00:00:00").valueOf();
    } else {
        dataStartMs = new Date(moment().subtract(12, 'months').format("YYYY-MM")+"-01 00:00:00").valueOf();
    }
    let param = {
        uid:uscc,
        ct:{"$gt":dataStartMs, "$lt":dataEndMs},
    };

    let pointDataList = await getPointDataByParam(POINTTYPEENUM.孵化器, FUHUAQINODEENUM.企业状态变化, param);

    let distinctMap = {}; //{ month:{ct:xxx, dataInfo:{} } }

    /**获取每个月的最后一次改动 */
    pointDataList.forEach(info => {
        let {p1, ct } = info;
        let pointInfo = JSON.parse(p1);
        let dataMonth = new Date(ct).getMonth() + 1;

        if (!distinctMap[dataMonth]) distinctMap[dataMonth] = {ct, pointInfo};
        else if(distinctMap[dataMonth].ct < ct) distinctMap[dataMonth] = {ct, pointInfo};
    });
    
    let dataList = [];
    for (let monthStr in distinctMap) {
        let {ct, pointInfo} = distinctMap[monthStr];
        dataList.push({month:monthStr, ct, xn:pointInfo.xn||0, st:pointInfo.st||0 });
    }
    /**按时间从小到大 */
    dataList.sort((a,b) => {return a.ct - b.ct});

    let xnData = [];
    let stData = [];
    let monthData = [];
    dataList.forEach(info => {
        let {month, xn, st} = info;
        monthData.push(month);
        xnData.push(xn);
        stData.push(st);
    });
    return {xnData, stData, monthData}
}


/**
 * 毕业企业数量变化趋势
 * @param uscc 
 * @param year 
 * @returns 
 */
async function getFuHuaQiOwnEnterpriseGraduateCountStats(uscc:string, year:number) {
    let dataStartMs = new Date().valueOf();
    let dataEndMs = new Date().valueOf();
    if (year!= new Date().getFullYear()) {
        dataStartMs = new Date(year+"-01-01 00:00:00").valueOf();
        dataEndMs = new Date((year+1)+"-01-01 00:00:00").valueOf();
    } else {
        dataStartMs = new Date(moment().subtract(12, 'months').format("YYYY-MM")+"-01 00:00:00").valueOf();
    }
    let param = {
        uid:uscc,
        ct:{"$gt":dataStartMs, "$lt":dataEndMs},
    };
    let pointDataList = await getPointDataByParam(POINTTYPEENUM.孵化器, FUHUAQINODEENUM.我的企业_孵化状态, param);

    let monthDataMap = {};
    pointDataList.forEach(info => {
        let { p2, ct } = info;
        let { state, moveOutType } = JSON.parse(p2);

        let dataMonth = new Date(ct).getMonth() + 1;
        if (state == FUHUASTATE.迁出 && moveOutType == MOVEOUTTYPE.毕业迁出) {
            if (!monthDataMap[dataMonth]) monthDataMap[dataMonth] = {ct, month:dataMonth, count:0}
            monthDataMap[dataMonth].count += 1;
        }
    });
    let dataList = Object.values(monthDataMap);

    let monthData = [];
    let graduateData = [];
    dataList.forEach(info => {
        let {month, count}:any = info;
        monthData.push(month);
        graduateData.push(count)
    });

    //todo 这缺一个  拟毕业

    return {monthData, graduateData};
}

async function getEnterpriseIndustry(uscc:string, year:number) {
    /**逻辑：以enterprise数据为基础，如有 基本信息_行业领域 埋点，跟进埋点*/
    let enterpriseList = await findEnterpriseList({fuHuaQiUscc:uscc});
    
    let distinctMap = {};
    enterpriseList.forEach(info => {
        let {uscc, industry} = info;
        distinctMap[uscc] = industry;
    });

    let startTime = new Date(year+'-01-01 00:00:00').valueOf();
    let endTime = new Date((year+1)+'-01-01 00:00:00').valueOf();
    let pointDataList = await getPointDataByParam(POINTTYPEENUM.企业, ENTERPRISENODEENUM.基本信息_行业领域, {p3:uscc, ct:{"$gt":startTime, "$lt":endTime} });

    pointDataList.forEach(info => {
        let {uid, p2} = info;
        distinctMap[uid] = JSON.stringify(p2 || "[]");
    });

    let countMap = {};
    for (let key in distinctMap) {
        distinctMap[key].forEach(industryItem => {
            if (!countMap[industryItem]) countMap[industryItem] = 0;
            countMap[industryItem] += 1;
        })
    }

    let dataList = [];

    for (let key in countMap) {
        let name = changeEnumValue(INDUSTRY, parseInt(key));
        dataList.push({name, value:countMap[key]});
    }

    return dataList;
}