/**
 * 团队信息表
 */

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}).countDocuments();
}

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);
}

/**
 * 根据条件查询总数
 * @param param 查询条件
 */
export async function findTeamDataCountByParams(param) {
    return await teamModel.find(param).countDocuments()
}

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

/**
 * 获取企业最新的团队数据
 * @param uscc 
 * @returns 
 */
export async function findEnterpriseNewTeamData(uscc:string) {
    let list = await teamModel.find({ uscc, "$or":[{isSubmit:true}, {fhqIsSubmit: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);
}


export async function statsEnterpriseTeamData(year:number, quarter:number) {
    let statsList = await teamModel.aggregate([
        {"$match":{year, quarter, draftLock:true}},
        {"$group":{
            _id:"stats", 
            doctorCount:{"$sum":"$doctor"},
            masterCount:{"$sum":"$master"},
            undergraduateCount:{"$sum":"$undergraduate"},
            juniorCollegeCount:{"$sum":"$juniorCollege"},
            otherCount:{"$sum":"$other"},
        }}
    ]);
    return statsList[0] ? statsList[0] : {doctorCount:0, masterCount:0, undergraduateCount:0, juniorCollegeCount:0, otherCount:0};
}

export async function statsEnterTeamDataByFHQ(year:number, quarter:number) {
    let statsList = await teamModel.aggregate([
        {"$match":{year, quarter, draftLock:true}},
        {"$group":{
            _id:"$fuHuaQiUscc",
            doctorCount:{"$sum":"$doctor"},
            masterCount:{"$sum":"$master"},
            undergraduateCount:{"$sum":"$undergraduate"},
            juniorCollegeCount:{"$sum":"$juniorCollege"},
            otherCount:{"$sum":"$other"},
        }}
    ]);
    let map = {};
    statsList.forEach(info => {
        let { doctorCount, masterCount, undergraduateCount, juniorCollegeCount, otherCount } = info;
        map[info._id] = doctorCount + masterCount + undergraduateCount + juniorCollegeCount + otherCount;
    });
    return map;
}

export async function statsEnterpriseTeamCountByNull(year:number, quarter:number) {
    let statsList = await teamModel.aggregate([
        {"$match":{year, quarter, draftLock:true}},
        {"$project":{
            name:1, count:[ "$doctor", "$master", "$undergraduate", "$juniorCollege", "$other"]
        }},
        {"$match":{count:0}},
    ]);
    return statsList;
}