

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

const caishouSchema = new Schema({
    csId:{type:String, index:true},//
    dIdList:{type:[String]}, //地块id
    plantType:Number, //种植种类【枚举】 PLANTTYPE
    weight:Number,//采收重量
    operationTime:Number,//采收时间 时间戳
    ct:Number,//创建时间
    createUser:String,//创建人
});

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

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

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

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


export async function selectChanLiangOfMonth(param) {
    return await caishouModel.aggregate([
        { $match: param },
        {
          $group: {
            _id: {
              year: { $year: { date: { $toDate: "$operationTime" }, timezone: "UTC" } },
              month: { $month: { date: { $toDate: "$operationTime" }, timezone: "UTC" } }
            },
            totalWeight: { $sum: "$weight" }
          }
        },
        {
          $project: {
            _id: 0,
            year: "$_id.year",
            month: "$_id.month",
            totalWeight: 1
          }
        },
        {
          $sort: { year: 1, month: 1 }
        }
      ]);
}

export async function selectChanLiangOfzuoWu(param) {
    return await caishouModel.aggregate([
       { $match: param },
        {
          $group: {
            _id:"$plantType",
            totalWeight: { $sum: "$weight" }
          }
        }]);
}
