/**
 * 企业投资详情表 
 * financing 确定好的数据才会到这里来
 */

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

const financingSchema = new Schema({
    id:{type:String, index:true},//唯一标识
    uscc:{type:String, index:true},//融资企业统一信用代码 冗余字段
    name:String,//企业名称
    financingRounds:Number,//融资轮次
    financingAmount:Number,//融资金额(万元)
    investmentInstitutionsName:String,//投资机构名称
    timeToObtainInvestment:Number,//获得投资时间
    fuHuaQiInvestment:{type:Boolean, default:false},//孵化器是否投资
    fuHuaQiInvestmentAmount:Number,//孵化器投资金额(万元)
    fuHuaQiInvestmentStyle:Number,//孵化器投资方式
    createTime:Number,//录入时间
    type:{type:Number, default:1},//1为 孵化器  2为企业自己添加  3为孵化器添加企业修改
});

var financingInfoModel;
export function initModel(){
    financingInfoModel = baseDB.model('financinginfo', financingSchema);
    financingInfoModel.selectOnceData = async function (paramater:object) {
        let selectInfo = await financingInfoModel.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);
    });
}



export async function addFinancingInfo(addInfo) {
    await financingInfoModel.create(addInfo);
}


/**
 * 获取企业融资情况列表
 * @param uscc 
 * @returns 
 */
export async function selectFinancingListByUscc(uscc:string) {
    return await financingInfoModel.find({uscc});
}


export async function selectFinancingInfo(uscc:string) {
    return await financingInfoModel.findOne({uscc});
}

export async function getFinancingById(id:string) {
    return await financingInfoModel.selectOnceData({id});
}

export async function deleteFinancingById(id:string) {
    return await financingInfoModel.deleteOne({id});
}

export async function selectFinancingListByParamsToPage(param, skipNumber) {
    return await financingInfoModel.find(param).skip(skipNumber).limit(10);
}

export async function selectFinancingCountByParamsToPage(param) {
    return await financingInfoModel.find(param).countDocuments();
}

export async function selectFinancingListByParams(param) {
    return await financingInfoModel.find(param);
}

/**
 * 获取两年内的融资金额
 */
export async function selectEnterpriseTwoYeasFinancing(uscc:string, startTime:number, endTime:number) {
    let param = { uscc, timeToObtainInvestment:{"$gt":startTime, "$lt":endTime } };
    let data = await financingInfoModel.find(param);
    let distinctMap = {};
    data.forEach(info => {
        let { timeToObtainInvestment, investmentInstitutionsName, financingAmount } = info;
        let distinctKey = `${timeToObtainInvestment}_${investmentInstitutionsName}`;
        if (!distinctMap[distinctKey]) distinctMap[distinctKey] = 0;
        distinctMap[distinctKey] += financingAmount;
    });

    let count = 0;
    Object.values(distinctMap).forEach((num:number) => {count += num});

    return count;
}


export async function statsEnterpriseFinancing() {
    let statsList = await financingInfoModel.aggregate([
        {"$group":{_id:"$financingRounds", count:{"$sum":"$financingAmount"} }}
    ]);
    return statsList;
}


export async function statsEnterpriseFinancingByTime(startTimeMs:number) {
    let param = { timeToObtainInvestment:{"$gt":startTimeMs} };
    let data = await financingInfoModel.find(param);

    let dataMap = {};
    data.forEach(info => {
        let {timeToObtainInvestment, financingAmount} = info; 
        let month = new Date(timeToObtainInvestment).getMonth() + 1;
        if (!dataMap[month]) dataMap[month] = {ms:timeToObtainInvestment, count:0, month};
        dataMap[month].count += financingAmount;
    });

    return Object.values(dataMap);
}