/**
 * 种植
 */

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 findDataToParamToSortPage(param, sort, pageNumber) {
    return await zhongzhiModel.find(param).sort(sort).skip((pageNumber-1)*10).limit(10);
}

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;
}


/**
 * 按年份统计种植面积
 * @param year 年份，可选
 * @returns 按种植类型分组的面积统计
 */
export async function zhongYangTongJiCountByYear(year?: number) {
    // 构建基础查询条件
    let matchCondition: any = { plantType: {"$gt": 100, "$lt": 200} };
    
    // 如果传入了年份参数，添加时间过滤
    if (year) {
        const startTime = new Date(year, 0, 1).getTime();    // 年份开始时间戳
        const endTime = new Date(year + 1, 0, 1).getTime();  // 年份结束时间戳
        
        matchCondition.plantTime = {
            "$gte": startTime,
            "$lt": endTime
        };
    }
    
    let list = await zhongzhiModel.aggregate([
        { $match: matchCondition },
        {
            "$group": {
                _id: "$plantType",
                sizeCount: {"$sum": "$size"}
            }
        }
    ]);

    return list;
}


/**
 * 按年份统计种植数量
 * @param year 年份，可选
 * @returns 按种植类型分组的数量统计
 */
export async function pingZhongCountByYear(year?: number) {
    let matchCondition: any = {};
    
    // 如果传入了年份参数，添加时间过滤
    if (year) {
        const startTime = new Date(year, 0, 1).getTime();    // 年份开始时间戳
        const endTime = new Date(year + 1, 0, 1).getTime();  // 年份结束时间戳
        
        matchCondition.plantTime = {
            "$gte": startTime,
            "$lt": endTime
        };
    }
    
    let list = await zhongzhiModel.aggregate([
        { $match: matchCondition },
        {
            "$group": {
                _id: "$plantType",
                count: {"$sum": 1}
            }
        }
    ]);

    return list;
}





