/**
 * 团队信息表
 */

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


/**团队信息 */
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();
}


/**
 * 查询特定时间的企业团队信息数据 (孵化器未提交 企业未提交的数据)
 * @param uscc 
 * @param year 
 * @param quarter 
 * @returns 
 */
export async function findNotSubmitTeamByUsccAndTime(uscc:string, year:number, quarter:number) {
    return await teamModel.selectOnceData({uscc, year, quarter, isSubmit:false, fhqIsSubmit:false});
}


/**
 * 获取符合条件的列表
 * @param param 
 * @returns 
 */
export async function findTeamDataByParams(param) {
    return await teamModel.find(param);
}


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


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


/**
 * 添加团队信息数据
 * @param addInfo 
 */
export async function addTeamData(addInfo) {
    await teamModel.create(addInfo);
}


/**
 * 添加多条 团队信息数据
 * @param addList 
 */
export async function addManyTeamData(addList) {
    await teamModel.insertMany(addList);
}


/**
 * 统计特定时间下已经提交的所有企业经营数据总数
 * @param year 
 * @param quarter 
 * @returns 
 */
export async function statsEnterpriseTeamData(year:number, quarter:number) {
    let statsList = await teamModel.aggregate([
        {"$match":{year, quarter, "$or":[{isSubmit:true}, {fhqIsSubmit: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};
}


/**
 * 统计特定时间下已经提交的按孵化器分组的经营数据
 * @param year 
 * @param quarter 
 * @returns 
 */
export async function statsEnterTeamDataByFHQ(year:number, quarter:number) {
    let statsList = await teamModel.aggregate([
        {"$match":{year, quarter, "$or":[{isSubmit:true}, {fhqIsSubmit: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;
}


/**
 * 统计特定时间下已经提交的各企业的经营数据和
 * @param year 
 * @param quarter 
 * @returns 
 */
export async function statsEnterpriseTeamCountByNull(year:number, quarter:number) {
    let statsList = await teamModel.aggregate([
        {"$match":{year, quarter, "$or":[{isSubmit:true}, {fhqIsSubmit:true}] }},
        {"$project":{
            name:1, count:{"$sum":[ "$doctor", "$master", "$undergraduate", "$juniorCollege", "$other"]}
        }},
        {"$match":{count:0}},
    ]);
    return statsList;
}



export async function statsEnterpriseNewTeamCount() {
    let list = await teamModel.aggregate([
        {"$match":{"$or":[{isSubmit:true}, {fhqIsSubmit:true}]} },
        {"$sort":{"year":-1, "quarter":-1}},
        {"$group":{_id:"$uscc", firstDoc:{"$first":"$$ROOT"}, d:{"$sum":0}}},
        {"$group":{
            _id:"$d",  
            doctorCount:{"$sum":"$firstDoc.doctor"}, 
            masterCount:{"$sum":"$firstDoc.master"}, 
            undergraduateCount:{"$sum":"$firstDoc.undergraduate"},
            juniorCollegeCount:{"$sum":"$firstDoc.juniorCollege"},
            otherCount:{"$sum":"$firstDoc.other"}
        }}
    ]);

    let count = 0;
    let countData = list[0];
    if (countData) {
        for (let key in countData) {
            count += countData[key];
        }
    }
    
    return count;
}