/**
 * 管委会移动端 任务管理
 * 6.0功能
 */

import moment = require("moment");
import { GUANWEIHUIHOMEPAGESUBTYPE, TASKTYPEENUM } from "../../../config/enum";
import { ERRORENUM } from "../../../config/errorEnum";
import { fuHuaQiEnterpairseCount } from "../../../data/enterprise/enterprise";
import { findFuHuaQiOperationNameMapByParam } from "../../../data/fuHuaQi/fuhuaqi";
import { statsFinancingEnterpriseAndCount } from "../../../data/fuHuaQi/monthTask/financing";
import { findMonthTableList } from "../../../data/fuHuaQi/monthTask/monthTable";
import { distinctCycle, findTaskListByParam } from "../../../data/fuHuaQi/monthTask/task";
import { BizError } from "../../../util/bizError";


/**
 * 已下发的任务月度集合
 * @returns 
 */
export async function taskMonthsList() {
    let cycleList = await distinctCycle();

    let dataList = [];
    cycleList.forEach(info => {
        let {_id} = info;
        let dateKey = `${_id.year}-${_id.month}`;
        let monthStr = _id.month <=9 ? `0${_id.month}` : `${_id.month}`;
        let sortKey = `${_id.year}${monthStr}`;
        dataList.push({
            key:dateKey,
            value:parseInt(dateKey),
            sortKey:parseInt(sortKey)
        });
    });
    dataList.sort( (a, b) => {return a.sortKey-b.sortKey});

    return {dataList}
}


/**
 * 任务列表
 * @param submitType 
 * @param taskYear 
 * @param taskMonth 
 * @param name 
 * @param page 
 * @param subType
 * @returns 
 */
export async function taskList(submitType:number, dataYear:number, dataMonth:number, name:string, page:number, subType?) {
    if (submitType<1 || submitType>3) throw new BizError(ERRORENUM.参数错误);
    let fuHuaQiMap = {};

    //获取数据年月
    let year = dataYear
    let month = dataMonth
    //获取填报key
    let TianBaoDataTime = moment(new Date(`${dataYear}-${dataMonth}-1 00:00:01`).valueOf()).add(1,'month');
    let taskKey = `${TianBaoDataTime.year()}${TianBaoDataTime.month() + 1}`;

    //获取任务状态
    let takList = await findTaskListByParam({year, month});
    takList.forEach(info => {
        let {type, fuHuaQiUscc, isSubmit} = info;
        if (!fuHuaQiMap[fuHuaQiUscc]) {
            fuHuaQiMap[fuHuaQiUscc] = {
                month:{isSubmit:false, rate:"-"},
                enterprise:{isSubmit:false, importCount:"-", registerCount:"-"},
                financing:{isSubmit:false, count:"-", amount:"-"},
            };
        }

        switch(type) {
            case TASKTYPEENUM.孵化器月度填报:
                fuHuaQiMap[fuHuaQiUscc].month.isSubmit = isSubmit;
            break;
            case TASKTYPEENUM.新注册或迁入企业登记:
                fuHuaQiMap[fuHuaQiUscc].enterprise.isSubmit = isSubmit;
            break;
            case TASKTYPEENUM.融资企业填报:
                fuHuaQiMap[fuHuaQiUscc].financing.isSubmit = isSubmit;
            break;
        }

    });

   
    /**出租率 */
    let monthTaskList = await findMonthTableList({year, month});
    monthTaskList.forEach(info => {
        let {occupancyRate, fuHuaQiUscc} = info;
        if (fuHuaQiMap[fuHuaQiUscc]) {
            fuHuaQiMap[fuHuaQiUscc].month.rate = `${occupancyRate}%`;
        }
    });
    
    /**新注册新迁入 */
    let inputEnterpriseList = await fuHuaQiEnterpairseCount(taskKey);
    inputEnterpriseList.forEach(info => {
        let {_id, isCreateSum, isNotCreateSum} = info;
        if (fuHuaQiMap[_id]) {
            fuHuaQiMap[_id].enterprise.importCount = `${isNotCreateSum}`;
            fuHuaQiMap[_id].enterprise.registerCount = `${isCreateSum}`;
        }
    });

    let financingList = await statsFinancingEnterpriseAndCount(taskKey);
    financingList.forEach(info => {
        let {_id, enterpriseCount, financingAmount} = info;
        if (fuHuaQiMap[_id]) {
            fuHuaQiMap[_id].financing.count = `${enterpriseCount}`;
            fuHuaQiMap[_id].financing.amount = `${financingAmount}`;
        }
    });

    let nameMapParam = {};
    if (name) nameMapParam = {operationName: {"$regex":`${name}`} };
    let fhqNameMap = await findFuHuaQiOperationNameMapByParam(nameMapParam);
    let allDataList = [];
    

    for (let uscc in fuHuaQiMap) {
        if (fhqNameMap[uscc]) {
            if (subType) {
                fuHuaQiMap[uscc]["name"] = fhqNameMap[uscc];
                switch (subType) {
                    case GUANWEIHUIHOMEPAGESUBTYPE.新注册:
                        if (fuHuaQiMap[uscc].enterprise.isSubmit && parseInt(fuHuaQiMap[uscc].enterprise.registerCount)) {
                            allDataList.push(fuHuaQiMap[uscc]);
                        } 
                    break;
                    case GUANWEIHUIHOMEPAGESUBTYPE.新迁入:
                        if (fuHuaQiMap[uscc].enterprise.isSubmit && parseInt(fuHuaQiMap[uscc].enterprise.importCount)) {
                            allDataList.push(fuHuaQiMap[uscc]);
                        } 
                    break;
                    case GUANWEIHUIHOMEPAGESUBTYPE.出租率:
                        if (fuHuaQiMap[uscc].month.isSubmit) {
                            allDataList.push(fuHuaQiMap[uscc]);
                        } 
                    break;
                    case GUANWEIHUIHOMEPAGESUBTYPE.融资额:
                    case GUANWEIHUIHOMEPAGESUBTYPE.融资企业:
                        if (fuHuaQiMap[uscc].financing.isSubmit && fuHuaQiMap[uscc].financing.count != '-') {
                            allDataList.push(fuHuaQiMap[uscc]);
                        } 
                    break;
                }

            } else {
                fuHuaQiMap[uscc]["name"] = fhqNameMap[uscc];
                let itemState = 0;
                if (fuHuaQiMap[uscc].month.isSubmit == false || fuHuaQiMap[uscc].enterprise.isSubmit == false || fuHuaQiMap[uscc].financing.isSubmit == false) {
                    itemState = 3;
                } else {
                    itemState = 2;
                }
    
                if (itemState == submitType || submitType == 1) allDataList.push(fuHuaQiMap[uscc]);
            }
            
            
        }
    }

    let dataCount = allDataList.length;

    /**在全量结果数据里做分页 */
    let dataList = allDataList.splice((page-1)*10, page*10);

    return {dataCount:dataCount, dataList, pageCount:Math.ceil(dataCount/10)};
}