/**
 * 权限管理
 */

import { ADMINFIRSTDIR, ADMINLV, ADMINSTATE, ADMINTYPE, MEMBERSTATE, STATE } from "../../config/enum";
import { ERRORENUM } from "../../config/errorEnum";
import { TABLEENUM } from "../../data/models/model";
import { find, findCount, findOnce, findToPage } from "../../data/select";
import { BizError } from "../../util/bizError";
import { changeEnumValue, eccEnumValue } from "../../util/verificationEnum";
import * as sysTools from "../../tools/system";
import { addOneData } from "../../data/add";
import { updateOneData } from "../../data/update";

/**
 * 管理员列表
 * @param param0 
 * @returns 
 */
export async function adminList({pageNumber}) {
    let fileList = ["userId", "memberState", "loginId", "adminLv", "adminType"];
    let dbList = await findToPage(TABLEENUM.用户表, {isAdmin:STATE.是}, fileList, pageNumber);
    let dataCount = await findCount(TABLEENUM.用户表, {isAdmin:STATE.是});

    let dataList = [];
    dbList.forEach(info => {
        let {userId, memberState, loginId, adminLv, adminType} = info;
        let memberStateStr = changeEnumValue(ADMINSTATE, memberState);
        
        dataList.push({
            userId,
            memberState:memberStateStr,
            loginId,
            adminType:changeEnumValue(ADMINTYPE, adminType),
            adminLv:changeEnumValue(ADMINLV, adminLv),
            superAdmin : loginId == "admin"
        });
    });

    return {dataList, dataCount};
}

/**
 * 添加管理员 success
 */
export async function addAdmin({userId, form}) {
    let {loginId, pwd, confirmation, adminType, adminLv} = form;

    /**校验参数 */
    eccEnumValue("添加管理员", "管理员类别", ADMINTYPE, adminType);
    eccEnumValue("添加管理员", "管理员等级", ADMINLV, adminLv);
    /**校验密码 */
    if (pwd.search(/^[A-Za-z0-9]{6,18}$/) < 0) throw new BizError(ERRORENUM.密码只能由6至18位字符和数字组成);
    if (pwd != confirmation)  throw new BizError(ERRORENUM.两次密码不一致);

    let addInfo = {
        userId:sysTools.generateUserId(),//系统生成唯一id
        loginId,
        pwd,
        adminType,
        adminLv,
        isAdmin:STATE.是
    };

    await addOneData(TABLEENUM.用户表, addInfo);

    return sysTools.successResult();
}


export async function initAdmin() {
    let userInfo = await findOnce(TABLEENUM.用户表, {loginId:'admin'});    
    if (!userInfo || !userInfo.userId) {
        let addInfo = {
            userId:sysTools.generateUserId(),//系统生成唯一id
            loginId:'admin',
            pwd:'123456',
            adminType:ADMINTYPE.管理员,
            adminLv:[101,102,103,104,105,106,107, 201,202,203,304,205,206],
            isAdmin:STATE.是
        };
        await addOneData(TABLEENUM.用户表, addInfo);
    }
    console.log("初始化admin账号成功");
}


/**
 * 修改密码
 * @param userId 登录的用户id 
 * @returns 
 */
export async function changeAdminPwd({userId, form}) {
    let {pwd, confirmation} = form;

    let userInfo = await findOnce(TABLEENUM.用户表, {userId:form.id}, ["id"]);
    if (!userInfo || !userInfo.id) throw new BizError(ERRORENUM.目标数据不存在);

    /**校验密码 */
    if (pwd.search(/^[A-Za-z0-9]{6,18}$/) < 0) throw new BizError(ERRORENUM.密码只能由6至18位字符和数字组成);
    if (pwd != confirmation)  throw new BizError(ERRORENUM.两次密码不一致);

    await updateOneData(TABLEENUM.用户表, {userId:form.id}, {pwd:form.pwd});

    return sysTools.successResult();
}


/**
 * 修改权限
 */
export async function updateMGMT({id, adminLv}) {
    eccEnumValue("修改管理员权限权限", "权限列表", ADMINLV, adminLv);
    let userInfo = await findOnce(TABLEENUM.用户表, {userId:id}, ["adminLv", "userId", "loginId"]);
    if (!userInfo || !userInfo.id) throw new BizError(ERRORENUM.目标数据不存在);

    await updateOneData(TABLEENUM.用户表, {userId:id}, {adminLv});    

    return sysTools.successResult();
}


/**
 * 回显
 */
export async function info({id}) {
    let userInfo = await findOnce(TABLEENUM.用户表, {userId:id}, ["adminLv", "userId", "loginId"]);
    if (!userInfo || !userInfo.id) throw new BizError(ERRORENUM.目标数据不存在);

    let distinctMap = {};//去重
    for(let i = 0; i < userInfo.adminLv.length; i++) {
        let adminLv = userInfo.adminLv[i];
        let firstKey = Math.floor(adminLv/100);
            if (!distinctMap[firstKey]) distinctMap[firstKey] = []
            if(distinctMap[firstKey]) {
            distinctMap[firstKey].push({
                key:ADMINLV[adminLv],
                value:adminLv
            });
        }
    }

    let dataInfo = {
        loginId:userInfo.loginId,
        distinctMap
    }

    return {dataInfo}
}


/**
 * 冻结管理员权限、解冻管理员权限 success
 * @param id 列表返回的userId 
 */
 export async function freeze({userId, id}) {
    let userInfo = await findOnce(TABLEENUM.用户表, {userId:id}, ["userId", "memberState"]);
    if (!userInfo || !userInfo.userId) throw new BizError(ERRORENUM.目标数据不存在);
 
    if(userInfo.memberState == ADMINSTATE.冻结) {
        await updateOneData(TABLEENUM.用户表, {userId:id}, {memberState:MEMBERSTATE.正常});
    } else {
        await updateOneData(TABLEENUM.用户表, {userId:id}, {memberState:ADMINSTATE.冻结});
    }
    
    return sysTools.successResult();
}


/**
 * 删除
 * @param id 列表返回的userId 
 */
 export async function deleteAdmin({userId, id}) {
    let userInfo = await findOnce(TABLEENUM.用户表, {userId:id}, ["userId", "memberState"]);
    if (!userInfo || !userInfo.userId) throw new BizError(ERRORENUM.目标数据不存在);

    await updateOneData(TABLEENUM.用户表, {userId:id}, { isAdmin:STATE.否 });

    return sysTools.successResult();
}


/**
 * 权限下拉列表
 */
export async function mgmtSelectList() {
   
    let distinctMap = {};//去重
    for (let key in ADMINFIRSTDIR) {
        let anyKey:any = key;
        if (isNaN(anyKey)) {//字符
            let keyStr = key;
            let value = ADMINFIRSTDIR[key];
            distinctMap[value] = {
                key:keyStr,
                value,
                subList:[]
            }
        }
    }
    
    for (let key in ADMINLV) {
        let anyKey:any = key;
        if (isNaN(anyKey)) {//字符
            let keyStr = key;
            let value:any = ADMINLV[key];
            let firstKey = Math.floor(value/100);
            if(distinctMap[firstKey]) {
                distinctMap[firstKey].subList.push({
                    key:keyStr,
                    value
                });
            }
            
        }
    }
    let dataList = Object.values(distinctMap);
   
    return {dataList};
}