/**
 * 孵化器季度任务 
 * 标识 key格式为YYYY0quarter 其含义为任务生成时的年和季度
 */

import {Schema} from 'mongoose';
import { baseDB } from '../../../db/mongo/dbInit';

const quarterTaskSchema = new Schema({
    key:{type:Number, index:true},//任务标识  格式为:YYYY0quarter  这里和月度任务做区分
    type: {type:Number,index:true},//任务类型
    taskId:String,//任务id
    fuHuaQiUscc:String,//任务所属孵化器id
    submitTime:Number,//提交时间
    // relevanceId:String,//任务关联的表 financing 或 enterprise 的id  弃用
    isSubmit:Boolean,//是否提交
    quarter:Number,//数据填报季度
    year:Number,//数据填报年 2.0算分的时候加入的
    submitCount:{type:Number, default:0},//提交数量  默认0
});

var quarterTaskModel;
export function initModel(){
    quarterTaskModel = baseDB.model('fuHuaQiQuarterTask', quarterTaskSchema);
    quarterTaskModel.selectOnceData = async function (paramater:object) {
        let selectInfo = await quarterTaskModel.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);
    });
}


export async function findQuarterTaskByParam(param) {
    return await quarterTaskModel.find(param);
}
export async function findQuarterTaskByTaskIdAndType(taskId:string, type:number) {
    return await quarterTaskModel.selectOnceData({taskId, type});
}

export async function findQuarterTaskMapTypeIsKeyByParam(taskId:string) {
    let result = await quarterTaskModel.find({taskId});
    let map = {};
    result.forEach(info => {
        map[info.type] = info;
    });
    return map;
}


export async function findQuarterTaskCountByParam(param) {
    return await quarterTaskModel.find(param).countDocuments();
}

/**
 * 创建季度任务
 * @param tableList 任务列表 
 */
export async function createQuarterTaskToList(tableList:object) {
    await quarterTaskModel.insertMany(tableList);
}


export async function findQuarterTaskByParamToPage(param, skipCount) {
    return await quarterTaskModel.find(param).skip(skipCount).limit(10);
}
