var system = require("../../../system");
var settings = require("../../../../config/settings");
const CtlBase = require("../../ctl.base");
const md5 = require("MD5");
class tmqueryCtl extends CtlBase {
  constructor() {
    super();
    this.channelApiUrl = settings.channelApiUrl();
    this.appInfo = {
      1688: { appkey: "201911131657", secret: "eeb18393aade40149287b024d8ba0850", selfRegistProduct: ["5743091"] }
    };
    this.execClient = system.getObject("util.execClient");
  }
  async doPost(pobj, obj, req) {
    var rc = system.getObject("util.execClient");
    try {
      if (!pobj.requrl) {
        return system.getResult(null, "requrl不能为空");
      }
      if (!pobj.actionProcess) {
        return system.getResult(null, "actionProcess不能为空");
      }
      if (!pobj.actionType) {
        return system.getResult(null, "actionType不能为空");
      }
      if (!pobj.actionBody) {
        return system.getResult(null, "actionBody不能为空");
      }
      var reqobj = {
        "actionProcess": pobj.actionProcess || "",
        "actionType": pobj.actionType || "",
        "sign": pobj.sign || "",
        "isUser": pobj.isUser || "yes",//是否需要验证用户，no否，yes是
        "isDecryptUser": pobj.isDecryptUser || "no",//是否解密用户Id，no否，yes是
        "actionBody": pobj.actionBody || null
      };
      var tokenInfo = await this.getToken(reqobj.actionProcess);
      if (tokenInfo.status != 0) {
        return tokenInfo;
      }
      if (!pobj.timeStamp) {
        let currentDate = Math.floor(new Date().getTime() / 1000);
        reqobj.actionBody.timeStamp = currentDate;
      }
      var oldActionType = reqobj.actionType;
      var oldActionBody = reqobj.actionBody;
      var oldIsUser = reqobj.isUser;
      if (reqobj.isDecryptUser == "yes") {
        reqobj.actionType = "decryptStr";
        reqobj.isUser = "no";
        let currentDate = Math.floor(new Date().getTime() / 1000);
        reqobj.actionBody = { opStr: decodeURIComponent(oldActionBody.channelUserId), timeStamp: currentDate };
        var decryptSignResult = await this.createSign(reqobj.actionBody, tokenInfo.data.secret);
        if (decryptSignResult.status != 0) {
          return decryptSignResult;
        }
        reqobj.sign = decryptSignResult.data;
        var decrypReqUrl = this.channelApiUrl + pobj.requrl;
        var decryptResult = await this.execClient.execPostTK(reqobj, decrypReqUrl, tokenInfo.data.token);
        if (!decryptResult) {
          return system.getResult(null, "处理decryptStr请求失败");
        }
        if (decryptResult.status && decryptResult.status != 0) {
          return decryptResult;
        }
        if (!decryptResult.data || decryptResult.data == "") {
          decryptResult.status = -201;
          decryptResult.msg = "decrypt channelUserId error";
          return decryptResult;
        }
        oldActionBody.channelUserId = decryptResult.data;
        reqobj.actionType = oldActionType;
        reqobj.actionBody = oldActionBody;
        reqobj.isUser = oldIsUser;
        var signResult = await this.createSign(reqobj.actionBody, tokenInfo.data.secret);
        if (signResult.status != 0) {
          return signResult;
        }
        reqobj.sign = signResult.data;
      }//解密操作

      if (!reqobj.sign) {
        var signInfo = await this.createSign(reqobj.actionBody, tokenInfo.data.secret);
        if (signInfo.status != 0) {
          return signInfo;
        }
        reqobj.sign = signInfo.data;
      }
      var reqUrl = this.channelApiUrl + pobj.requrl;
      var result = await this.execClient.execPostTK(reqobj, reqUrl, tokenInfo.data.token);
      if (!result) {
        return system.getResult(null, "处理请求失败");
      }
      if (result.status && result.status != 0) {
        return result;
      }
      // if (pobj.actionType == "getChannelOrderInfo") {
      //   var tmpSkipUrl = await this.getPageSkipUrl(reqobj.actionProcess, reqobj.actionBody.itemCode);
      //   if (!tmpSkipUrl) {
      //     return system.getResult(null, "获取页面url失败");
      //   }
      //   result.skipUrl = tmpSkipUrl;
      // }//获取渠道订单信息
      return result;
    } catch (e) {
      console.log(e.stack, "操作error...................");
      return system.getResult(null, "操作失败");
    }
  }
  // async getPageSkipUrl(reqType, itemCode) {
  //   var self = this;
  //   var skipUrl = "";
  //   switch (reqType) {
  //     case "1688":
  //       if (self.appInfo["1688"].selfRegistProduct.indexOf(itemCode) < 0) {
  //         skipUrl = "/#/1688/jdindentlist";
  //       } else {
  //         skipUrl = "/#/1688/selftmreg";
  //       }
  //       break;
  //     default:
  //       break;
  //   }
  //   return skipUrl;
  // }

  async getToken(reqType) {
    var self = this;
    var token = "";
    var reqTokenUrl = this.channelApiUrl + "/auth/accessAuth/getToken";
    var reqParam = {};
    switch (reqType) {
      case "1688":
        reqParam = self.appInfo["1688"];
        break;
      default:
        break;
    }
    if (!reqParam.appkey || !reqParam.secret) {
      return system.getResult(null, "reqType类型有误，请求失败");
    }
    var rtn = await this.execClient.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;
  }
  /**
   * 验证签名
   * @param {*} params 要验证的参数 
   * @param {*} app_key 应用的校验key
   */
  async createSign(params, app_key) {
    if (!params) {
      return system.getResult(null, "请求参数为空");
    }
    if (!params.timeStamp) {
      return system.getResult(null, "请求参数timeStamp为空");
    }
    var signArr = [];
    var keys = Object.keys(params).sort();
    if (keys.length == 0) {
      return system.getResult(null, "请求参数信息为空");
    }
    for (let k = 0; k < keys.length; k++) {
      const tKey = keys[k];
      if (tKey != "sign" && params[tKey]) {
        signArr.push(tKey + "=" + params[tKey]);
      }
    }
    if (signArr.length == 0) {
      return system.getResult(null, "请求参数组装签名参数信息为空");
    }
    var resultSignStr = signArr.join("&") + "&key=" + app_key;
    var resultTmpSign = md5(resultSignStr).toUpperCase();
    return system.getResultSuccess(resultTmpSign);
  }

}
module.exports = tmqueryCtl;
// var task = new tmqueryCtl();
// var obj={
//     "currentpage": 1,
//     "keyword": "萌",
//     "max": "",
//     "min": "",
//     "order": "",
//     "pagesize": 36,
//     "sort": "",
//     "tm_nclcode": [],
//     "tm_structure": "",
//     "tm_word": ""
//     };   
// task.test(obj).then(d=>{
//     console.log("dddddddddddddddddddddddddddddd");
//     console.log(d);
// })
