/**
 * 孵化器任务表
 * 任务标识为 YYYYMM  
 * 任务id 格式遵循tool中getTaskId
 * 每种任务一个月只能提交一次  2023-02-06 确定此需求
 * 任务提交之后将不会出现在列表中  2023-02-06 确定此需求
 * 任务不能提交后不能修改和删除 2023-02-06 确定此需求
 * type 依赖枚举
 */
import {Schema} from 'mongoose';
import { baseDB } from '../../db/mongo/dbInit';

const fuHuaQiTaskSchema = new Schema({
    key:{type:Number, index:true},//任务标识  格式为:YYYYMM
    type: {type:Number,index: true},//任务类型
    taskId:String,//任务id
    fuHuaQiUscc:String,//任务所属孵化器id
    submitTime:Number,//提交时间
    // relevanceId:String,//任务关联的表 financing 或 enterprise 的id  弃用
    isSubmit:Boolean,//是否提交
});

var fuHuaQiTaskModel;
export function initModel(){
    fuHuaQiTaskModel = baseDB.model('fuHuaQiTask', fuHuaQiTaskSchema);
    fuHuaQiTaskModel.selectOnceData = async function (paramater:object) {
        let selectInfo = await fuHuaQiTaskModel.findOne(paramater).exec();
        if (selectInfo) {
            if (!selectInfo.runSave) {
                selectInfo.runSave = selectInfo.save;
                selectInfo.save = save.bind(selectInfo)
            }
        }
        return selectInfo;
    }
}
export async function save(throwError=false) {
    if (!this.isModified()) return;
    await this.runSave({validateBeforeSave:false}).catch(err=>{
        console.log(err);
    });
}

/**
 * 通过任务id 查询孵化器任务
 * @param taskId 任务id
 * @returns {1:{}, 2:{}}
 */
export async function findFuHuaQiTaskByTaskId(taskId:string) {
    let findList = await fuHuaQiTaskModel.find({taskId}).exec() || [];
    let taskMap = {};
    findList.forEach(item => {
        taskMap[item.type] = item;
    });
    return taskMap;
}


/**
 * 通过任务id和类型获取任务信息
 * 支持.save方法保存对象修改
 * @param taskId 任务id
 * @param type 任务类型
 * @returns {}
 */
export async function findEnterpriseByTaskIdAndType(taskId:string, type:number) {
    return await fuHuaQiTaskModel.selectOnceData({taskId, type});
}


export async function findTaskCountByKey(key:string) {
    return await fuHuaQiTaskModel.find({key}).count();
}



export async function createTaskToList(taskList:object) {
    await fuHuaQiTaskModel.insertMany(taskList);
}

export async function findTaskListByType(param) {
    let taskList = await fuHuaQiTaskModel.find(param);
    let map = {};
    taskList.forEach(info => {
        map[info.taskId] = info.isSubmit
    });
    return map;
}