/**
 * 孵化器经营数据填报
 * 
 */

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

const fuHuaQiBusinessSchema = new Schema({
    taskId:{type:String, index:true},//任务id
    name:String,//任务名称
    fuHuaQiUscc:String,//任务所属孵化器id
    TR:{type:Number, default:0},//综合收入
    ROR:{type:Number, default:0},//投资收入
    RR:{type:Number, default:0},//租金收入
    FS:{type:Number, default:0},//财政补贴
    MIS:{type:Number, default:0},//其他
    NP:{type:Number, default:0},//净利润
    TP:{type:Number, default:0},//纳税
    /**不下发字段 */
    draftLock:{type:Boolean, default:false},//草稿锁，true为提交之后，false为草稿
    quarter:{type:Number, index:true},//数据填报季度
    year:{type:Number, index:true},//数据填报年份
    isUpdate:{type:Boolean, default:false},
    submitTime:Number,//提交时间
});

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


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


export async function findBusinessByTaskId(taskId:string) {
    return await fuHuaQiBusinessModel.selectOnceData({taskId});
}

export async function findBusinessListByTaskIdAndUpdate(taskId:string, isUpdate:boolean) {
    return await fuHuaQiBusinessModel.find({taskId, isUpdate});
}