/**
 * 数据接口输出
 */

import moment = require("moment");
import { LIANGSHI, NONGZITYPE, PLANTTYPE, PLOTTYPE, XIAOSHOUQUXIANG } from "../config/enum";
import { diKuaiSizeCountByParam } from "../data/dikuai";
import * as nongziData from "../data/nongzi";
import { zhongYangTongJiCount, zhongZhiTongJiCount } from "../data/zhongzhi"
import * as nongshiData from "../data/nongshi"
import * as xiaoshouData from "../data/xiaoshou"
import * as caishouData from "../data/caishou"
import { changeEnumValue } from "../util/verificationEnum";
import { selectChanLiangOfMonth } from "../data/caishou";



export async function getDataOut() {
    let 种植总面积 = 0;
    let 粮田面积 = 0;
    let 菜田面积 = 0;
    let 作物数量 = 0; isEnd: 0

    let zhongZhiList = await zhongZhiTongJiCount({ isEnd: 0, plantType:{"$lt":PLANTTYPE.鲈鱼}});
    let zhongZhiZuoWuList = []; //结果
    zhongZhiList.forEach(info => {
        let {_id, sizeCount} = info;
        种植总面积 += sizeCount;
        if (_id == LIANGSHI.水稻 || _id == LIANGSHI.蚕豆) {
            粮田面积 += sizeCount;
        } else if (_id < 100) {
            菜田面积 += sizeCount;
        }
        if ( !(_id > 100 && _id < 200)) {
            作物数量 += 1;
            zhongZhiZuoWuList.push({key:changeEnumValue(PLANTTYPE, _id), value:sizeCount});
        }
    });

    let diKuaiInfo = await diKuaiSizeCountByParam({plotType:PLOTTYPE.地块});
    let 地块使用率 = 0;
    if (diKuaiInfo.totalSize && diKuaiInfo.totalUseSize) {
        地块使用率 = Math.round(diKuaiInfo.totalUseSize/diKuaiInfo.totalSize * 100);
    }
    let zhongZhiTypeList = [
        {key:"种植总面积", value:731},//种植总面积
        {key:"菜田面积", value:370},//菜田面积
        {key:"粮田面积", value:361},
        {key:"作物数量", value:作物数量},
        {key:"地块使用率", value:地块使用率},
    ]; //结果

    let 农资类型 = await nongziData.statisNongZiType();
    let 农资情况Map = {};
    农资情况Map[NONGZITYPE.肥料] = {key:changeEnumValue(NONGZITYPE, NONGZITYPE.肥料), value:0, unit:"KG"};
    农资情况Map[NONGZITYPE.农药] = {key:changeEnumValue(NONGZITYPE, NONGZITYPE.农药), value:0, unit:"G"};
    农资情况Map[NONGZITYPE.药剂] = {key:changeEnumValue(NONGZITYPE, NONGZITYPE.药剂), value:0, unit:"ML"};
    农资类型.forEach(info => {
        let {_id, count} = info;
        switch (_id) {
            case NONGZITYPE.磷肥:
            case NONGZITYPE.水溶肥:
            case NONGZITYPE.有机肥:
            case NONGZITYPE.复合肥:农资情况Map[NONGZITYPE.肥料].value += count;break;
            case NONGZITYPE.好力克:
            case NONGZITYPE.奥罗:
            case NONGZITYPE.银法利:
            case NONGZITYPE.啶虫脒:
            case NONGZITYPE.龙克均:
            case NONGZITYPE.三令: 农资情况Map[NONGZITYPE.药剂].value += count; break;
            case NONGZITYPE.追肥保果素:农资情况Map[NONGZITYPE.农药].value += count;break; 
        }
    });
    let nongZiList = Object.values(农资情况Map); //结果


    let nongZiAllMonthList = await nongziData.selectToParam({});
    let nongZiCountInfo = {};//肥料用药情况
    nongZiCountInfo[NONGZITYPE.农药] = {};
    nongZiCountInfo[NONGZITYPE.肥料] = {};
    // let lastMonthMs = moment().startOf('M').valueOf()
    nongZiAllMonthList.forEach(info => {
        let {useTime, count, nzType} = info;
        // if (useTime < lastMonthMs ) return
        let keyNum = 1;
        switch (nzType) {
            case NONGZITYPE.磷肥:
            case NONGZITYPE.水溶肥:
            case NONGZITYPE.有机肥:
            case NONGZITYPE.复合肥:keyNum = NONGZITYPE.肥料; break;
             case NONGZITYPE.好力克:
            case NONGZITYPE.奥罗:
            case NONGZITYPE.银法利:
            case NONGZITYPE.啶虫脒:
            case NONGZITYPE.龙克均:
            case NONGZITYPE.三令:
            case NONGZITYPE.追肥保果素:keyNum = NONGZITYPE.农药; break; 
        }
        if (nongZiCountInfo[keyNum]) {
            let keyStr = getKey(useTime);
            if (!nongZiCountInfo[keyNum][keyStr]) nongZiCountInfo[keyNum][keyStr] = 0;
            nongZiCountInfo[keyNum][keyStr] += count;
        };
    });
    let 肥料  = [];
    let 用药 = [];
    let allKeyList = getAllKey(new Date().valueOf());
    for (let i = 0; i < allKeyList.length; i++) {
        let key = allKeyList[i];
        肥料.push({
            key,
            value:nongZiCountInfo[NONGZITYPE.肥料][key] || 0
        });
        用药.push({
            key,
            value:nongZiCountInfo[NONGZITYPE.农药][key] || 0
        });
    }
    let feiliaoyongyaoqingkuang = [ //结果
        {name:"肥料", data:肥料},
        {name:"用药", data:用药},
    ];
 
    let nongShiCount = await nongshiData.selectCountByParam({}); //结果
    let nongshiTyptList = await nongshiData.selectToParam({});
    let 操作趋势 = {};
    let nongShiList = [];//结果
    nongshiTyptList.forEach(info => {
        let {nsType, operationTime} = info;
        let key = getKey(operationTime);
        
        if (!操作趋势[key]) 操作趋势[key] = 0;
        操作趋势[key] += 1;;
    });
    for (let i= 0; i < allKeyList.length; i++) {
        let key = allKeyList[i];
        nongShiList.push({
            key,
            value:操作趋势[key] || 0
        });
    }


    let monthDBList = await caishouData.selectToParam({plantType:{"$lt":PLANTTYPE.鲈鱼}});
    let 作物产量Map = {};
    let 今年产量总数 = 0;
    monthDBList.forEach(info => {
        let {ct, weight} = info;
        if (new Date(ct).getFullYear() == 2025) 今年产量总数 += weight;
        let key = getKey(ct)
        if (!作物产量Map[key]) 作物产量Map[key] = 0;
        作物产量Map[key] += weight;

    });

    let 今年 = [];
    let 去年 = [];
 
   
    let 去年产量总数 = 0;
    for (let i =0 ; i < allKeyList.length; i++) {
        let key = allKeyList[i];
        let changeValue = 作物产量Map[key] ? Math.round(作物产量Map[key]/1000*100)/100 : 0;
        今年.push({key: key, value:changeValue || 0 });
        去年.push({key: key, value:0 });
    }
    let chanLiangList = [ //结果
        {name:"今年", data:今年},
        {name:"去年", data:去年},
    ];

    let 产量年同比 = 0;
    if (今年产量总数 && 去年产量总数)  {
        产量年同比 = Math.round((今年产量总数 - 去年产量总数)/ 去年产量总数*10000)/100
    }
    let chanLiangStatisList = [//结果
        {key:"作物产量", value:Math.round(今年产量总数/1000*100)/100},
        {key:"同比", value:产量年同比}
    ];

    let xiaoshouStartMs = moment().subtract(1, "months").startOf('month').valueOf();
    let xiaoshouEndMs = moment().startOf('month').valueOf();
    let xiaoshouDBList = await xiaoshouData.selectToParam({});

    let lastMonthXiaoShou = 0;
    let lastMonthXiaoShouMap = {};
    xiaoshouDBList.forEach(info => {
        let {operationTime, weight} = info;
        lastMonthXiaoShou += weight;
        let key = getKey(operationTime);
        if (!lastMonthXiaoShouMap[key]) lastMonthXiaoShouMap[key] = 0;
        lastMonthXiaoShouMap[key] += weight;
    });
    // let lastMonthXiaoShouList = Object.values(lastMonthXiaoShouMap);//结果
    let lastMonthXiaoShouList = [];
    let allxiaoshouKeyList = getAllKey(new Date().valueOf());
    for (let i = 0; i < allxiaoshouKeyList.length; i++) {
        let key = allxiaoshouKeyList[i];
        let value = lastMonthXiaoShouMap[key] || 0;

        lastMonthXiaoShouList.push({
            key,
            value:Math.round(value/1000*100)/100,
        })

    }
    return {
        zhongZhiZuoWuList,
        zhongZhiTypeList,
        nongZiList,
        feiliaoyongyaoqingkuang,
        nongShiList,
        nongShiCount,
        chanLiangList,
        chanLiangStatisList,
        lastMonthXiaoShou:Math.round(lastMonthXiaoShou/1000*100)/100,
        lastMonthXiaoShouList
    }

}

function getKey(timestamp) {
     const date = new Date(timestamp);
  
  // 计算当前时间所在周期的周一（UTC时间）
  const day = date.getUTCDay(); // 0（周日）到6（周六）
  const diff = day === 0 ? 6 : day - 1; // 计算到上周一的差值
  const start = new Date(date);
  start.setUTCDate(start.getUTCDate() - diff); // 回退到周一
  start.setUTCHours(0, 0, 0, 0); // 设置为UTC零点

  // 计算周期结束时间（周日）
  const end = new Date(start);
  end.setUTCDate(end.getUTCDate() + 6); // 周一 + 6天 = 周日
  end.setUTCHours(23, 59, 59, 999); // 设置为周日最后一刻（可选）

  
  return `${moment(start).format("M/D")}-${moment(end).format("M/D")}`;
}

function getAllKey(timestamp) {
    let cycles = [];
   for (let i = 7; i >=0 ; i--) {
        let ms = moment(timestamp).subtract(i*7, 'd').valueOf();
        cycles.push(getKey(ms))
   } 
  return cycles;
}

export async function getGuiYuOut() {
    let zhongZhiList = await zhongYangTongJiCount();

    let ymyzsl = [];
    let count = 0;
    let kcMap = {};
    zhongZhiList.forEach(info => {
        let {_id, sizeCount} = info;
        ymyzsl.push({
            key:changeEnumValue(PLANTTYPE, _id),
            value:`${sizeCount}万尾`
        });
        count += sizeCount;
        if (!kcMap[_id]) kcMap[_id] = 0
        kcMap[_id] += (info.sizeCount * 10000);
    });

    let scyz = [
        // {key:"养殖面积", value:'0亩'},
        {key:"鱼苗养殖", value:`${count}万尾`},
    ];

   

    let xiaoshouList = await xiaoshouData.selectToParam({plantType:{"$gt":100, "$lt":200}});
    let xsjl = [];
    xiaoshouList.forEach(info => {
        let subList = [
            changeEnumValue(PLANTTYPE, info.plantType),
            changeEnumValue(XIAOSHOUQUXIANG, info.quXiang),
            info.weight,
            '尾',
            moment(info.operationTime).format("YYYY-MM-DD")
        ];
        xsjl.push(subList);
        if (kcMap[info.plantType]) {
            kcMap[info.plantType] -= info.weight;
        }
    });

    let kcjlData = [];
    for (let key in kcMap ) {
        if (kcMap[key] > 0) {
            kcjlData.push({
                key:changeEnumValue(PLANTTYPE, parseInt(key)),
                value:`${Math.ceil(kcMap[key]/1000000)*100}尾`
            })
        }
    }

    return {kcjlData, scyz, ymyzsl, xsjl};
}
