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

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

const nongziSchema = new Schema({
    nzId: {type:String, index:true},//,
    nzType:Number, //农资类型 
    dIdList:{type:[String], default:[]}, //地块id
    plantType:Number, //作物名称【枚举】 PLANTTYPE
    count:Number,//用量
    useTime:Number,//使用时间
    ct:Number,//创建时间
});

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

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

export async function findOne(param) {
    return await nongziModel.selectOnceData(param);
}

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

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


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

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



export async function statisNongZiType() {
    let list = await nongziModel.aggregate([
        {
            "$group":{
                _id:"$nzType",
                count:{"$sum":1}
            }
        }
    ]);

    return list;
}


export async function statisNongZiTypeCountByTime() {
    let list = await nongziModel.aggregate([
        {
            $group: {
                _id: {
                    year: { $year: { date: { $toDate: "$useTime" }, timezone: "UTC" } },
                    month: { $month: { date: { $toDate: "$useTime" }, timezone: "UTC" } },
                    nzType:"$nzType"
                },
                totalWeight: { $sum: "$count" }
            }
        },
        {
            $project: {
                _id: 0,
                year: "$_id.year",
                month: "$_id.month",
                nzType:"$_id.nzType",
                totalWeight: 1
            }
        },
        {
            $sort: { year: 1, month: 1 }
        }
    ]);

    return list;
}