import { OPERATIONALDATATYPE, TABLENAME } from "../config/enum/dbEnum";
import { ERRORENUM } from "../config/enum/errorEnum";
import { operationalData, selectData } from "../data/operationalData";
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.企业用户表, {uId:userId}, ["token", "uId", "eId"]);
    if (!userInfo || !userInfo.uId) 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.uId,
        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();
}