/**
 * 团队信息表
 */

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


/**团队信息 */
const teamSchema = new Schema({
    uscc:{type:String, index:true},
    fuHuaQiUscc:{type:String, index:true},
    name:String,//企业名称
    year:{type:Number, index:true},
    quarter:{type:Number, index:true},
    doctor:{type:Number, default:0},//博士
    master:{type:Number, default:0},//硕士
    undergraduate:{type:Number, default:0},//本科
    juniorCollege:{type:Number, default:0},//专科
    other:{type:Number, default:0},//其他
    studyAbroad:{type:Number, default:0},//留学人数
    graduates:{type:Number, default:0},//应届毕业生
    createMs:Number,//填报时间
    isUpdate:{type:Boolean, default:false},//是否修改
    isSubmit:{type:Boolean, default:false},//是否提交
    fhqIsSubmit:{type:Boolean, default:false},//孵化器点了审核通过这里就要改成ture 就不能显示了
}); 

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 quarter 季度
 * @returns 
 */
export async function findTeamByUsccAndTime(uscc:string, year:number, quarter:number) {
    return await teamModel.selectOnceData({uscc, year, quarter});
}

/**
 * 查询特定时间的企业团队信息数据总和
 * @param year 年度
 * @param quarter 季度
 * @returns 
 */
export async function findTeamDataCountByTime(year:number, quarter:number) {
    return await teamModel.find({year, quarter}).count();
}

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

export async function findTeamDataByParams(param) {
    return await teamModel.find(param);
}

export async function findTeamDataByUsccAndTime(uscc:string, year:number, quarter:number) {
    return await teamModel.find({uscc, year, quarter}).count();
}

/**
 * 获取企业最新的团队数据
 * @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);
}

export async function addManyTeamData(addList) {
    await teamModel.insertMany(addList);
}