import { ERRORENUM } from "../config/errorEnum";
import { findAdminuserByLoginId } from "../data/adminuser";
import { findEnterpriseByUscc } from "../data/enterprise";
import { BizError } from "../util/bizError";



/**
 * 中间件 校验管理后台token
 * @param req 
 * @param res 
 * @param next 
 * @returns 
 */
export async function checkAdminUserToken(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 = await findAdminuserByLoginId(UserId);
    if (!userInfo || !userInfo.loginId) return next(new BizError(ERRORENUM.非法登录, `userId:${UserId} token:${ReqToken}`));
    if (userInfo.token != ReqToken ) return next(new BizError(ERRORENUM.身份验证过期, `userId:${UserId} token:${ReqToken}`));
    // if (userInfo.token != ReqToken || (new Date().valueOf() - userInfo.tokenMs) > (3600*100*24*7) ) return next(new BizError(ERRORENUM.身份验证过期, `userId:${UserId} token:${ReqToken}`));

    next();
}



/**
 * 中间件 校验企业token
 * @param req 
 * @param res 
 * @param next 
 * @returns 
 */
export async function checkEnterpriseToken(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 = await findEnterpriseByUscc(userId);
    if (!userInfo) return next(new BizError(ERRORENUM.非法登录, `userId:${userId} token:${reqToken}`));
    
    if (userInfo.token != reqToken || (new Date().valueOf() - userInfo.tokenMs) > (3600*100*24*7) ) 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;

    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();
}


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

    const Sign = req.headers.sign;

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

    next();
}