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

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


/**
 * 根据任务id获取经营数据
 * @param taskId 
 * @returns 
 */
export async function findBusinessByTaskId(taskId:string) {
    return await fuHuaQiBusinessModel.selectOnceData({taskId});
}


/**
 * 根据任务id和修改状态获取任务列表
 * @param taskId 
 * @param isUpdate 
 * @returns 
 */
export async function findBusinessListByTaskIdAndUpdate(taskId:string, isUpdate:boolean) {
    return await fuHuaQiBusinessModel.find({taskId, isUpdate});
}


/**
 * 分页查询
 * @param param 
 * @param skipCount 
 * @returns 
 */
export async function findBusinessDataByParamToPage(param, skipCount) {
    return await fuHuaQiBusinessModel.find(param).skip(skipCount).limit(10);
}


/**
 * 分页获取总数
 * @param param 
 * @returns 
 */
export async function findBusinessDataCountByParam(param) {
    return await fuHuaQiBusinessModel.find(param).countDocuments();
}


/**
 * 根据条件查询列表
 * @param param 
 * @returns 
 */
export async function findBusinessDataByParam(param) {
    return await fuHuaQiBusinessModel.find(param);
}


export async function statsFHQBusiness(year:number) {
    let list = await fuHuaQiBusinessModel.aggregate([
        {"$match":{draftLock:true, year }},
        {"$group":{_id:"$year",  
            TR:{"$sum":"$TR"},
            ROR:{"$sum":"$ROR"},
            RR:{"$sum":"$RR"},
            FS:{"$sum":"$FS"},
            MIS:{"$sum":"$MIS"},
            NP:{"$sum":"$NP"},
            TP:{"$sum":"$TP"}
        }}
    ]);

    return list[0] || { TR:0, ROR:0, RR:0, FS:0, MIS:0, NP:0, TP:0 };
}


export async function statsFHQQuerterBusinessInfo(year:number) {
    let list = await fuHuaQiBusinessModel.aggregate([
        {"$match":{draftLock:true, year }},
        {"$group":{_id:"$quarter",  
            TR:{"$sum":"$TR"},
            ROR:{"$sum":"$ROR"},
            RR:{"$sum":"$RR"},
            FS:{"$sum":"$FS"},
            MIS:{"$sum":"$MIS"},
            NP:{"$sum":"$NP"},
            TP:{"$sum":"$TP"}
        }}
    ]);
    let TRMap = {};
    let RORMap = {};
    let RRMap = {};
    let FSMap = {};
    let MISMap = {};
    let NPMap = {};
    let TPMap = {};
    list.forEach(info => {
        let {_id, TR, ROR, RR, FS, MIS, NP, TP} = info;
        let str = `第${_id}季度`;
        TRMap[str] = TR;
        RORMap[str] = ROR;
        RRMap[str] = RR;
        FSMap[str] = FS;
        MISMap[str] = MIS;
        NPMap[str] = NP;
        TPMap[str] = TP;
    });

    return { TRMap, RORMap, RRMap, FSMap, MISMap, NPMap, TPMap };
}
