/**
 * 种养
 */

import moment = require("moment");
import { TABLENAME } from "../../config/dbEnum";
import { DiKuaiConfig, ZhongYangConfig } from "../../config/eccParam";
import { PLANTTYPE, PLOTTYPE, XIAOSHOUQUXIANG, ZHONGYANGTYPE } from "../../config/enum";
import * as zhongzhiData from "../../data/zhongzhi";
import * as xiaoshouData from "../../data/xiaoshou";
import * as dikuaiData from "../../data/dikuai";
import { randomId, successResult } from "../../tools/system";
import { changeEnumValue, eccEnumValue } from "../../util/verificationEnum";
import { eccFormParam } from "../../util/verificationParam";
import { BizError } from "../../util/bizError";
import { ERRORENUM } from "../../config/errorEnum";

/**
 * 种养列表
 * @param plantType 种养类型
 * @param selectStr 
 * @returns 
 */
export async function zhongYangDangQianList(zhongYangType:number, selectStr:string) {
    let funName = `当前种养列表`;
    eccEnumValue(funName, 'zhongYangType', ZHONGYANGTYPE, zhongYangType);

    let param = {
        plantType:{"$gte":zhongYangType, "$lt":zhongYangType+99},
        isEnd:0
    };
    let zyList = await zhongzhiData.selectToParam( param );
    
    let typeMap = {};
    zyList.forEach(info => {
        let {plantType} = info;
        typeMap[plantType] = {value:plantType, key:changeEnumValue(PLANTTYPE, plantType)};
    });
    let dataList = Object.values(typeMap);

    return {dataList};
}


/**
 * 种养列表-分页 暂无使用
 * @param zhongYangType 
 * @param selectStr 
 * @param pageNumber 
 * @returns 
 */
export async function zhongYangDangQianListToPage(zhongYangType:number, selectStr:string, pageNumber) {
    let funName = `当前种养列表`;
    let param:any = { };
    if (zhongYangType) {
        eccEnumValue(funName, 'zhongYangType', ZHONGYANGTYPE, zhongYangType);
        param.plantType = {"$gte":zhongYangType, "$lt":zhongYangType+99};
    }

    let zyList = await zhongzhiData.findDataToParamToSortPage( param, {plantTime:-1}, pageNumber );
    let dataCount = await zhongzhiData.findDataToParamCouant(param);
    let dataList = [];
    zyList.forEach(info => {
        let addInfo = {
            zId : info.zId,
            size : info.size,
            plantType : info.plantType,
            dId : info.dId,
            plantTime : info.plantTime
        };
        dataList.push(addInfo);
    });

    return {dataList, dataCount};
}


/**
 * 删除种养 暂无使用
 * @param zId 
 * @returns 
 */
export async function deleteZhongYang(zId) {
    let zhongYangInfo = await zhongzhiData.selectOne({zId});
    if (!zhongYangInfo || !zhongYangInfo.zId) throw new BizError(ERRORENUM.数据不存在);

    await zhongzhiData.deleteData({zId});

    return successResult();
}


/**
 * 添加种养
 * @param reqUser 
 * @param param 
 * @returns 
 */
export async function addZhongYang(reqUser, param) {
    let funName = `添加种养`;
    eccFormParam(funName, ZhongYangConfig, param);
    eccEnumValue(funName, "plantType", PLANTTYPE, param.plantType);

    //校验地块大小是否符合扣除
    let dkInfo = await dikuaiData.selectOne({dId:param.dId});
    if (!dkInfo || !dkInfo.dId) throw new BizError(ERRORENUM.地块不存在);
    if (param.plantType < PLANTTYPE.鲈鱼 && param.plantType > PLANTTYPE.水稻 ) {
        if (dkInfo.size < param.size) throw new BizError(ERRORENUM.地块大小不足);
    }

    let addInfo = {
        zId:randomId(TABLENAME.种植表),
        size:param.size,//种植大小
        plantType:param.plantType,//
        dId:param.dId,//地块id
        plantTime:param.plantTime,//种植时间
        uId:reqUser.userId,
        isEnd:0,
        ct:new Date().valueOf()
    };

    await zhongzhiData.addData(addInfo);

    dkInfo.nullSize = dkInfo.size - param.size;
    dkInfo.useSize = dkInfo.useSize + param.size;
    await dkInfo.save();

    return successResult();
}


/**
 * 修改种养 暂无使用
 * @param reqUser 
 * @param zId 
 * @param param 
 * @returns 
 */
export async function updateZhongYang(reqUser, zId, param) {
    let funName = `修改种养`;
    eccFormParam(funName, ZhongYangConfig, param);
    eccEnumValue(funName, "plantType", PLANTTYPE, param.plantType);

    let dkInfo = await dikuaiData.selectOne({dId:param.dId});
    if (!dkInfo || !dkInfo.dId) throw new BizError(ERRORENUM.地块不存在);
    if (dkInfo.size < param.size) throw new BizError(ERRORENUM.地块大小不足);

    let zhongYangInfo = await zhongzhiData.selectOne({zId});

    zhongYangInfo.plantType = param.plantType;
    zhongYangInfo.dId = param.dId;
    zhongYangInfo.size = param.size;
    zhongYangInfo.plantTime = param.plantTime;

    await zhongYangInfo.save();

    return successResult();
}


/**
 * 种养回显 暂无使用
 * @param zId 
 * @returns 
 */
export async function zhognYangInfo(zId) {
    let dikuaiInfo = await zhongzhiData.selectOne({zId});
    let dataInfo = {
        plantType:dikuaiInfo.plantType,//编号
        dId:dikuaiInfo.dId,//地块id
        size:dikuaiInfo.size,//地块大小
        plantTime:dikuaiInfo.plantTime,//种植时间
    };

    return {dataInfo}
}


/**
 * 种养记录
 * @param zhongYangType 
 * @param selectStr 
 * @param plantType 
 * @param plantTime 
 * @param dId 
 * @returns 
 */
export async function zhongYangJiLu(zhongYangType:number, selectStr:string, plantType:number, plantTime:number, dId:string) {
    let funName = `种养记录`;
 
    let param:any = { plantType:{"$gte":zhongYangType, "$lt":zhongYangType+99} };
    if (plantType) {
        eccEnumValue(funName, "plantType", PLANTTYPE, plantType);
        param.plantType = plantType;
    }
    if (dId) {
        param.dId = dId;
    }
    if (plantTime) {
        let selectStartTime = moment(plantTime).startOf('day').valueOf();
        let selectEndTime = moment(plantTime).endOf("day").valueOf();
        param.plantTime = {"$gte":selectStartTime, "$lte":selectEndTime};
    }
    
    /**获取地块名称 */
    let dikuaiList = await dikuaiData.selectToParam({});
    let diKuaiMap = {};
    dikuaiList.forEach(info => {
        let {dId, code} = info;
        diKuaiMap[dId] = code;
    });

    let dbList = await zhongzhiData.selectToParam(param);
    let dataList = [];
    dbList.forEach(info => {
        dataList.push({
            plantType:changeEnumValue(PLANTTYPE, info.plantType),
            size:info.size,
            code:diKuaiMap[info.dId],
            plantTime:moment(info.plantTime).format("YYYY-MM-DD"),
            plantTimeNum:info.plantTime
        })
    });

    dataList.sort( (a, b) => {
        return b.plantTimeNum - a.plantTimeNum;
    })

    return {dataList};
}



/** =================================供大屏使用==================================== */

/**
 * 种养列表
 * @param zhongYangType
 * @returns 
 */
// export async function zhongYangList(zhongYangType:number) {
//     let funName = `当前种养列表`;
//     let param:any = { };
//     // let startTime = moment().subtract(1, 'month').startOf('month').valueOf();
//     // let endTime = moment().subtract(1, 'month').endOf('month').valueOf();
//     let startTime = moment().subtract(90, 'days').startOf('day').valueOf();
//     let endTime = moment().endOf('day').valueOf();
//     if (zhongYangType) {
//         eccEnumValue(funName, 'zhongYangType', ZHONGYANGTYPE, zhongYangType);
//         param.plantType = {"$gte":zhongYangType, "$lt":zhongYangType+99};
//         param.isEnd = 0;
//         param.plantTime = {"$gte":startTime, "$lte":endTime}
//     }

//     let zyList = await zhongzhiData.selectToParam(param);
//     let dataInfo = {};
//     zyList.forEach(info => {
//         let addInfo = {
//             size : info.size,
//             plantType : changeEnumValue(PLANTTYPE, info.plantType),
//             plantTime : moment(info.plantTime).format("YYYY-MM-DD"),
//         };

//         let plantType = changeEnumValue(PLANTTYPE, info.plantType);

//         if (!dataInfo[plantType]) dataInfo[plantType] = [];
//         dataInfo[plantType].push(addInfo);
//     });
    
//     let dataList = [];
//     let unit = "亩";
//     if (zhongYangType == ZHONGYANGTYPE.水产) unit = "万尾";

//     for (let key in dataInfo) {
//         let size = 0;
//         let zhongyang = dataInfo[key];
//         zhongyang.forEach(item => {
//             size += item.size;
//         });

//         dataList.push({
//             key:key,
//             value:Math.round(size*100)/100,
//             unit
//         });
//     }

//     dataList.sort((a, b) => {
//         return b.value - a.value;
//     })

//     return dataList.slice(0, 10);
// }


/**
 * 种养列表
 * @param zhongYangType
 * @returns 
 */
export async function zhongYangList(zhongYangType:number) {
    let funName = `当前种养列表`;
    let param:any = { };
    
    // 根据种养类型设置不同的时间范围
    let startTime, endTime;
    
    if (zhongYangType === ZHONGYANGTYPE.水产) {
        // 水产类型：获取近一年的数据
        startTime = moment().subtract(1, 'year').startOf('day').valueOf();
        endTime = moment().endOf('day').valueOf();
    } else {
        // 其他类型：保持原来的90天范围
        startTime = moment().subtract(90, 'days').startOf('day').valueOf();
        endTime = moment().endOf('day').valueOf();
    }
    
    if (zhongYangType) {
        eccEnumValue(funName, 'zhongYangType', ZHONGYANGTYPE, zhongYangType);
        param.plantType = {"$gte":zhongYangType, "$lt":zhongYangType+99};
        param.isEnd = 0;
        param.plantTime = {"$gte":startTime, "$lte":endTime}
    }

    let zyList = await zhongzhiData.selectToParam(param);
    let dataInfo = {};
    zyList.forEach(info => {
        let addInfo = {
            size : info.size,
            plantType : changeEnumValue(PLANTTYPE, info.plantType),
            plantTime : moment(info.plantTime).format("YYYY-MM-DD"),
        };

        let plantType = changeEnumValue(PLANTTYPE, info.plantType);

        if (!dataInfo[plantType]) dataInfo[plantType] = [];
        dataInfo[plantType].push(addInfo);
    });
    
    let dataList = [];
    let unit = "亩";
    if (zhongYangType == ZHONGYANGTYPE.水产) unit = "万尾";

    for (let key in dataInfo) {
        let size = 0;
        let zhongyang = dataInfo[key];
        zhongyang.forEach(item => {
            size += item.size;
        });

        dataList.push({
            key:key,
            value:Math.round(size*100)/100,
            unit
        });
    }

    dataList.sort((a, b) => {
        return b.value - a.value;
    })

    return dataList.slice(0, 10);
}


/**
 * 鱼苗数据
 * @returns 
 */
export async function yuMiaoList() {
    /**鱼苗销售记录 */
    let param:any = {};
    param.plantType = {"$gte":PLANTTYPE.鲈鱼, "$lt":PLANTTYPE.水稻};

    // let lastMonth = moment().subtract(1, 'years').format('YYYY-MM-DD');
    // let startMs = moment(lastMonth).startOf("day").valueOf();
    // let endMs = moment(new Date()).endOf("day").valueOf();
    // param.operationTime = {"$gte":startMs, "$lte":endMs};

    let xiaoShouData = await xiaoshouData.selectToParam(param);
    console.log(`xiaoShouData: ${JSON.stringify(xiaoShouData)}`);
    xiaoShouData.sort( (a, b) => {
        return b.operationTime - a.operationTime;
    })

    let xiaoShouList = [];
    xiaoShouData.forEach(item => {
        let {plantType, quXiang, operationTime, weight } = item;
        
        xiaoShouList.push({
            plantType:changeEnumValue(PLANTTYPE, plantType),
            quXiang:changeEnumValue(XIAOSHOUQUXIANG, quXiang),
            weight,
            unit:"尾",
            operationTime:moment(operationTime).format("YYYY-MM-DD"),
        });
    });

    /**鱼苗养殖记录 */
    let param2:any = {};
    param2.plantType = {"$gte":PLANTTYPE.鲈鱼, "$lt":PLANTTYPE.水稻};
    param2.isEnd = 0;
    // param2.plantTime = {"$gte":startMs, "$lte":endMs};
    let yangZhiData = await zhongzhiData.selectToParam(param2);
    let yangZhiList = [];
    yangZhiData.forEach(item => {
        let {plantType, size, plantTime } = item;
        
        yangZhiList.push({
            plantType:changeEnumValue(PLANTTYPE, plantType),
            size,
            plantTime:moment(plantTime).format("YYYY-MM-DD"),
            plantTimeNum:plantTime
        });
    });

    yangZhiList.sort( (a, b) => {
        return b.plantTimeNum - a.plantTimeNum;
    })

    /**各类鱼苗库存数量：养殖-销售 */
    let kuCunData = calculateKuCun(yangZhiList, xiaoShouList);
    
    let dataList = {
        鱼苗销售记录:xiaoShouList,
        鱼苗养殖记录:yangZhiList,
        鱼苗库存数据:kuCunData
    }

    return dataList;
}


/**
 * 计算各类鱼苗库存
 * @param {Array} yangZhiList 养殖记录
 * @param {Array} xiaoShouList 销售记录
 * @returns {Array} 库存数据
 */
function calculateKuCun(yangZhiList, xiaoShouList) {
    // 按鱼苗类型统计总养殖量
    let yangZhiTotal = {};
    yangZhiList.forEach(item => {
        const type = item.plantType;
        const size = parseFloat(item.size) || 0;
        if (!yangZhiTotal[type]) {
            yangZhiTotal[type] = 0;
        }
        yangZhiTotal[type] += size;
    });

    // 按鱼苗类型统计总销售量
    let xiaoShouTotal = {};
    xiaoShouList.forEach(item => {
        const type = item.plantType;
        const weight = parseFloat(item.weight) * 10000 || 0; //单位转换为万尾
        if (!xiaoShouTotal[type]) {
            xiaoShouTotal[type] = 0;
        }
        xiaoShouTotal[type] += weight;
    });

    // 计算库存并格式化结果
    let kuCunList = [];
    const allTypes = new Set([
        ...Object.keys(yangZhiTotal),
        ...Object.keys(xiaoShouTotal)
    ]);

    allTypes.forEach(type => {
        const yangZhi = yangZhiTotal[type] || 0;
        const xiaoShou = xiaoShouTotal[type] || 0;
        let kuCun = yangZhi - xiaoShou;
        
        // 如果库存为负数，直接置零
        if (kuCun < 0) {
            kuCun = 0;
        }
        
        kuCunList.push({
            plantType: type,
            yangZhiTotal: yangZhi,
            xiaoShouTotal: xiaoShou,
            kuCun: kuCun,
            unit: "万尾",
            updateTime: moment().format("YYYY-MM-DD HH:mm:ss")
        });
    });

    // 按库存量降序排列
    kuCunList.sort((a, b) => b.kuCun - a.kuCun);

    return kuCunList;
}




