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

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

const dikuaiSchema = new Schema({
    dId: {type:String, index:true},//
    size: Number, //地块大小
    useSize: Number, //使用大小
    nullSize:Number,//可使用大小
    code:String, //编号
    name:String, //地块名称 同code
    area:String,//地块区域
    plotType:Number, //地块类型 【枚举】  PLOTTYPE
    purpose:Number,//用途 【枚举】 PURPOSE
    createUser:String, //创建人
    ct:Number,//创建时间
});

var dikuaiModel;
export function initModel(){
    dikuaiModel = baseDB.model('dikuai', dikuaiSchema);
    dikuaiModel.selectOnceData = async function (paramater:object) {
        let selectInfo = await dikuaiModel.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 addData(param) {
    return await dikuaiModel.create(param);
}

export async function addManyData(param) {
    return await dikuaiModel.insertMany(param);
}

export async function selectOne(param) {
    return await dikuaiModel.selectOnceData(param);
}

export async function selectToParam(param) {
    return await dikuaiModel.find(param);
}

export async function findDataToParamToSortPage(param, sort, pageNumber) {
    return await dikuaiModel.find(param).sort(sort).skip((pageNumber-1)*10).limit(10);
}

export async function findDataToParamToPage(param, pageNumber) {
    return await dikuaiModel.find(param).skip((pageNumber-1)*10).limit(10);
}

export async function findDataToParamCouant(param) {
    return await dikuaiModel.find(param).countDocuments();
}


export async function diKuaiSizeCount(param) {
    let list = await dikuaiModel.aggregate([
        { $match: param },
        {
            "$group":{
                _id:null,
                totalSize:{"$sum":"$size"},
                totalUseSize:{"$sum":"$useSize"}
            }
        }
    ]);

    return list[0];
}


export async function diKuaiSizeCountByParam(param) {
    let list = await dikuaiModel.aggregate([
        { $match: param },
        {
            "$group":{
                _id:null,
                totalSize:{"$sum":"$size"},
                totalUseSize:{"$sum":"$useSize"}
            }
        }
    ]);

    return list[0];
}
