import { OPERATIONALDATATYPE, TABLENAME } from "../config/enum/dbEnum";
import { ERRORENUM } from "../config/enum/errorEnum";
import { operationalData, selectData } from "../data/operationalData";
import { md5PwdStr } from "../tools/system";
import { BizError } from "../util/bizError";


/**
 * 小程序中间件
 * @param req 
 * @param res 
 * @param next 
 * @returns 
 */
export async function checkUser(req, res, next) {   
    if (!req.headers) req.headers = {};

    const reqToken = req.headers.token;
    const userId = req.headers.userid || "";

    if (!userId) return next(new BizError(ERRORENUM.身份验证失败, `userId:${userId} token:${reqToken}`));

    let userInfo:any = await selectData(OPERATIONALDATATYPE.查询单个, TABLENAME.管理后台用户, {aId:userId}, ["token", "aId"]);
    if (!userInfo || !userInfo.aId) return next(new BizError(ERRORENUM.非法登录, `userId:${userId} token:${reqToken}`));
    
   
    if (userInfo.token != reqToken ) return next(new BizError(ERRORENUM.身份验证过期, `userId:${userId} token:${reqToken}`));

    req.headers.uscc = req.headers.userid;

    req.userInfo = {
        uId:userInfo.aId,
        eId:userInfo.aId
    }

    next();
}


/**
 * 小程序中间件
 * @param req 
 * @param res 
 * @param next 
 * @returns 
 */
export async function checkEnterpriseUser(req, res, next) {   
    if (!req.headers) req.headers = {};

    const reqToken = req.headers.token;
    const userId = req.headers.userid || "";

    if (!userId) return next(new BizError(ERRORENUM.身份验证失败, `userId:${userId} token:${reqToken}`));

    let userInfo:any = await selectData(OPERATIONALDATATYPE.查询单个, TABLENAME.企业基础信息表, {eId:userId},  ["eId", "uscc", "randomCode"]);
    if (!userInfo || !userInfo.eId) return next(new BizError(ERRORENUM.非法登录, `userId:${userId} token:${reqToken}`));
    
   
    if (md5PwdStr(userInfo.randomCode) != reqToken ) return next(new BizError(ERRORENUM.身份验证过期, `userId:${userId} token:${reqToken}`));

    req.headers.uscc = req.headers.userid;

    req.userInfo = {
        uId:userInfo.eId,
        eId:userInfo.eId
    }
    next();
}



/**
 * 中间件 数据维护接口
 * @param req 
 * @param res 
 * @param next 
 * @returns 
 */
export async function checkInterior(req, res, next) {
    if (!req.headers) req.headers = {};

    const Sign = req.headers.sign;

    let sysSign = 'sadfjslakdfjlksadjffujisdaiofjsajl09092302'
   
    if (!Sign || Sign != sysSign) return next(new BizError(ERRORENUM.非法登录, `内部接口非法调用 ${Sign}`));

    next();
}