/**
 * 用户
 */


import { ERRORENUM } from "../../config/errorEnum";
import { findUserInfoByLoginId, findUserInfoByUserId } from "../../data/users";
import * as caishouData from "../../data/caishou";
import { getPwdMd5, getToken, successResult } from "../../tools/system";
import { BizError } from "../../util/bizError";
import * as diKuaiData from "../../data/dikuai";
import * as zhongZhiData from "../../data/zhongzhi";
import { selectChanLiangOfMonth, selectChanLiangOfzuoWu } from "../../data/caishou";
import { changeEnumValue } from "../../util/verificationEnum";
import { PLANTTYPE, PLOTTYPE } from "../../config/enum";
import { selectXiaoShouOfMonth, selectXiaoShouOfzuoWu } from "../../data/xiaoshou";
import moment = require("moment");


/**
 * 登录
 * @param loginId 
 * @param pwd 
 * @returns 
 */
export async function adminUserLogin(loginId:string, pwd:string) {
    let userInfo:any = await findUserInfoByLoginId(loginId);
    if (!userInfo || !userInfo.userId) throw new BizError(ERRORENUM.账号不存在, loginId);

    let checkPwd = getPwdMd5(loginId, pwd); 
    if (userInfo.pwd != checkPwd) throw new BizError(ERRORENUM.密码错误);

    let token = getToken(loginId);
    
    let resultUserInfo = {
        loginId:userInfo.loginId,
        name: userInfo.name,
        userId:userInfo.userId,
        token:token,
    };

    userInfo.adminToken = token;
    userInfo.adminTokenMs = new Date().valueOf();

    await userInfo.save();
    
    return {dataInfo:resultUserInfo};
}



/**
 * 登出
 * @param userInfo 
 */
export async function adminUserLogout(reqUserInfo) {
    let userInfo = await findUserInfoByUserId(reqUserInfo.userid);

    userInfo.adminToken = getToken(userInfo.loginId);
    userInfo.adminTokenMs = new Date().valueOf();

    await userInfo.save();

    return successResult(); 
}


/**
 * 统计页产量统计
 * @param type 统计类型：1-年，2-季度，3-月
 * @returns 
 */
export async function homePageStatisChanLiang(type:number) {
    //产量 时间分
    let zuoWuMonthDBList = await caishouData.selectToParam({plantType:{"$lt":PLANTTYPE.鲈鱼}});
    let zuoWuDistinctMap = {};
    let zuoWuCount = 0;

    let map1 = {};
    zuoWuMonthDBList.forEach(info => {
        let {ct, weight} = info;
        
        let year = moment(ct).year();
        let month = moment(ct).month() + 1;
        if (!map1[''+year+''+month]) map1[''+year+''+month] = {month, year, totalWeight:0}
        map1[''+year+''+month].totalWeight += weight;
    })

    let list1 =  Object.values(map1);
    list1.forEach(info => {
        let {year, month, totalWeight}:any = info;
        
        let strKey:any = "";
        if (type == 1) {//年
            strKey = year;
        } else if (type == 2) {//季度
            let quarter = 1;
            if (month >= 10) quarter = 4;
            else if (month >= 7) quarter = 3;
            else if (month >= 4) quarter = 2;
            strKey = `${year}-${quarter}`;
        } else {//月
            strKey = `${year}-${month}`;
        }

        if (!zuoWuDistinctMap[strKey]) zuoWuDistinctMap[strKey] = {key:strKey, value:0};
        zuoWuDistinctMap[strKey].value += totalWeight;

        zuoWuCount += totalWeight;
    });
    let nongChanPin = Object.values(zuoWuDistinctMap);

    for (let i = 0; i < nongChanPin.length; i++) {
        nongChanPin[i]["value"] =  Math.ceil(nongChanPin[i]["value"] / 10)/100;
    }
    //农作物产量
    let zuoWuDBList = await selectChanLiangOfzuoWu({plantType:{"$lt":PLANTTYPE.鲈鱼}});
    let zuoWu = [];
    zuoWuDBList.forEach(info => {
        let {_id, totalWeight} = info;
        zuoWu.push({
            key:changeEnumValue(PLANTTYPE, _id),
            value:totalWeight/1000
        });
    });
    zuoWu.sort((a,b) =>{return b.value - a.value});


    //产量 
    let shuiChanMonthDBList = await selectChanLiangOfMonth({plantType:{"$gte":PLANTTYPE.鲈鱼}});
    let shuiChanDistinctMap = {};
    let shuiChanCount = 0;
    shuiChanMonthDBList.forEach(info => {
        let {year, month, totalWeight} = info;
        
        let strKey = "";
        if (type == 1) {//年
            strKey = year;
        } else if (type == 2) {//季度
            let quarter = 1;
            if (month >= 10) quarter = 4;
            else if (month >= 7) quarter = 3;
            else if (month >= 4) quarter = 2;
            strKey = `${year}-${quarter}`;
        } else {//月
            strKey = `${year}-${month}`;
        }

        if (!shuiChanDistinctMap[strKey]) shuiChanDistinctMap[strKey] = {key:strKey, value:0};
        shuiChanDistinctMap[strKey].value += totalWeight;

        shuiChanCount += totalWeight;
    });
    let shuiChanPin = Object.values(shuiChanDistinctMap);

    for (let i = 0; i < nongChanPin.length; i++) {
        nongChanPin[i]["value"] =  Math.ceil(nongChanPin[i]["value"] / 100)/100;
    }
    //农作物产量
    let shuiChanDBList = await selectChanLiangOfzuoWu({plantType:{"$gte":PLANTTYPE.鲈鱼}});
    let shuiChan = [];
    shuiChanDBList.forEach(info => {
        let {_id, totalWeight} = info;
        shuiChan.push({
            key:changeEnumValue(PLANTTYPE, _id),
            value:totalWeight/10000
        });
    });
    shuiChan.sort((a,b) =>{return b.value - a.value});

    
    let shuiChanZhognYang = [];
    let shuiChanZhognYangCount = 0;
    let zhognYangDBList = await zhongZhiData.zhongYangTongJiCount();
    zhognYangDBList.forEach(info => {
        let {_id, sizeCount} = info;
        shuiChanZhognYang.push({
            key:changeEnumValue(PLANTTYPE, _id),
            value:sizeCount
        });
        shuiChanZhognYangCount += sizeCount;
    });

    let dataInfo = {
        zuoWu:{
            count:Math.ceil(zuoWuCount/10)/100,
            nongChanPin,
            zuoWu:zuoWu,
        },
        shuiChan:{
            count:Math.ceil(shuiChanCount/100)/100,
            shuiChanPin,
            shuiChan,
        },
        shuiChanZhognYang:{
            shuiChanZhognYangList:shuiChanZhognYang,
            count:shuiChanZhognYangCount,
        }
       
    };

    return {dataInfo};
}



/**
 * 统计页产量统计
 * @param year 年份，如 2025
 * @param type 统计类型：1-年，2-季度，3-月
 * @returns 
 */
// export async function homePageStatisChanLiang(year: number, type: number) {
//     // 产量 时间分
//     let zuoWuMonthDBList = await caishouData.selectToParam({plantType:{"$lt":PLANTTYPE.鲈鱼}});
//     let zuoWuDistinctMap = {};
//     let zuoWuCount = 0;

//     let map1 = {};
//     zuoWuMonthDBList.forEach(info => {
//         let {ct, weight} = info;
        
//         let dataYear = moment(ct).year();
//         let month = moment(ct).month();
        
//         // 添加年份过滤
//         if (year && dataYear !== year) {
//             return;
//         }
        
//         if (!map1[''+dataYear+''+month]) map1[''+dataYear+''+month] = {month, year: dataYear, totalWeight:0}
//         map1[''+dataYear+''+month].totalWeight += weight;
//     })

//     let list1 = Object.values(map1);
//     list1.forEach(info => {
//         let {year: dataYear, month, totalWeight}: any = info;
        
//         let strKey: any = "";
//         if (type == 1) {//年
//             strKey = dataYear;
//         } else if (type == 2) {//季度
//             let quarter = 1;
//             if (month >= 10) quarter = 4;
//             else if (month >= 7) quarter = 3;
//             else if (month >= 4) quarter = 2;
//             strKey = `${dataYear}-${quarter}`;
//         } else {//月
//             strKey = `${dataYear}-${month}`;
//         }

//         if (!zuoWuDistinctMap[strKey]) zuoWuDistinctMap[strKey] = {key: strKey, value: 0};
//         zuoWuDistinctMap[strKey].value += totalWeight;

//         zuoWuCount += totalWeight;
//     });
//     let nongChanPin = Object.values(zuoWuDistinctMap);

//     for (let i = 0; i < nongChanPin.length; i++) {
//         nongChanPin[i]["value"] = Math.ceil(nongChanPin[i]["value"] / 10) / 100;
//     }
    
//     // 农作物产量 - 添加年份过滤条件
//     let zuoWuDBList = await selectChanLiangOfzuoWu({
//         plantType: {"$lt": PLANTTYPE.鲈鱼},
//         ...(year && {year: year}) // 如果有年份参数，添加过滤条件
//     });
//     let zuoWu = [];
//     zuoWuDBList.forEach(info => {
//         let {_id, totalWeight} = info;
//         zuoWu.push({
//             key: changeEnumValue(PLANTTYPE, _id),
//             value: totalWeight / 1000
//         });
//     });
//     zuoWu.sort((a, b) => {return b.value - a.value});

//     // 产量 
//     let shuiChanMonthDBList = await selectChanLiangOfMonth({plantType:{"$gte":PLANTTYPE.鲈鱼}});
//     let shuiChanDistinctMap = {};
//     let shuiChanCount = 0;
//     shuiChanMonthDBList.forEach(info => {
//         let {year: dataYear, month, totalWeight} = info;
        
//         // 添加年份过滤
//         if (year && dataYear !== year) {
//             return;
//         }
        
//         let strKey = "";
//         if (type == 1) {//年
//             strKey = dataYear;
//         } else if (type == 2) {//季度
//             let quarter = 1;
//             if (month >= 10) quarter = 4;
//             else if (month >= 7) quarter = 3;
//             else if (month >= 4) quarter = 2;
//             strKey = `${dataYear}-${quarter}`;
//         } else {//月
//             strKey = `${dataYear}-${month}`;
//         }

//         if (!shuiChanDistinctMap[strKey]) shuiChanDistinctMap[strKey] = {key: strKey, value: 0};
//         shuiChanDistinctMap[strKey].value += totalWeight;

//         shuiChanCount += totalWeight;
//     });
//     let shuiChanPin = Object.values(shuiChanDistinctMap);

//     for (let i = 0; i < shuiChanPin.length; i++) {
//         shuiChanPin[i]["value"] = Math.ceil(shuiChanPin[i]["value"] / 100) / 100;
//     }
    
//     // 水产品产量 - 添加年份过滤条件
//     let shuiChanDBList = await selectChanLiangOfzuoWu({
//         plantType: {"$gte": PLANTTYPE.鲈鱼},
//         ...(year && {year: year}) // 如果有年份参数，添加过滤条件
//     });
//     let shuiChan = [];
//     shuiChanDBList.forEach(info => {
//         let {_id, totalWeight} = info;
//         shuiChan.push({
//             key: changeEnumValue(PLANTTYPE, _id),
//             value: totalWeight / 10000
//         });
//     });
//     shuiChan.sort((a, b) => {return b.value - a.value});

//     // 水产品种植统计 - 添加年份过滤条件
//     let shuiChanZhognYang = [];
//     let shuiChanZhognYangCount = 0;
//     let zhognYangDBList = await zhongZhiData.zhongYangTongJiCountByYear(year);
//     zhognYangDBList.forEach(info => {
//         let {_id, sizeCount} = info;
//         shuiChanZhognYang.push({
//             key: changeEnumValue(PLANTTYPE, _id),
//             value: sizeCount
//         });
//         shuiChanZhognYangCount += sizeCount;
//     });

//     let dataInfo = {
//         zuoWu: {
//             count: Math.ceil(zuoWuCount / 10) / 100,
//             nongChanPin,
//             zuoWu: zuoWu,
//         },
//         shuiChan: {
//             count: Math.ceil(shuiChanCount / 100) / 100,
//             shuiChanPin,
//             shuiChan,
//         },
//         shuiChanZhognYang: {
//             shuiChanZhognYangList: shuiChanZhognYang,
//             count: shuiChanZhognYangCount,
//         }
//     };

//     return {dataInfo};
// }






