/**
 * 用户
 */


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 userAdminLogin(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 userAdminLogout(reqUserInfo) {
    let userInfo = await findUserInfoByUserId(reqUserInfo.userId);

    userInfo.token = getToken(userInfo.loginId);
    userInfo.tokenMs = new Date().valueOf();

    await userInfo.save();

    return successResult(); 
}


/**
 * 登录
 * @param loginId 
 * @param pwd 
 * @returns 
 */
export async function userLogin(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.token = token;
    userInfo.tokenMs = new Date().valueOf();

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



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

    userInfo.token = getToken(userInfo.loginId);
    userInfo.tokenMs = new Date().valueOf();

    await userInfo.save();

    return successResult(); 
}



/**
 * 首页
 * @param userInfo 
 * @returns 
 */
export async function homePageChongHai(userInfo) {
    // let param = {
    //     state:SOLVESTATE.待解决,//待解决
    // };
    // let visitCount = await visitData.findDataCount(param);

    // let enterpriseCount = await findEnterpriseCountByParam({RAS:RAS.续存});
    // let industryCount = await statisIndustryEnterprise();

    return {dataInfo:{title:"当前无虫害预警", state:0}};
}


/**
 * 首页 顶部
 * @param userInfo 
 * @returns 
 */
export async function homePageTop(userInfo) {

    return {dataInfo:{
        name:userInfo.name,
        title:userInfo.position
    }};
}


/**
 * 首页-统计页 顶部
 * @param userInfo 
 * @returns 
 */
export async function homePageStatisTop(userInfo) {
    //面积
    let {totalSize, totalUseSize} = await diKuaiData.diKuaiSizeCount({plotType:PLOTTYPE.地块});
    let rate = Math.ceil(totalUseSize/totalSize*10000)/100;
    if (totalSize && totalUseSize) {
        Math.round(totalUseSize/totalSize*100);
    }

    //品种
    let zhongZhiTypeList = await zhongZhiData.pingZhongCount({ isEnd: 0 , plantType:{"$lt":PLANTTYPE.鲈鱼}});

    let dataInfo = {
        diKuaiCount : totalSize,
        zhongYangCount : totalUseSize,
        zhongYangPinZhong : zhongZhiTypeList.length,
        shiYongLv:rate,
    };

    return {dataInfo};
}



/**
 * 首页-统计页 底部
 * @param userInfo 
 * @returns 
 */
export async function homePageStatisBottom(userInfo) {

    let dataInfo = {
        congYe : 0,
        zhuanYe : 0,
        chanYeZhuTi : 0,
    };

    return {dataInfo};
}



/**
 * 统计页产量统计
 * @param type 
 * @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();
        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 type 
 * @returns 
 */
export async function homePageStatisXiaoShou() {
    let thisYear = new Date().getFullYear();
    //产量
    let monthDBList = await selectXiaoShouOfMonth({plantType:{"$lt":PLANTTYPE.鲈鱼}});
    let distinctMap = {};
    let count = 0;
    let lastYearCount = 0;
    monthDBList.forEach(info => {
        let {year, month, totalWeight} = info;
        
        let strKey = `${year}-${month}`;

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

        if (thisYear == year) count += totalWeight;
        else if (year == (thisYear-1)) lastYearCount += totalWeight;
    });

    let xiaoShouList = Object.values(distinctMap);

    let xiaoShouDBList = await selectXiaoShouOfzuoWu({plantType:{"$lt":PLANTTYPE.鲈鱼}});

    let xiaoShou = [];
    xiaoShouDBList.forEach(info => {
        let {_id, totalWeight} = info;
        xiaoShou.push({
            key:changeEnumValue(PLANTTYPE, _id),
            value:Math.ceil(totalWeight/10)/100
        });
    });
    xiaoShou.sort((a,b) =>{return b.value - a.value});

    for (let i = 0; i < xiaoShouList.length; i++) {
        xiaoShouList[i]["value"] =  Math.ceil(xiaoShouList[i]["value"] / 10)/100;
    }

    //水产

    //产量
    let shuiChanMonthDBList = await selectXiaoShouOfMonth({plantType:{"$gte":PLANTTYPE.鲈鱼}});
    let shuiChanDistinctMap = {};
    let shuiChanCount = 0;
    let suiChanLastYearCount = 0;
    shuiChanMonthDBList.forEach(info => {
        let {year, month, totalWeight} = info;
        
        let strKey = `${year}-${month}`;

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

        if (thisYear == year) shuiChanCount += totalWeight;
        else if (year == (thisYear-1)) suiChanLastYearCount += totalWeight;
    });

    let suiChanxiaoShouList = Object.values(shuiChanDistinctMap);

    let shuiChanXiaoShouDBList = await selectXiaoShouOfzuoWu({plantType:{"$gte":PLANTTYPE.鲈鱼}});
    let shuiChanxiaoShou = [];
    shuiChanXiaoShouDBList.forEach(info => {
        let {_id, totalWeight} = info;
        shuiChanxiaoShou.push({
            key:changeEnumValue(PLANTTYPE, _id),
            value:Math.ceil(totalWeight/10)/100
        });
    });
    shuiChanxiaoShou.sort((a,b) =>{return b.value - a.value});
    
    let dataInfo = {
        zuoWu:{
            count:Math.ceil(count/10)/100,
            mom:Math.round( (count-lastYearCount)/lastYearCount * 1000 )/10,
            xiaoShou:xiaoShouList,
            zuoWu:xiaoShou
        },
        shuiChan:{
            count:Math.ceil(shuiChanCount/10)/100,
            mom:Math.round( (shuiChanCount-suiChanLastYearCount)/suiChanLastYearCount * 1000 )/10,
            xiaoShou:suiChanxiaoShouList,
            shuiChan:shuiChanxiaoShou
        }
       
    };

    return {dataInfo};
}


/**
 * 登录
 * @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(); 
}