const system = require("../system");
var moment = require('moment')
var settings = require("../../config/settings");
class ServiceBase {
  constructor(gname, daoName) {
    //this.dbf=system.getObject("db.connection");
    this.db = system.getObject("db.common.connection").getCon();
    this.cacheManager = system.getObject("db.common.cacheManager");
    this.daoName = daoName;
    this.dao = system.getObject("db." + gname + "." + daoName);
    this.restS = system.getObject("util.restClient");
    this.execS = system.getObject("util.execClient");
    this.channelApiUrl = settings.channelApiUrl();
    this.appInfo = {
      aliyuntmtransfer: { appkey: "201912031344", secret: "7cbb846246874167b5c7e01cd0016c88" }
    };

  }

  async apiCallWithAk(url, params) {
    var acckapp = await this.cacheManager["ApiAccessKeyCache"].cache(settings.appKey);
    var acck = acckapp.accessKey;
    //按照访问token
    var restResult = await this.restS.execPostWithAK(params, url, acck);
    if (restResult) {
      if (restResult.status == 0) {
        var resultRtn = restResult.data;
        return resultRtn;
      } else {
        await this.cacheManager["ApiAccessKeyCache"].invalidate(settings.appKey);
        return null;
      }
    }
    return null;
  }
  async apiCallWithAkNoWait(url, params) {
    var acckapp = await this.cacheManager["ApiAccessKeyCache"].cache(settings.appKey);
    var acck = acckapp.accessKey;
    //按照访问token
    this.restS.execPostWithAK(params, url, acck).then((restResult) => {
      if (restResult) {
        if (restResult.status == 0) {
          var resultRtn = restResult.data;
          return resultRtn;
        } else {
          this.cacheManager["ApiAccessKeyCache"].invalidate(settings.appKey);
          return null;
        }
      }
      return null;
    });
  }
  static getDaoName(ClassObj) {
    return ClassObj["name"].substring(0, ClassObj["name"].lastIndexOf("Service")).toLowerCase() + "Dao";
  }
  async findAndCountAll(obj) {
    const apps = await this.dao.findAndCountAll(obj);
    return apps;
  }
  async refQuery(qobj) {
    return this.dao.refQuery(qobj);
  }
  async bulkDelete(ids) {
    var en = await this.dao.bulkDelete(ids);
    return en;
  }
  async delete(qobj) {
    return this.dao.delete(qobj);
  }
  async create(qobj) {
    return this.dao.create(qobj);
  }
  async update(qobj, tm = null) {
    return this.dao.update(qobj, tm);
  }
  async updateByWhere(setObj, whereObj, t) {
    return this.dao.updateByWhere(setObj, whereObj, t);
  }
  async customExecAddOrPutSql(sql, paras = null) {
    return this.dao.customExecAddOrPutSql(sql, paras);
  }
  async customQuery(sql, paras, t) {
    return this.dao.customQuery(sql, paras, t);
  }
  async findCount(whereObj = null) {
    return this.dao.findCount(whereObj);
  }
  async findSum(fieldName, whereObj = null) {
    return this.dao.findSum(fieldName, whereObj);
  }
  async getPageList(pageIndex, pageSize, whereObj = null, orderObj = null, attributesObj = null, includeObj = null) {
    return this.dao.getPageList(pageIndex, pageSize, whereObj, orderObj, attributesObj, includeObj);
  }
  async findOne(obj) {
    return this.dao.findOne(obj);
  }
  async findById(oid) {
    return this.dao.findById(oid);
  }
  /*
  返回20位业务订单号
  prefix：业务前缀
  */
  async getBusUid(prefix) {
    prefix = (prefix || "");
    if (prefix) {
      prefix = prefix.toUpperCase();
    }
    var prefixlength = prefix.length;
    var subLen = 8 - prefixlength;
    var uidStr = "";
    if (subLen > 0) {
      uidStr = await this.getUidInfo(subLen, 60);
    }
    var timStr = moment().format("YYYYMMDDHHmm");
    return prefix + timStr + uidStr;
  }
  /*
  len：返回长度
  radix：参与计算的长度，最大为62
  */
  async getUidInfo(len, radix) {
    var chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'.split('');//长度62，到yz长度为长36
    var uuid = [], i;
    radix = radix || chars.length;
    if (len) {
      for (i = 0; i < len; i++) uuid[i] = chars[0 | Math.random() * radix];
    } else {
      var r;
      uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
      uuid[14] = '4';
      for (i = 0; i < 36; i++) {
        if (!uuid[i]) {
          r = 0 | Math.random() * 16;
          uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
        }
      }
    }
    return uuid.join('');
  }

  async aliclient(obj) {
    var sobj = {
      "actionProcess": "aliyuntmtransfer",
      "actionType": "aliclient",
      "sign": "2FviZ9PGws8Pt1fBhq0t90mjUvI",
      "actionBody": obj
    }
    var tokenInfo = await this.getToken();
    var reqUrl = this.channelApiUrl + "/action/tradetransfer/aliclienttransfer";
    console.log("------------rtn---------------------------")
    var rtn = await this.execS.execPostTK(sobj, reqUrl, tokenInfo.data.token);
    console.log(rtn);
    //var rtn = await this.execS.execPostTK(sobj, reqUrl,"token");
    return rtn;
  }

  async getToken() {
    var self = this;
    var reqTokenUrl = this.channelApiUrl + "/auth/accessAuth/getToken";
    var reqParam = self.appInfo["aliyuntmtransfer"];
    if (!reqParam.appkey || !reqParam.secret) {
      return system.getResult(null, "reqType类型有误，请求失败");
    }
    var rtn = await this.execS.execPost(reqParam, reqTokenUrl);
    if (!rtn.stdout) {
      return system.getResult(null, "获取token失败");
    }
    var tokenResult = JSON.parse(rtn.stdout);
    if (tokenResult.status == 0) {
      tokenResult.data.secret = reqParam.secret;
    }
    return tokenResult;
  }


  trim(o) {
    if (!o) {
      return "";
    }
    return o.toString().trim();
  }

  isStrEmpty(str) {
    return this.trim(str) ? true : false;
  }
}
module.exports = ServiceBase;
