const system = require("../system");
const settings = require("../../config/settings");
const DocBase = require("./doc.base");
class APIBase extends DocBase {
    constructor() {
        super();
        this.cacheManager = system.getObject("db.common.cacheManager");
        this.logCtl = system.getObject("web.common.oplogCtl");
        this.apitradeSvr = system.getObject("service.common.apitradeSve");
    }
  
    async isExistInNoAuthMainfest(gname, methodname) {
        var fullname = gname + "." + methodname;
        var lst = [

        ];
        var x = lst.indexOf(fullname);
        return x >= 0;
    }
    async checkAcck(gname, methodname, pobj, query, req) {
        var apptocheck=null;
        var isExistInNoAuth = await this.isExistInNoAuthMainfest(gname, methodname);
        if (!isExistInNoAuth) {//在验证请单里面,那么就检查访问token
            var ak = req.headers["accesskey"];
            apptocheck = await this.cacheManager["ApiAccessKeyCheckCache"].cache(ak, { status: true }, 3000);
           
        }
        return {apptocheck:apptocheck,ispass:isExistInNoAuth || apptocheck};
    }
    async doexec(gname, methodname, pobj, query, req) {
        try {
            //检查访问token
            var isPassResult = await this.checkAcck(gname, methodname, pobj, query, req);
            if (!isPassResult.ispass) {
                return system.getResultFail(system.tokenFail, "访问token失效，请重新获取");
            }
            var rtn = await this[methodname](pobj, query);
            if(isPassResult.apptocheck){
                var app=isPassResult.apptocheck.app;
                if(methodname && methodname.indexOf("recvNotificationForCacheCount")<0){
                    this.apitradeSvr.create({
                        srcappkey: app.appkey,
                        tradeType: "consume",
                        op: req.classname + "/" + methodname,
                        params: JSON.stringify(pobj),
                        clientIp: req.clientIp,
                        agent: req.uagent,
                        destappkey:settings.appKey,
                      });
                }

            }
            return rtn;
        } catch (e) {
            console.log(e.stack,"api调用出现异常，请联系管理员..........")
            this.logCtl.error({
                optitle: "api调用出现异常，请联系管理员",
                op: pobj.classname + "/" + methodname,
                content: e.stack,
                clientIp: pobj.clientIp
            });
            return system.getResultFail(-200, "出现异常，请联系管理员");
        }
    }
}
module.exports = APIBase;

