/**
 * 孵化器任务相关逻辑
 * 作者: 李某
 * 任务相关逻辑 包括任务的增删改查 管理后台的任务列表逻辑
 * 
 */

import moment = require("moment");
import { TASKTYPEENUM } from "../../config/enum";
import { ERRORENUM } from "../../config/errorEnum";
import { findEnterpriseListByTaskId, updateEnterpriseDraftLock } from "../../data/enterprise/enterprise";
import { findFinancingListByTaskId, updateFinancingDraftLock } from "../../data/enterprise/financing";
import { findAllFuHuaQi } from "../../data/fuHuaQi/fuhuaqi";
import { createMonthTableToList, findMonthTableByTaskId, findmonthTableListByTaskId } from "../../data/fuHuaQi/monthTable";
import { findEnterpriseByTaskIdAndType, createTaskToList, findFuHuaQiTaskByTaskId, findTaskCountByKey } from "../../data/fuHuaQi/task";
import { BizError } from "../../util/bizError";
import { logHandle } from "../../util/log";
import { getTaskId, getTimeKey } from "../../util/tools";


/**
 * 获取孵化器的任务列表
 * 小程序端
 * @param uscc 孵化器统一信用
 * @returns [{type:1, title:'', enterpriseList:[] }]
 */
export async function fuHuaQiTaskList(uscc:string) {
    let result = [];

    const TaskId = getTaskId(uscc);
    let taskMap = await findFuHuaQiTaskByTaskId(TaskId);

    // let taskTypeMapConf = {};
    for (let key in TASKTYPEENUM) {
        let k:any = key;
        if (isNaN(k)) {
            const Value = k;
            const KeyStr = TASKTYPEENUM[key]
            let keyNumber = parseInt(KeyStr);
            let onceObj = { key:keyNumber, title:Value, enterpriseList:[]};

            let onceTaskInfo = taskMap[KeyStr];

            if (!onceTaskInfo.isSubmit) { //没有提交任务
                let dataList = [];

                switch(keyNumber) {
                    case TASKTYPEENUM.孵化器月度填报: dataList = await findmonthTableListByTaskId(TaskId); break;
                    case TASKTYPEENUM.新注册或迁入企业登记: dataList = await findEnterpriseListByTaskId(TaskId); break;
                    case TASKTYPEENUM.融资企业填报: dataList = await findFinancingListByTaskId(TaskId); break;
                }
            
                dataList.forEach(info => {
                    let addInfo:any = {name:info.name, id:info.uscc, isCreate:info.isCreate || false};
                    onceObj.enterpriseList.push(addInfo);
                });
                result.push(onceObj);
            }
        } 
    }

    return {taskList:result};
}


/**
 * 提交任务
 * 小程序端
 * @param uscc 孵化器统一信用代码
 * @param taskType 任务类型
 * @returns {isSuccess:true/false}
 */
export async function checkTask(uscc:string, taskType:number) {
    const TaskId = getTaskId(uscc);
    let taskInfo = await findEnterpriseByTaskIdAndType(TaskId, taskType);

    if (!taskInfo) throw new BizError(ERRORENUM.任务不存在, uscc, TaskId);
    if ( taskInfo.isSubmit ) throw new BizError(ERRORENUM.不能重复提交任务, uscc, taskType);

    switch (taskType) {
        case TASKTYPEENUM.孵化器月度填报:
            let monthTableInfo = await findMonthTableByTaskId(TaskId);
            if (!monthTableInfo.isUpdate) throw new BizError(ERRORENUM.该报表需要填写本月内容后提交, uscc, taskType);
            if ( monthTableInfo.draftLock ) throw new BizError(ERRORENUM.不能重复提交任务, uscc, taskType, '月度表lock = true');
            
            monthTableInfo.draftLock = true;
            await monthTableInfo.save();
        break;
        case TASKTYPEENUM.新注册或迁入企业登记:
            await updateEnterpriseDraftLock(TaskId);
        break;
        case TASKTYPEENUM.融资企业填报:
            await updateFinancingDraftLock(TaskId);
        break;
    }

    //添加一条任务
    taskInfo.isSubmit = true;
    taskInfo.submitTime = new Date().valueOf();
    
    await taskInfo.save();

    return {isSuccess:true};
}


/**
 * 发放任务
 * 系统自发
 * 需求说明:
 * 每月1日0时0分，将任务下发至孵化器表中未被禁用的孵化器中
 * 
 */
export async function provideTask() {
    const TimeKey = getTimeKey();
    let taskCount = await findTaskCountByKey(TimeKey);
    if (taskCount) {}//todo 重复创建了任务

    let fuHuaQiList = await findAllFuHuaQi();

    const Month = new Date().getMonth() + 1;
    let addList = [];//任务列表
    let monthList = [];//月度填报列表
    
    const MonthNumber = moment().subtract(1, 'months').month() + 1;
    const YearNumber = new Date().getFullYear();
    const MonthTableName = `${MonthNumber}月孵化器月度填报`;

    fuHuaQiList.forEach(info => {
        let { uscc } = info;
        let taskId = getTaskId(uscc);
        addList.push({
            key:TimeKey,
            type:TASKTYPEENUM.孵化器月度填报,
            taskId,
            fuHuaQiUscc:uscc,
            isSubmit:false
        },{
            key:TimeKey,
            type:TASKTYPEENUM.新注册或迁入企业登记,
            taskId,
            fuHuaQiUscc:uscc,
            isSubmit:false
        },{
            key:TimeKey,
            type:TASKTYPEENUM.融资企业填报,
            taskId,
            fuHuaQiUscc:uscc,
            isSubmit:false
        });

        monthList.push({
            taskId,
            name:MonthTableName,
            fuHuaQiUscc:uscc,
            month:MonthNumber,
            year:YearNumber,
            draftLock:false
        });
    });


    try {
        await createTaskToList(addList);
        
         /**添加月度填报表 */
        await createMonthTableToList(monthList);
        logHandle(`添加了${addList.length}`);
    } catch (err) {
        //todo添加异常了
    }

}
