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

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

const nongshiSchema = new Schema({
    nsId: {type:String, index:true},//,
    nsType:Number, //农事类型
    dIdList:{type:[String], default:[]}, //地块id
    operationTime:Number,//操作时间
    ct:Number,//创建时间
});

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

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


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

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

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


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

    return list;
}