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

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


/**
 * 获取时间段的补录数据列表
 * @param uscc 
 * @param year 
 * @returns 
 */
export async function selectRepleishData(uscc:string, year:number) {
    return await replenishDataModel.find({uscc, year});
}


/**
 * 根据条件获取单个补录数据 可save保存
 * @param uscc 
 * @param type 
 * @param year 
 * @param quarter 
 * @returns 
 */
export async function selectOnceRepleishData(uscc:string, type:number, year:number, quarter:number ) {
    return await replenishDataModel.selectOnceData({uscc, year, type, quarter});
}


/**
 * 获取特定企业下的特定时间特定类型的数据 不支持save保存
 * @param uscc 
 * @param type 
 * @param year 
 * @returns 
 */
export async function findRepleishDataByTypeAndYear(uscc:string, type:number, year:number) {
    return await replenishDataModel.find({uscc, type, year});
}


/**
 * 获取企业在某年度的经营数据
 * @param uscc 
 * @param startYear 
 * @param endYear 
 * @returns 
 */
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;
}


/**
 * 获取符合条件的列表
 * @param param 
 * @returns 
 */
export async function findReplenishDataByParam(param) {
    return await replenishDataModel.find(param);
}