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

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

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

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 findBusinessDataByParams(param) {
    return await businessDataModel.find(param);
}


export async function addManyBusinessData(addList) {
    await businessDataModel.insertMany(addList);
}

/**
 * 查询特定时间的企业经营数据总和
 * @param year 年度
 * @param quarter 季度
 * @returns 
 */
export async function findBusinessDataCountByTime(year:number, quarter:number) {
    return await businessDataModel.find({year, quarter}).count();
}