/**
 * 数据看板 张江看板  孵化器信息
 */

import moment = require("moment");
import { FUHUAINDUSTRY, FUHUAQILV, INSTITUTIONALNATURE } from "../../../../config/enum";
import { findFuHuaQiList, findFuHuaQiOperationNameMapByParam } from "../../../../data/fuHuaQi/fuhuaqi";
import { changeEnumValue } from "../../../../util/verificationEnum";
import { findMonthTableListCount, statsFuHuaQiMonthDataCount } from "../../../../data/fuHuaQi/monthTask/monthTable";
import { findScoreDataByParam } from "../../../../data/fuHuaQi/score";
import * as monthTableData from "../../../../data/fuHuaQi/monthTask/monthTable";

export async function fuHuaQiBaseData() {
    let fuHuaQiList = await findFuHuaQiList({});

    let fuHuaQiCount = 0;

    let institutionalNatureMap = {};//用户计算机构性质分布
    let logonTimeMap = {//用于计算注册时间分布
        "未满1年":{key:"未满1年", count:0},
        "1年-2年":{key:"1年-2年", count:0},
        "2年-3年":{key:"2年-3年", count:0},
        "3年-5年":{key:"3年-5年", count:0},
        "5年以上":{key:"5年以上", count:0},
    };
    let lvMap = {};//用于计算级别分布
    let industryMap = {};//用于计算孵化领域
    let nameMap = {};
    fuHuaQiList.forEach( info => {
        let { userState, institutionalNature, logonTime, lv, industry, uscc, operationName } = info;
        nameMap[uscc] = operationName;
        if (!userState) fuHuaQiCount += 1;
        let institutionalStr = changeEnumValue( INSTITUTIONALNATURE, institutionalNature);

        if (!institutionalNatureMap[institutionalStr]) institutionalNatureMap[institutionalStr] = {count:0, key:institutionalStr};
        institutionalNatureMap[institutionalStr].count += 1;
        if (logonTime) {
            let ago = moment(logonTime).fromNow(true);
            if (ago.indexOf('months') > -1) {
                logonTimeMap["未满1年"].count += 1;
            } else {
                if (parseInt(ago) <= 2) logonTimeMap["1年-2年"].count += 1;
                else if (parseInt(ago) <= 3)logonTimeMap["2年-3年"].count += 1;
                else if (parseInt(ago) <= 5)logonTimeMap["3年-5年"].count += 1;
                else logonTimeMap["5年以上"].count += 1;
            }
        }
        if (lv) {
            let lvStr = changeEnumValue(FUHUAQILV, lv);
            if (!lvMap[lvStr]) lvMap[lvStr] = {key:lvStr, count:0};
            lvMap[lvStr].count += 1;
        }
        if (industry) {
            industry.forEach(item => {
                let industryStr = changeEnumValue(FUHUAINDUSTRY, item);
                if (!industryMap[industryStr]) industryMap[industryStr] = {key:industryStr, count:0};
                industryMap[industryStr].count += 1;
            });
        }


    });

    let zcsjfb = Object.values(logonTimeMap);//注册时间分布
    let jgxzfb = Object.values(institutionalNatureMap); //机构性质分布
    let fhqjbfb = Object.values(lvMap);//孵化器级别分布
    let fhqlyfb = Object.values(industryMap);//孵化器领域分布

    let scoreDataList = await findScoreDataByParam({});
    
    let rankList = [];
    scoreDataList.forEach((info) => {
        let name = nameMap[info.uscc]
        if (!name) return;
        let score = Math.ceil(info.startScore+info.myDataScore+info.baseDataScore+info.myEnterpriseScore+info.taskScore);
        rankList.push({ name, score });
    });
    rankList.sort((a, b) => {return a.score - b.socre});
    let fhqpfpm = rankList.slice(0, 10);

    /**出租率趋势 */
    let czlqsInfo = await czlqs();

    return {czlqsInfo, fhqpfpm, zcsjfb, jgxzfb, fhqjbfb, fhqlyfb, fuHuaQiCount};
}

async function czlqs() {
    let dataList = [];
    for (let i = 1; i <= 6; i++) {
        let dataMonth = moment().subtract(i, 'months').month() +1
        let dataYear = moment().subtract(i, 'months').year();
        let ms = moment().subtract(i, 'months').valueOf();

        let dataSum = await statsFuHuaQiMonthDataCount(dataYear, dataMonth);
        let dataCount = await findMonthTableListCount({year:dataYear, month:dataMonth, draftLock:true});
        
        dataList.push({avg:Math.ceil((dataSum/dataCount) * 100)/100, month:dataMonth, ms });
    }
    dataList.sort( (a, b) => {return a.ms-b.ms});
    let monthList = [];
    let czlList = [];
    dataList.forEach(item => {
        monthList.push(item.month);
        czlList.push(item.avg);
    });
    return {czlList, monthList};
}


/**
 * 孵化器看板
 * 孵化器填报情况
 */
export async function taskTianBao(startMs, endMs) {
    let startYear = new Date(startMs).getFullYear();
    let startMonth = new Date(startMs).getMonth() + 1;
    let endMonth = new Date(endMs).getMonth() + 1; 

    
    let param = {
        draftLock:true,
        // $or: [
        //     { year: startYear, month: { $gte: startMonth } },
        //     { year: endYear, month: { $lte: endMonth } }
        // ]
        year:startYear,
        month:{"$gte":startMonth, "$lte":endMonth}
    };
    let nullParam = {
        draftLock:{"$ne":true},
        year:startYear,
        month:{"$gte":startMonth, "$lte":endMonth}
        // $or: [
        //     { year: startYear, month: { $gte: startMonth } },
        //     { year: endYear, month: { $lte: endMonth } }
        // ]
    };


    let nameMap = await findFuHuaQiOperationNameMapByParam({});

    let dbList = await monthTableData.findMonthTableList(param);
    let nullCount = await monthTableData.findMonthTableListCount(nullParam); 

    let allOccupancyRate = 0;//整体出租率
    let allCount = 0;
    let submitCount = 0;//整体填报率

    let dataList = [];
    dbList.forEach(info => {
        dataList.push({
            occupancyRate:info.occupancyRate,
            name:nameMap[info.fuHuaQiUscc] || "",
            fuHuaQiUscc:info.fuHuaQiUscc,
        });
        if (info.occupancyRate) {
            allOccupancyRate += info.occupancyRate;
            allCount += 1;
            submitCount += 1;
        } else {
            nullCount += 1;
        }

    });
    dataList.sort((a, b) => {return a.occupancyRate - b.occupancyRate});

    let occupancyRate = 0;
    if (allOccupancyRate && allCount ){
        occupancyRate = Math.ceil(allOccupancyRate/allCount);
    }
    let submitRate = 0;
    if (submitCount && (nullCount+submitCount)) {
        submitRate = Math.ceil(submitCount/(nullCount+submitCount) * 100);
    }

    return {
        occupancyRate, submitRate, dataList:dataList.slice(0, 10)
    }
}


