/**
 * 自定义任务
 */
import {Schema} from 'mongoose';
import { baseDB } from '../../db/mongo/dbInit';

const customTaskSchema = new Schema({
   customTaskId:{type:String, index:true},//格式 fuHuaQiTaskType_数据周期的YYYYMM (没错，是数据周期)
   customTaskType:{type:Number},//类型 遵循  FUHUAQICUSTOMTASKTYPE
   dataCycle:{type:Number},//数据周期  202401  格式
   startMs:{type:Number},
   endMs:{type:Number},
   isExtension:{type:Boolean, default:false},//是否延期
   ct:{type:Number}
});

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



/**
 * 通过taskId 获取此次自定义任务
 * 支持.save方法保存对象修改
 * @param taskId 任务id 格式遵循tool中getTaskId
 * @returns {}
 */
export async function findCustomTaskByTaskId(customTaskId:string) {
    let taskInfo = await customTaskModel.selectOnceData({customTaskId});
    return taskInfo;
}


/**
 * 列表 分页
 * @param param 
 * @param skipCount 
 * @returns 
 */
export async function findCustomTaskListByPage(param, skipCount) {
    return await customTaskModel.find(param).sort({ct:-1}).skip(skipCount).limit(10);
}


export async function findCustomTaskCount(param) {
    return await customTaskModel.find(param).countDocuments();
}


/**
 * 添加自定义任务
 * @param customTaskId 
 * @param customTaskType 
 * @param dataCycle 
 * @param startMs 
 * @param endMs 
 */
export async function addTask(customTaskId:string, customTaskType:number, dataCycle:number, startMs:number, endMs:number ) {
    await customTaskModel.create({customTaskId, customTaskType, dataCycle, startMs, endMs, ct:new Date().valueOf()});
}



/**
 * 获取最新月份
 * @param param 
 */
export async function getNewMonthTask(customTaskType:number) {
    let list = await customTaskModel.find({customTaskType}).sort({dataCycle:-1}).limit(1);
    return list[0];
}