/**
 * 管委会小程序端主页面
 * 6.0功能
 */

import moment = require("moment");
import { findEnterpriseCount, newEnterpriseIndustry, statsEnterpriseLabels } from "../../data/enterprise/enterprise";
import { findTaskListByParam } from "../../data/fuHuaQi/monthTask/task";
import { statsAvgOccupancyRate } from "../../data/fuHuaQi/monthTask/monthTable";
import { statsFinancingCount, statsFinancingEnterpriseCount } from "../../data/fuHuaQi/monthTask/financing";
import { changeEnumValue } from "../../util/verificationEnum";
import { INDUSTRY } from "../../config/enum";
import { getEffectiveLabelMap } from "../../data/label";
import { statsFuHuaQiLabels } from "../../data/fuHuaQi/fuhuaqi";
import { LABELGOAL } from "../../config/enum/labelEnum";


/**
 * 主页
 * @param year 数据年 
 * @param month 数据月
 */
export async function stagingHomePageTop(year:number, month:number) {
    //上一个月周期 用于计算同比环比
    let lastMonthDate = moment(new Date(`${year}-${month}-1 00:00:00`).valueOf()).subtract(1, 'month');
    let lastYear = lastMonthDate.year();
    let lastMonth = lastMonthDate.month() + 1;

    let taskList = await findTaskListByParam({year, month});

    let taskStatsMap = {};
    taskList.forEach(info => {
        let { fuHuaQiUscc, isSubmit} = info;
        if (!taskStatsMap[fuHuaQiUscc]) taskStatsMap[fuHuaQiUscc] = true;
        if (!isSubmit) taskStatsMap[fuHuaQiUscc] = false;
    });

    let taskCount = Object.keys(taskStatsMap).length;
    let submitCount = 0;
    for (let key in taskStatsMap) {
        if (taskStatsMap[key]) submitCount += 1;
    }
    
    let tianBaoMonth =  moment(new Date(`${year}-${month}-1 00:00:00`).valueOf()).add(1, 'month');
    let nextMonthTaskId = `${tianBaoMonth.year()}${tianBaoMonth.month() + 1}`;

    let statsList = [];
    //新注册企业
    let registerCount = await findEnterpriseCount({taskId:{"$regex":`${nextMonthTaskId}$`}, isCreate:true, draftLock:true});
    let lastMonthRegisterCount = await findEnterpriseCount({taskId:{"$regex":`${lastYear}${lastMonth}$`}, isCreate:true});
    statsList.push({key:"新注册企业", value:registerCount, mom:Math.round(((registerCount-lastMonthRegisterCount)/lastMonthRegisterCount)*10000)/100 });
    //新迁入企业
    let moveInCount = await findEnterpriseCount({taskId:{"$regex":`${nextMonthTaskId}$`}, isCreate:false});
    let lastMonthMoveInCount = await findEnterpriseCount({taskId:{"$regex":`${lastYear}${lastMonth}$`}, isCreate:false});
    statsList.push({key:"新迁入企业", value:moveInCount, mom:Math.round(((moveInCount-lastMonthMoveInCount)/lastMonthMoveInCount)*10000)/100 });
    //平均出租率
    let occupancyRateAVG = await statsAvgOccupancyRate(year, month);
    let lastMonthOccupancyRateAVG = await statsAvgOccupancyRate(lastYear, lastMonth);
    statsList.push({key:"平均出租率", value:occupancyRateAVG, mom:Math.round(((occupancyRateAVG-lastMonthOccupancyRateAVG)/lastMonthOccupancyRateAVG)*10000)/100 } );
    //融资企业数
    let financingEnterpriseCount = await statsFinancingEnterpriseCount({taskId:{"$regex":`${nextMonthTaskId}$`}, draftLock:true});
    let lastMonthFinancingEnterpriseCount = await statsFinancingEnterpriseCount({taskId:{"$regex":`${lastYear}${lastMonth}$`}, draftLock:true});
    statsList.push({key:"融资企业", value:financingEnterpriseCount, mom:Math.round(((financingEnterpriseCount-lastMonthFinancingEnterpriseCount)/lastMonthFinancingEnterpriseCount)*10000)/100 });
    //融资额
    let financingCount = await statsFinancingCount({taskId:{"$regex":`${nextMonthTaskId}$`}, draftLock:true});
    let lastMonthFinancingCount = await statsFinancingCount({taskId:{"$regex":`${lastYear}${lastMonth}$`}, draftLock:true});
    statsList.push({key:"融资额", value:financingCount, mom:Math.round(((financingCount-lastMonthFinancingCount)/lastMonthFinancingCount)*10000)/100 });

    /**新增企业行业分布 */
    let industryDBList = await newEnterpriseIndustry(year, month);
    let industryList = [];
    let industryCount = 0;
    industryDBList.forEach(info => {
        let {_id, count} = info;
        if ( _id ) {
            industryList.push({key:changeEnumValue(INDUSTRY, _id), count});
            industryCount += count;
        }
        
    });
    industryList.sort((a, b) => {return b.count - a.count});
    for (let i= 0; i < industryList.length; i++) {
        let itemValue = industryList[i].count;
        industryList[i]["rate"] = Math.round( (itemValue/industryCount)*10000 )/100;
    }

    
    return {
        taskInfo:{
            taskCount,//发送填报表总数
            submitCount,//已填报
            notSubmitCount:taskCount-submitCount,//未填报
            submitRate:Math.round((submitCount/taskCount)*10000)/100,//填报率
            notSubmitRate:Math.round( ((taskCount-submitCount)/taskCount)*10000 )/100//未填报率
        },
        statsList,//卡片列表
        industryList//新增企业行业分布
    };
}


/**
 * 企业标签
 */
export async function enterpriseLabel() {
    let labelList = await statsEnterpriseLabels();

    let labelNameMap = await getEffectiveLabelMap(LABELGOAL.企业);

    let countMap = {};
    labelList.forEach(info => {
        let id = info._id;
        countMap[id] = info.count;
    });

    let dataList = [];
    for (let key in labelNameMap) {
        let name = labelNameMap[key].labelName;
        dataList.push({
            label:name,
            count:countMap[key] || 0
        });
    }
    dataList.sort((a,b) => {return b.count-a.count});

    return {dataList};
}


/**
 * 孵化器标签
 */
export async function fuHuaQiLabel() {
    let labelList = await statsFuHuaQiLabels();

    let labelNameMap = await getEffectiveLabelMap(LABELGOAL.孵化器);

    let countMap = {};
    labelList.forEach(info => {
        let id = info._id;
        countMap[id] = info.count;
    });

    let dataList = [];
    for (let key in labelNameMap) {
        let name = labelNameMap[key].labelName;
        dataList.push({
            label:name,
            count:countMap[key] || 0
        });
    }
    dataList.sort((a,b) => {return b.count-a.count});

    return {dataList};
}
