/**
 * 团队信息表
 */

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


/**团队信息 */
const teamSchema = new Schema({
    uscc:{type:String, index:true},
    year:Number,
    quarters:Number,
    doctor:Number,//博士
    master:Number,//硕士
    undergraduate:Number,//本科
    juniorCollege:Number,//专科
    other:Number,//其他
    studyAbroad:Number,//留学人数
    graduates:Number,//应届毕业生
    createMs:Number,//填报时间
    isSubmit:{type:Boolean, default:false}//是否提交
}); 

var teamModel;
export function initModel(){
    teamModel = baseDB.model('team', teamSchema);
    teamModel.selectOnceData = async function (paramater:object) {
        let selectInfo = await teamModel.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 uscc 企业统一信用代码
 * @param year 年度
 * @param quarters 季度
 * @returns 
 */
export async function findTeamByUsccAndTime(uscc:string, year:number, quarters:number) {
    return await teamModel.selectOnceData({uscc, year, quarters});
}


export async function findNotSubmitTeamByUsccAndTime(uscc:string, year:number, quarters:number) {
    return await teamModel.selectOnceData({uscc, year, quarters, isSubmit:false});
}


/**
 * 获取企业最新的团队数据
 * @param uscc 
 * @returns 
 */
export async function findEnterpriseNewTeamData(uscc:string) {
    let list = await teamModel.find({ uscc, isSubmit:true }).sort({"createMs":-1}).limit(1);
    return list[0] || {};
}

export async function addTeamData(addInfo) {
    await teamModel.create(addInfo);
}