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

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

const xiaoshouSchema = new Schema({
    xsId: {type:String, index:true},//,
    plantType:Number, //种植种类【枚举】 PLANTTYPE
    quXiang:Number,//销售去向
    weight:Number,//重量
    operationTime:Number,//销售时间
    ct:Number,//创建时间
    createUser:String,//创建人
});

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

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

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

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

export async function selectCountByParam(param) {
    return await xiaoshouModel.find(param).countDocuments();
}

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

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

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

export async function selectXiaoShouOfMonth(param) {
    return await xiaoshouModel.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 selectXiaoShouOfzuoWu(param) {
    return await xiaoshouModel.aggregate([
        { $match: param },
        {
            $group: {
            _id:"$plantType",
            totalWeight: { $sum: "$weight" }
            }
    }]);
}
