var system = require("../../system")
var settings = require("../../../config/settings");
const CtlBase = require("../ctl.base");
const axios = require("axios");

class WxCtl extends CtlBase {
  constructor() {
    super(CtlBase.getServiceName(WxCtl));

    this.execClient = system.getObject("util.execClient");
    this.redisClient = system.getObject("util.redisClient");
  }
  async fetchOAuthPath(q, obj, req) {
    var appk = obj.apk;
    var subfixstr = obj.subfix;
    if (appk == "") {
      appk = null;
    }
    if (subfixstr == "") {
      subfixstr = null;
    }
    var result = await this.service.fetchOAuthPath(appk, subfixstr);
    return system.getResult2(result, null);
  }
  async getJsApiConfig(q, obj) {
    console.log("getJsApiConfig.......................");
    console.log(obj.url);
    var result = await this.service.getJsApiConfig(null, obj.url);
    return system.getResult2(result, null);
  }

  async wxuseropenid(q, obj, req) {
    var code = obj.code;

    var redisKey = "bpo_code_openid_" + code;

    var openId = await this.redisClient.get(redisKey);
    if(openId) {
      return system.getResult2(openId);
    }

    var rtn = null;
    var url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=wxf616c0a459d66081&secret=35275146272c7c862ff4b1ba11282d02&code=" + code + "&grant_type=authorization_code";
    try {
      // rtn = await this.execClient.execGet({}, url);
      rtn = await axios({
        method: 'get',
        url:url
     });
      console.log(rtn);
      var result = rtn.data;
      if(result.openid) {
        await this.redisClient.set(redisKey, result.openid, 6 * 60 * 60);
        return system.getResult2(result.openid);
      }
      return system.getErrResult2("openId获取失败，请重新打开页面");
    } catch (e) {
      console.log(e);
      return system.getErrResult2(JSON.stringify(rtn) || "openId获取失败，请关闭页面重试");
    }
  }

}
module.exports = WxCtl;