/**
 * 企业经营数据补充表
 */

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

const replenishSchema = new Schema({
    year:{type:Number, index:true},//年度
    quarter:{type:Number, index:true},//季度
    uscc:{type:String, index:true},
    type:Number,
    value:Number,
    timeMs:Number,//填写时间
});

var replenishDataModel;
export function initModel(){
    replenishDataModel = baseDB.model('replenish', replenishSchema);
    replenishDataModel.selectOnceData = async function (paramater:object) {
        let selectInfo = await replenishDataModel.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 季度
 * @param type 类型
 * @param value 值
 */
export async function replenishData(uscc:string, year:number, quarter:number, type:number, value:number) {
    let addInfo = {uscc, year, quarter, type, value, timeMs:new Date().valueOf() };
    await replenishDataModel.create(addInfo);
}

export async function selectRepleishData(uscc:string, year:number) {
    return await replenishDataModel.find({uscc, year});
}

export async function selectOnceRepleishData(uscc:string, type:number, year:number, quarter:number ) {
    return await replenishDataModel.selectOnceData({uscc, year, type, quarter});
}


export async function findRepleishDataByTypeAndYear(uscc:string, type:number, year:number) {
    return await replenishDataModel.find({uscc, type, year});
}

export async function findReplenishBusinessDataByYear(uscc:string, startYear:number, endYear:number) {
    let dataList = await replenishDataModel.find({"$or":[{year:startYear}, {year:endYear}], uscc, type:BUSINESSDATATYPE.营业收入});
    let count = 0;
    dataList.forEach(info => {
        let {value} = info;
        if (value) count += value;
    });

    return count;
}

export async function findReplenishDataByParam(param) {
    return await replenishDataModel.find(param);
}