/**内部开放接口 */

import * as monthTableData from "../../data/fuHuaQi/monthTable";
import * as taskData from "../../data/fuHuaQi/task";
import * as enterpriseData from "../../data/enterprise/enterprise";
import { FUHUASTATE, SCOREWAYS, TASKTYPEENUM } from "../../config/enum";
import { ERRORENUM } from "../../config/errorEnum";
import { findAllNotDisabledFuHuaQi, findFuHuaQiList } from "../../data/fuHuaQi/fuhuaqi";
import { BizError } from "../../util/bizError";
import { logHandle } from "../../util/log";
import { initFuHuaQiScore } from "../../data/fuHuaQi/score";
import { updateScore } from "../mobileFuHuaQi/fuHuaQi/score";
import { findFinancingList } from "../../data/enterprise/financing";



/**
 * 发放1月数据
 */
export async function provideLastTask() {
    const TimeKey = '20232';

    let addList = [];//任务列表
    let monthList = [];//月度填报列表
    
    const MonthNumber = 1;//数据填报月份
    const YearNumber = 2023
    const MonthTableName = `${MonthNumber}月孵化器月度填报`;

    let fuHuaQiList = await findAllNotDisabledFuHuaQi();
    fuHuaQiList.forEach(info => {
        let { uscc } = info;
        let taskId = `${uscc}${TimeKey}`;
        addList.push( { key:TimeKey, type:TASKTYPEENUM.孵化器月度填报, month:1, taskId, fuHuaQiUscc:uscc, isSubmit:false},
            { key:TimeKey, type:TASKTYPEENUM.新注册或迁入企业登记, month:1, taskId, fuHuaQiUscc:uscc, isSubmit:false },
            { key:TimeKey, type:TASKTYPEENUM.融资企业填报, month:1, taskId, fuHuaQiUscc:uscc, isSubmit:false});
        /**任务报表的初始状态为 草稿(draftLock=fals) 未被编辑(isUpdate=false)  */
        monthList.push({ taskId, name:MonthTableName, fuHuaQiUscc:uscc, month:MonthNumber, year:YearNumber, draftLock:false, isUpdate:false });
    });

    try {
        /**初始化 任务 */
        await taskData.createTaskToList(addList);
        logHandle(`添加了${addList.length} 任务`);
         /**初始化 月度填报表 */
        await monthTableData.createMonthTableToList(monthList);
        logHandle(`添加了${monthList.length} 月度任务`);
    } catch (err) {
        new BizError(ERRORENUM.系统错误, '添加任务和月度报表的时候 出现了异常 请检查数据库  ', err);
    }
}


export async function updateEnterpriseFuHuaState() {
    await enterpriseData.updateEnterpriseState(FUHUASTATE.实体孵化);
    return {};
}

export async function updateFuHuaQiTaskYear() {
    await taskData.updateTaskYearData(2023);
    return {};
}

export async function initScoreData() {
    let data = await findFuHuaQiList({});

    let addList = [];
    data.forEach(info => {
        addList.push({
            uscc:info.uscc,//孵化器uscc
            startScore: 400,//初始分 400  创建孵化器的时候要在这里加上
            lastYearStar: 3,//去年星值  这里默认是3星  每年12月31日12时，需要根据分算星然后更新到这里
            myDataScore: 0,//我的数据获得的分数
            baseDataScore: 0,//基础数据获得的分数
            myEnterpriseScore: 0,//我的企业获得的分数
            taskScore: 0,//任务获得分数
            updateTime: new Date().valueOf(),//更新时间戳
            /**上一次评分 */
            lastScore:0//在获取列表的时候要同步数据
        });
    });
    await initFuHuaQiScore(addList);

    for (let i =0; i < data.length; i++) {
        let {uscc} = data[i];
        await updateScore(uscc, SCOREWAYS.我的企业数据, false);
        await updateScore(uscc, SCOREWAYS.我的信息, false);
        await updateScore(uscc, SCOREWAYS.我的数据, false);
    }
    
    /**初始化任务得分 */
    let taskList = await taskData.findTaskListByParam({});
    for (let i =0; i < taskList.length; i++) {
        let {fuHuaQiUscc, isSubmit, type} = taskList[i];
        if ( isSubmit ) await updateScore(fuHuaQiUscc, SCOREWAYS.任务得分, true, type);
        else await updateScore(fuHuaQiUscc, SCOREWAYS.任务得分, false, type);
    }
    console.log("初始化评分成功");

}


export async function replenishTaskData() {
    let list = await enterpriseData.findStats();

    let taskMap = {};
    list.forEach(info => {
        if (info.taskId) {
            if (!taskMap[info.taskId]) taskMap[info.taskId] = 0;
            taskMap[info.taskId] += 1;
        }
    });


    for (let key in taskMap) {
        let value = taskMap[key];

        await taskData.updateSubmitCount(key, TASKTYPEENUM.新注册或迁入企业登记, value);

    }

    let fList = await findFinancingList({});

    let fTaskMap = {};
    fList.forEach(info => {
        if (info.taskId) {
            if (!fTaskMap[info.taskId]) fTaskMap[info.taskId] = 0;
            fTaskMap[info.taskId] += 1;
        }
    });

    for (let key in fTaskMap) {
        let value = fTaskMap[key];

        await taskData.updateSubmitCount(key, TASKTYPEENUM.融资企业填报, value);

    }

    console.log("初始化任务提交数成功");
}