const system = require("../system");
const uuidv4 = require('uuid/v4');
const settings = require("../../config/settings");
const sha256 = require('sha256');
class APIBase {
  constructor() {
    this.cacheManager = system.getObject("db.common.cacheManager");
    this.logClient = system.getObject("util.logClient");
    this.queryAction = ["getTemplateAndLinkInfo"];
    this.redisClient = system.getObject("util.redisClient");
  }
  async setContextParams(pobj, qobj, req) {
    let custtags = req.headers["x-consumetag"] ? req.headers["x-consumetag"].split("|") : null;
    //当自由用户注册时，需要根据前端传来的companykey,查询出公司，给companyid赋值
    req.xctx = {
      appkey: req.headers["xappkey"],//用于系统管理区分应用,比如角色
      companyid: custtags ? custtags[0].split("_")[1] : null,
      password: custtags ? custtags[1].split("_")[1] : null,
      username: req.headers["x-consumer-username"],
      credid: req.headers["x-credential-identifier"],
      companykey: req.headers["x-company-key"],//专用于自由用户注册,自由用户用于一定属于某个存在的公司
    }
    if (!req.xctx.appkey) {
      return [-200, "请求头缺少应用x-app-key"]
    } else {
      // let app = await this.cacheManager["AppCache"].cache(req.xctx.appkey);
      // req.xctx.appid = app.id;
      // pobj.app_id = app.id;//传递参数对象里注入app_id
    }
    //平台注册时，companyid，companykey都为空
    //自由注册时，companykey不能为空
    // if(!req.xctx.companyid && !req.xctx.companykey){
    //   return [-200,"请求头缺少应用x-app-key"]
    // }

    if (req.xctx.companyid) {//在请求传递数据对象注入公司id
      pobj.company_id = req.xctx.companyid;
    }
  }
  async doexec(gname, methodname, pobj, query, req) {
    try {
      var shaStr = await sha256(JSON.stringify(pobj));
      //查询缓存
      if (pobj && pobj.actionType && this.queryAction.indexOf(pobj.actionType) >= 0) {
          var cacheRes = await this.redisClient.get(shaStr);
          if (cacheRes) {
              // return JSON.parse(cacheRes);
          }
      }
      let xarg = await this.setContextParams(pobj, query, req);
      if (xarg && xarg[0] < 0) {
        return system.getResultFail(...xarg);
      }
      var rtn = await this[methodname](pobj, query, req);
      this.logClient.log(pobj, req, rtn);
      if(rtn && rtn.status==0){
        await this.redisClient.setWithEx(shaStr, JSON.stringify(rtn), 300);
      }
      return rtn;
    } catch (e) {
      this.logClient.log(pobj, req, null, e.stack);
      console.log(e.stack, "api调用异常--error...................");
      var rtnerror = system.getResultFail(-200, "出现异常，请联系管理员");
      return rtnerror;
    }
  }
}
module.exports = APIBase;

