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 = {
      jd: { appkey: "201911251551", secret: "56006077354d48858026c80c0e10bef6" }
    };
    this.execClient = system.getObject("util.execClient");
    this.jdOauthUrl = "https://oauth2.jdcloud.com/userinfo";
  }
  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;
      }
      return result;
    } catch (e) {
      console.log(e.stack, "操作error...................");
      return system.getResult(null, "操作失败");
    }
  }

  async getToken(reqType) {
    var self = this;
    var token = "";
    var reqTokenUrl = this.channelApiUrl + "/auth/accessAuth/getToken";
    var reqParam = {};
    switch (reqType) {
      case "jd":
        reqParam = self.appInfo["jd"];
        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);
  }

  async getUserInfo(pobj, qobj, req) {
    try {
      console.log(qobj, "getUserInfo..######################.qobj....");
      var result = await this.execClient.execPostJDTK("", this.jdOauthUrl, qobj.token_type + " " + qobj.access_token);
      console.log(result, "getUserInfo.....result.......");
      if (!result || !result.account) {
        return system.getResult(null, "处理用户请求失败,msg:" + result.error_description);
      }
      return system.getResultSuccess(result);
    } catch (error) {
      console.log(e.stack, "操作error...................");
      return system.getResult(null, "操作失败");
    }
  }
  async getJdSign(pobj, qobj, req) {
    try {
      const { Signer, Context } = require('../jd-gateway-sdk');
      let ctx = new Context('x3k0s704lfun-test.cn-north-1.jdcloud-api.net', '/market/order/api/submit', 'POST', null, 'empty');
      ctx.regionId = 'cn-north-1'
      ctx.headers.set('content-type', 'application/json');

      let credentials = {
        accessKeyId: 'C6D680733C19362B5DF478207D6A90A4', //替换自己的AK
        secretAccessKey: 'EB9AFEE49CE41700CADD5F2EE3B2122C' //替换自己的SK--jd>>>>>>>
      }

      //测试报文：
      //ctx.body = "pin=jcloud_pRiHQTd&serviceId=580010&itemCode=FW_GOODS-580010-1&platform=6"
      //POST
      var qs = require('querystring');
      var post_data = { pin: "jcloud_pRiHQTd", serviceId: 580010, itemCode: "FW_GOODS-580010-1", platform: 6, orderNum: 1, articleType: 1 };//这是需要提交的数据
      var tmpContent = JSON.stringify(post_data);
      var tmpContentLength = Buffer.byteLength(tmpContent);
      var content = qs.stringify(post_data);
      ctx.body = tmpContent;

      ctx.method = 'POST'
      var signer = new Signer(ctx, credentials);


      ctx.headers.set('Content-Length', tmpContentLength)
      ctx.buildNonce()
      var dd = new Date();
      var auth = signer.sign(dd)

      console.log("POST签名为：", auth)
      ctx.headers.set('Authorization', auth)

      ////////////////////////////////////////////////////////////////////////////////////////////////////////////
      var http = require('https');

      var options = {
        host: 'x3k0s704lfun-test.cn-north-1.jdcloud-api.net',
        port: 443,
        path: '/market/order/api/submit',
        method: 'POST',
        headers: {
        }
      };

      for (let [key, value] of ctx.headers) {
        options.headers[key] = value
      }
      console.log("\n post options:\n", options);
      console.log("\n tmpContent:\n", tmpContent);

      var req = http.request(options, function (res) {
        console.log("statusCode: ", res.statusCode);
        console.log("headers: ", res.headers);
        var _data = '';
        res.on('data', function (chunk) {
          _data += chunk;
        });
        res.on('end', function () {
          console.log("\n--->>\nresult:", _data)
        });
      });
      req.on('error', (e) => {
        console.error(`请求遇到问题-------------: ${e.message}`);
      });
      req.write(tmpContent);
      req.end();

    } catch (errorMsg) {
      console.log(errorMsg, "--jd>>>>>>>errorMsg..............................>>>>>>");
    }
  }

}
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);
// })
