/**
 * 
 * 
 */

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

const zhongzhiSchema = new Schema({
    zId:{type:String, index:true},//
    size:Number, //种植面积
    plantType:Number, //种植种类【枚举】 PLANTTYPE
    dId:String, //地块id
    plantTime:Number, //种植时间
    uId:String,//用户id
    isEnd:{type:Number, default:0},//是否结束  0=否 1=是
    ct:Number,
    csId:String,//采收id
});

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

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

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

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

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

export async function updateManyToParam(param, updateInfo) {
    return await zhongzhiModel.updateMany(param, {"$set":updateInfo});
}

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


export async function deleteData(param) {
    return await zhongzhiModel.deleteOne(param);
}

export async function pingZhongCount(param) {
    let list = await zhongzhiModel.aggregate([
        { $match: param },
        {
            "$group":{
                _id:"$plantType",
                count:{"$sum":1}
            }
        }
    ]);

    return list;
}


export async function zhongZhiTongJiCount(param) {
    let list = await zhongzhiModel.aggregate([
        { $match: param },
        {
            "$group":{
                _id:"$plantType",
                sizeCount:{"$sum":"$size"}
            }
        }
    ]);

    return list;
}


export async function zhongYangTongJiCount() {
    let list = await zhongzhiModel.aggregate([
        { $match: { plantType:{"$gt":100, "$lt":200} } },
        {
            "$group":{
                _id:"$plantType",
                sizeCount:{"$sum":"$size"}
            }
        }
    ]);

    return list;
}

