/**
 * 企业经营数据 数据层
 * 
 */

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

const businessSchema = new Schema({
    year:{type:Number, index:true},//年度
    fuHuaQiUscc:{type:String, index:true},
    quarter:{type:Number, index:true},//季度
    uscc:{type:String, index:true},
    name:{type:String, index:true},//企业名称
    BI:{type:Number, default:0},//营业收入
    RD:{type:Number, default:0},//研发投入
    TXP:{type:Number, default:0},//纳税
    createTime:Number,//填写时间
    isUpdate:{type:Boolean, default:false},//是否修改
    isSubmit:{type:Boolean, default:false},//是否提交
    fhqIsSubmit:{type:Boolean, default:false},//孵化器点了审核通过这里就要改成ture 就不能显示了
});

var businessDataModel;
export function initModel(){
    businessDataModel = baseDB.model('business', businessSchema);
    businessDataModel.selectOnceData = async function (paramater:object) {
        let selectInfo = await businessDataModel.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 年度
 */
export async function findBusinessDataByUsccAndYear(uscc:string, year:number) {
    return await businessDataModel.find({uscc, year});
}


/**
 * 获取单个数据
 * @param uscc 
 * @param year 
 * @param quarter 
 * @returns 
 */
export async function findBusinessDataByTimeAndUscc(uscc:string, year:number, quarter:number) {
    return await businessDataModel.selectOnceData({uscc, year, quarter});
}


/**
 * 获取单个数据 （孵化器和企业都未提交的数据）
 * @param uscc 
 * @param year 
 * @param quarter 
 * @returns 
 */
export async function findNotSubmitBusinessDataByTimeAndUscc(uscc:string, year:number, quarter:number) {
    return await businessDataModel.selectOnceData({uscc, year, quarter, isSubmit:false, fhqIsSubmit:false});
}


/**
 * 根据条件 分页查询
 * @param param 查询条件
 */
export async function findBusinessDataByParamsToPage(param, skipNumber) {
    return await businessDataModel.find(param).skip(skipNumber).limit(10);
}


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


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


/**
 * 添加多个数据
 * @param addList 
 */
export async function addManyBusinessData(addList) {
    await businessDataModel.insertMany(addList);
}


/**
 * 更具年份获取企业的经营数据
 * @param uscc 
 * @param startYear 
 * @param endYear 
 * @returns 
 */
export async function findBusinessDataByYear(uscc:string, startYear:number, endYear:number) {
    let dataList = await businessDataModel.find({"$or":[{year:startYear}, {year:endYear}], uscc});
    let count = 0;
    dataList.forEach(info => {
        let {BI} = info;
        if (BI) count += BI;
    });

    return count;
}


/**
 * 统计所有企业的经营数据
 * @returns 
 */
export async function statsBusinessDataByParam() {
    let statsList = await businessDataModel.aggregate([
        {"$match":{"$or":[{isSubmit:true}, {fhqIsSubmit:true}]}},
        {"$group":{_id:"stats", BICount:{"$sum":"$BI"}, RDCount:{"$sum":"$RD"}, TXPCount:{"$sum":"$TXP"} }}
    ]);
    return statsList.length ? statsList[0] : {BICount:0, RDCount:0, TXPCount:0};
}


/**
 * 根据条件统计经营次数
 * @param param 
 * @returns 
 */
export async function statsBusinessCount(param) {
    let statsList = await businessDataModel.aggregate([
        {"$match":param},
        {"$group":{_id:"$name", count:{"$sum":1} }},
        {"$match":{count:{"$gt":1}}}
    ]);
    return statsList;
}


/**
 * 统计本年度企业经营情况
 */
export async function statsEnterpriseBusinessInfo(year:number) {
    let list = await businessDataModel.aggregate([
        {"$match":{year:2023, "$or":[{isSubmit:true}, {fhqIsSubmit:true}] }},
        {"$group":{_id:"$year",  
            BI:{"$sum":"$BI"},
            RD:{"$sum":"$RD"},
            TXP:{"$sum":"$TXP"}
        }}
    ]);
    return list[0] || { BI:0, RD:0, TXP:0 };
}


export async function statsEnterpriseQuerterBusinessInfo(year:number) {
    let list = await businessDataModel.aggregate([
        {"$match":{year, "$or":[{isSubmit:true}, {fhqIsSubmit:true}] }},
        {"$group":{_id:"$quarter",  
            BI:{"$sum":"$BI"},
            RD:{"$sum":"$RD"},
            TXP:{"$sum":"$TXP"}
        }}
    ]);
    let biMap = {};
    let rdMap = {};
    let txpMap = {};
    list.forEach(info => {
        let {_id, BI, RD, TXP} = info;
        let str = `第${_id}季度`;
        biMap[str] = BI;
        rdMap[str] = RD;
        txpMap[str] = TXP;
    });

    return { biMap, rdMap, txpMap };
}


export async function selectEnterpriseBusinessAmount(uscc:string) {
    //year  BI
    let financingList = await businessDataModel.aggregate([
        {"$match":{uscc, "$or":[{isSubmit:true}, {fhqIsSubmit:true}] }},
        {"$group":{_id:"$year",  
            BI:{"$sum":"$BI"},
        }}
    ]);
    financingList.sort( (a, b) => {return a._id - b._id});
    let state = false;
    for (let i= 0; i < financingList.length; i++) {
        let {_id, BI} = financingList[i];
        let count = BI;
        for (let j = (i+1); j < financingList.length; j++) {
            count += financingList[j].financingAmount;
            if ((financingList[j]._id - _id) > 1) {
                break;
            }
        }
        if (count >= 10000000) {
            state = true;
            break;
        }
    }
    return state;
}