const system = require('../system');
const uuidv4 = require('uuid/v4');
const settings = require('../../config/settings');
class APIBase {
  constructor() {
    this.cacheManager = system.getObject('db.common.cacheManager');
    this.logClient = system.getObject('util.logClient');
  }
  async setContextParams(pobj, qobj, req) {
    const 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'],
      userid: req.headers['x-consumer-custom-id'],
      credid: req.headers['x-credential-identifier'],
      companykey: req.headers['x-company-key'], // 专用于自由用户注册,自由用户用于一定属于某个存在的公司
      opath: req.headers.xopath,
      ptags: req.headers.xptags,
    };
    // 添加组织结构路径,如果是上级，取上级
    if (req.xctx.ptags && req.xctx.ptags != '') {
      pobj.opath = req.xctx.ptags;
    } else {
      pobj.opath = req.xctx.opath;
    }
    if (req.xctx.userid) { // 在请求传递数据对象注入公司id
      pobj.userid = req.xctx.userid;
      pobj.username = req.xctx.username;
    }
    if (!req.xctx.appkey) {
      return [-200, '请求头缺少应用x-app-key'];
    }
    // 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 && req.xctx.companykey && req.xctx.companykey != 'null' && req.xctx.companykey != 'undefined') {
      const comptmp = await this.cacheManager.CompanyCache.cache(req.xctx.companykey);
      req.xctx.companyid = comptmp.id;
    }
    if (req.xctx.companyid) { // 在请求传递数据对象注入公司id
      pobj.company_id = req.xctx.companyid;
    }
  }
  async doexec(gname, methodname, pobj, query, req) {
    try {
      const xarg = await this.setContextParams(pobj, query, req);
      if (xarg && xarg[0] < 0) {
        return system.getResultFail(...xarg);
      }

      const rtn = await this[methodname](pobj, query, req);
      this.logClient.log(pobj, req, rtn);
      return rtn;
    } catch (e) {
      this.logClient.log(pobj, req, null, e.stack);
      console.log(e.stack, 'api调用异常--error...................');
      const rtnerror = system.getResultFail(-200, '出现异常，请联系管理员');
      return rtnerror;
    }
  }
}
module.exports = APIBase;

