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");
  }
  async doPost(pobj, obj, req) {
    if (["subTmOrder", "getTmOrderList", "getTmOrderInfo", "getTmApplyInfo", "getTmNclList",
      "getNeedInfo", "tmConfirm", "updateTmInfo", "updateNclInfo",
      "updateContacts", "updateCustomerInfo"].indexOf(pobj.actionType) >= 0) {
      if (!pobj.actionBody.channelUserId) {
        return system.getResult(null, "verify channelUserId is not empty");
      }
      if (!req.session.userPinInfo) {
        return system.getResult(null, "ueser is not login");
      }
      if (req.session.userPinInfo.encryptChannelUserId != pobj.actionBody.channelUserId) {
        return system.getResult(null, "ueser login is error");
      }
      pobj.isDecryptUser = "yes";
    }

    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 (["jd"].indexOf(pobj.actionProcess) >= 0 && pobj.actionType == "subTmOrder") {
        var opPayPageInfoResult = await this.opPayPageInfo(pobj, result, req);
        return opPayPageInfoResult;
      }
      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
   * @param {*} isEmptySign params key 对应值为空是否参与签名
   */
  async createSign(params, app_key, isEmptySign) {
    if (!params) {
      return system.getResult(null, "请求参数为空");
    }
    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") {
        if (tKey != "token") {
          if (tKey != "actionProcess") {
            if (isEmptySign) {
              signArr.push(tKey + "=" + params[tKey]);
            } else {
              if (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 {
      var tokenInfo = await this.getToken(pobj.actionProcess);
      if (tokenInfo.status != 0) {
        return tokenInfo;
      }
      //有返回用户信息进行用户ID加密
      var param = {
        actionProcess: pobj.actionProcess,
        actionType: "createChannelUser",
        actionBody: { channelUserId: pobj.tmpchannelUserId },
        isUser: "yes"
      };
      var reqUrl = this.channelApiUrl + "/action/tmTools/springBoard";
      var resultUser = await this.execClient.execPostTK(param, reqUrl, tokenInfo.data.token);
      if (!resultUser) {
        return system.getResult(null, "处理请求失败");
      }
      req.session.userPinInfo = resultUser.data;
      return resultUser;



      // var authUrl = pobj.authUrl;
      // var authToken = pobj.authToken;
      // var actionProcess = pobj.actionProcess;
      // if (!authUrl) {
      //   return system.getResult(null, "authUrl不能为空");
      // }
      // if (!authToken) {
      //   return system.getResult(null, "authToken不能为空");
      // }
      // if (!actionProcess) {
      //   return system.getResult(null, "actionProcess不能为空");
      // }
      // var result = await this.execClient.execPostJDTK("", authUrl, authToken);
      // if (!result || !result.account) {
      //   return system.getResult(null, "处理用户请求失败,msg:" + result.error_description);
      // }
      // var tokenInfo = await this.getToken(actionProcess);
      // if (tokenInfo.status != 0) {
      //   return tokenInfo;
      // }
      // //有返回用户信息进行用户ID加密
      // var param = {
      //   actionProcess: actionProcess,
      //   actionType: "createChannelUser",
      //   actionBody: { channelUserId: result.account },
      //   isUser: "yes"
      // };
      // var reqUrl = this.channelApiUrl + "/action/tmTools/springBoard";
      // var resultUser = await this.execClient.execPostTK(param, reqUrl, tokenInfo.data.token);
      // if (!resultUser) {
      //   return system.getResult(null, "处理请求失败");
      // }
      // req.session.userPinInfo = resultUser.data;
      // return resultUser;
    } catch (error) {
      console.log(error.stack, "操作error...................");
      return system.getResultFail(-200, "操作error");
    }
  }
  async opPayPageInfo(pobj, orderResult, req) {
    if (!pobj.actionBody.itemCode) {
      return system.getResult(null, "itemCode param is not empty");
    }
    if (pobj.actionProcess == "jd") {
      var itemCodeList = pobj.actionBody.itemCode.split('-');
      if (itemCodeList.length < 2) {
        return system.getResult(null, "itemCode is error");
      }
      var tmpResult = await this.getPayPageAddr(pobj.actionBody.itemCode, itemCodeList, req);
      // { result: true,
      //   data:
      //  '{"success":true,"code":null,"msg":null,"data":{"orderNumber":"6058867","erpOrderId":"523198741458590844",
      //  "returnUrl":"https://buy.jdcloud.com/pay?orderId=523198741458590844","saasCheckUrl":null}}' }

      console.log(tmpResult, "tmpResult...........opPayPageInfo........$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$....");
      if (tmpResult && tmpResult.result && tmpResult.result == true) {
        var payDataResult = JSON.parse(tmpResult.data);
        console.log(payDataResult, "payDataResult...........payDataResult........$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$..002..");
        if (payDataResult && payDataResult.success && payDataResult.success == true) {
          //更新订单信息

          return system.getResultSuccess({ payUrl: payDataResult.data.returnUrl });
        }//成功           
      }
      return system.getResult(null, "pay page is error");
    }
    return system.getResultSuccess()
  }
  async putPayOrderData() {
    var tokenInfo = await this.getToken(pushData.actionProcess);
    if (tokenInfo.status != 0) {
      return tokenInfo;
    }
    var param = {
      actionProcess: pushData.actionProcess,
      actionType: "updateOrderStatus",
      actionBody: {
        channelUserId: pushData.jdPin,
        channelItemCode: pushData.serviceCode,
        needNoOrderNo: pushData.orderId,
        buyerMoblie: pushData.mobile
      },
      isUser: "yes"
    };
    var reqUrl = this.channelApiUrl + "/action/tmOrder/springBoard";
    var resultUser = await this.execClient.execPostTK(param, reqUrl, tokenInfo.data.token);
    if (!resultUser) {
      return system.getResult(null, "req error");
    }
  }
  async getPayPageAddr(itemCode, itemCodeList, 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: "syaify", serviceId: 580010, itemCode: "FW_GOODS-580010-1", platform: 6, orderNum: 1, articleType: 1 };//这是需要提交的数据

      var post_data = {
        pin: req.session.userPinInfo.channelUserId,
        serviceId: itemCodeList[1],
        itemCode: "FW_GOODS-581976-1",
        platform: 6,
        orderNum: 1,
        articleType: 1,
        additions: '{ 246: 0 }'
      };//这是需要提交的数据

      // var tmpContent = '{"pin":"syaify","serviceId":"581976","itemCode":"FW_GOODS-581976","platform":6,"orderNum":1,"articleType":1,"additions":{"246":0}}';

      var tmpContent = JSON.stringify(post_data);
      var tmpContentLength = Buffer.byteLength(tmpContent);
      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 reqResult = await new Promise(function (resolve, reject) {
        let req = http.request(options, function (res) {
          // res.setEncoding(encoding);
          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--req---成功->>\nresult:", _data)
            resolve({ result: true, data: _data });
          });
        });
        req.on('error', (e) => {
          console.error(`请求遇到问题-------------: ${e.message}`);
          resolve({ result: false, errmsg: e.message });
        });
        req.write(tmpContent);
        req.end();
      });

      var tmd = 99;

      return reqResult;

      // 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();
      // var tmd = 99;
    } catch (errorMsg) {
      console.log(errorMsg, "--jd>>>>>>>errorMsg..............................>>>>>>");
      return { success: false, code: -200, msg: errorMsg.stack };
    }
  }
  async pushPayOrder(pushData, req) {//处理京东推送的订单信息
    try {
      var signResult = await this.createSign(pushData, "6B876EB84731E166D76E1F73AD5764BA", true);
      if (signResult.status != 0) {
        return signResult;
      }
      if (signResult.data != pushData.token.toUpperCase()) {
        return system.getResult(null, "签名错误");
      }
      var tokenInfo = await this.getToken(pushData.actionProcess);
      if (tokenInfo.status != 0) {
        return tokenInfo;
      }
      var param = {};
      if (pushData.serviceCode == "FW_GOODS-581976") {
        param = {
          actionProcess: pushData.actionProcess,
          actionType: "updateOrderPayStatus",
          actionBody: {
            channelUserId: pushData.jdPin,
            channelItemCode: pushData.serviceCode,
            needNoOrderNo: pushData.orderId,
            buyerMoblie: pushData.mobile
          },
          isUser: "yes"
        };
      }//自助注册产品
      else {
        //有返回用户信息进行用户ID加密
        param = {
          actionProcess: pushData.actionProcess,
          actionType: "addOrderAndDelivery",
          actionBody: {
            channelUserId: pushData.jdPin,
            needNoOrderNo: pushData.orderId,
            buyerMoblie: pushData.mobile
          },
          isUser: "yes"
        };
      }//商标注册【专家辅助申请】、商标注册【担保申请】和 除商标之外的产品
      var reqUrl = this.channelApiUrl + "/action/tmOrder/springBoard";
      var resultUser = await this.execClient.execPostTK(param, reqUrl, tokenInfo.data.token);
      if (!resultUser) {
        return system.getResult(null, "req error");
      }
      return resultUser;

    } catch (error) {
      console.log(error.stack, "操作error...................");
      return system.getResultFail(-200, "操作error");
    }
  }

}
module.exports = tmqueryCtl;
