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" },
      1688: { appkey: "201911131657", secret: "eeb18393aade40149287b024d8ba0850" },
      gsbhome: { appkey: "201912141625", secret: "8cbb846776874167b5c7e01cd0116c66" }
    };
    this.execClient = system.getObject("util.execClient");

    this.logClient = system.getObject("util.logClient");
  }
  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, "user is not login");
      }
      if (req.session.userPinInfo.encryptChannelUserId != pobj.actionBody.channelUserId) {
        return system.getResult(null, "user 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;
        }
        if (oldActionBody.channelUserId) {
          oldActionBody.channelUserId = decryptResult.data;
        }
        if (oldActionBody.channelUser && oldActionBody.channelUser.channelUserId) {
          oldActionBody.channelUser.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 opJdPayPageInfoResult = await this.opJdPayPageInfo(pobj, result, req);
        return opJdPayPageInfoResult;
      }
      else if (["gsbhome"].indexOf(pobj.actionProcess) >= 0 && pobj.actionType == "subTmOrder") {
        var opGsbPayPageInfoResult = await this.opGsbPayPageInfo(pobj, result, req);
        return opGsbPayPageInfoResult;
      }
      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;
      case "1688":
        reqParam = self.appInfo["1688"];
        break;
      case "gsbhome":
        reqParam = self.appInfo["gsbhome"];
        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 getUserIdEncryptStr(pobj, qobj, req) {
    try {
      if (!req.session.userPinInfo) {
        var userInfo = await this.createUserInfo(pobj, qobj, req);
        if (userInfo.status != 0) {
          return system.getResult(null, "user is not login...");
        }
        if (req.session.userPinInfo.encryptChannelUserId) {
          return system.getResultSuccess({ encryptChannelUserId: req.session.userPinInfo.encryptChannelUserId });
        }
      }
      if (req.session.userPinInfo.encryptChannelUserId) {
        return system.getResultSuccess({ encryptChannelUserId: req.session.userPinInfo.encryptChannelUserId });
      }
      var tokenInfo = await this.getToken(pobj.actionProcess);
      if (tokenInfo.status != 0) {
        return tokenInfo;
      }
      //有返回用户信息进行用户ID加密
      var param = {
        actionProcess: pobj.actionProcess,
        actionType: "encryptStr",
        actionBody: { channelUserId: req.session.userPinInfo.channelUserId, opStr: req.session.userPinInfo.channelUserId },
        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, "encryptStr resultUser is empty");
      }
      if (resultUser.status != 0) {
        return system.getResult(null, "encryptStr resultUser is error");
      }
      req.session.userPinInfo.encryptChannelUserId = resultUser.data || "";
      return system.getResultSuccess({ encryptChannelUserId: resultUser.data || "" });
    } catch (error) {
      console.log(error.stack, "操作error...................getUserIdEncryptStr");
      return system.getResultFail(-200, "操作error");
    }
  }
  async createUserInfo(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.channelUserId, channelUserMoblie: pobj.channelUserMoblie || "" },
        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...................getUserInfoTest");
      return system.getResultFail(-200, "操作error");
    }
  }
  async putPayOrderData(pobj, orderResult, channelServiceNo, needNo, needNoOrderNo, req) {//关联下单的数据
    var tokenInfo = await this.getToken(pobj.actionProcess);
    if (tokenInfo.status != 0) {
      return tokenInfo;
    }
    var param = {
      actionProcess: pobj.actionProcess,
      actionType: "updateOrderStatus",
      actionBody: {
        channelUserId: req.session.userPinInfo.channelUserId,
        orderNo: orderResult.data.orderNo,
        channelServiceNo: channelServiceNo,
        needNo: needNo,
        needNoOrderNo: needNoOrderNo
      },
      isUser: "yes"
    };
    // console.log(param, "putPayOrderData########################################333333...........................");
    this.logClient.info(pobj.actionProcess, "putPayOrderData###..." + JSON.stringify(param));
    var reqUrl = this.channelApiUrl + "/action/tmOrder/springBoard";
    var tmp = await this.execClient.execPostTK(param, reqUrl, tokenInfo.data.token);
    this.logClient.info(pobj.actionProcess, "putPayOrderData###...Result-->" + JSON.stringify(tmp));
    // console.log(tmp, "putPayOrderData########################################333333..........tmptmptmptmp.................");
  }

  //----------------------------jd------操作------------start
  async getJdUserInfo(pobj, qobj, req) {
    try {
      // this.logClient.info("jd", "getUserInfo--info--->pobj：" + JSON.stringify(pobj));
      req.session.userPinInfo = null;
      if (req.session.userPinInfo) {
        return system.getResultSuccess({ encryptChannelUserId: req.session.userPinInfo.encryptChannelUserId || "" });
      }
      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);
      this.logClient.info("jd", "getUserInfo----->tokenInfo：" + JSON.stringify(tokenInfo));
      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);
      this.logClient.info("jd", "getUserInfo----->resultUser：" + JSON.stringify(resultUser));
      if (!resultUser) {
        return system.getResult(null, "处理请求失败");
      }
      req.session.userPinInfo = resultUser.data;
      return system.getResultSuccess({ encryptChannelUserId: resultUser.data.encryptChannelUserId || "" });
    } catch (error) {
      this.logClient.error("jd", "req---->getUserInfo---->error:" + error.stack);
      return system.getResultFail(-200, "操作error");
    }
  }
  async opJdPayPageInfo(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.getJdPayPageAddr(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}}' }

      this.logClient.info("jd", "opJdPayPageInfo--tmpResult-->" + JSON.stringify(tmpResult));

      if (tmpResult && tmpResult.result && tmpResult.result == true) {
        var payDataResult = JSON.parse(tmpResult.data);
        if (payDataResult && payDataResult.success && payDataResult.success == true) {
          //更新订单信息
          var channelServiceNo = payDataResult.data.orderNumber;
          var needNo = pobj.actionBody.itemCode + "_" + payDataResult.data.orderNumber;
          var needNoOrderNo = payDataResult.data.orderNumber;
          await this.putPayOrderData(pobj, orderResult, channelServiceNo, needNo, needNoOrderNo, req);
          return system.getResultSuccess({ payUrl: payDataResult.data.returnUrl });
        }//成功           
      }
      return system.getResult(null, "pay page is error");
    }
    return system.getResultSuccess();
  }

  async getJdPayPageAddr(itemCode, itemCodeList, req) {//获取京东下单
    try {
      const { Signer, Context } = require('../jd-gateway-sdk');
      let ctx = new Context('x3k0s704lfun.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: 'A46DC38C2435B0FFF8615B284B958A93', //替换自己的AK
        secretAccessKey: '0D661D3C4890563AE73B7AE50C6207A8' //替换自己的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: req.session.userPinInfo.channelUserId,
      //   serviceId: itemCodeList[1],
      //   itemCode: itemCode,
      //   platform: 6,
      //   orderNum: 1,
      //   articleType: 1,
      //   additions: '{ \"247\": 0 }'
      // };//这是需要提交的数据------有附加项
      var post_data = {
        pin: req.session.userPinInfo.channelUserId,
        serviceId: itemCodeList[1],
        itemCode: itemCode,
        platform: 6,
        orderNum: 1,
        articleType: 1
      };//这是需要提交的数据      

      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.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
      }

      this.logClient.info("jd", "req---->getJdPayPageAddr---->options:" + JSON.stringify(options));
      this.logClient.info("jd", "req---->getJdPayPageAddr---->tmpContent:" + 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();
      });
      return reqResult;
    } catch (errorMsg) {
      this.logClient.error("jd", "req---->getJdPayPageAddr---->error:" + error.stack);
      return { success: false, code: -200, msg: error.stack };
    }
  }
  async pushJdPayOrder(pushData, req) {//处理京东推送的订单信息
    try {
      var signResult = await this.createSign(pushData, "F6FBD101C7571ADE231670F080653874", 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.skuId == "FW_GOODS-582064-1") {
        param = {
          actionProcess: pushData.actionProcess,
          actionType: "updateOrderPayStatus",
          actionBody: {
            channelUserId: pushData.jdPin,
            payStatus: "yfk",
            channelItemCode: pushData.skuId,
            needNoOrderNo: pushData.orderId,
            buyerMoblie: pushData.mobile
          },
          isUser: "yes"
        };
      }//自助注册产品
      else {
        //有返回用户信息进行用户ID加密
        param = {
          actionProcess: pushData.actionProcess,
          actionType: "addOrderAndDelivery",
          actionBody: {
            channelUserId: pushData.jdPin,
            payStatus: "yfk",
            channelItemCode: pushData.skuId,
            needNo: pushData.skuId + "_" + pushData.orderNumber,
            needNoOrderNo: pushData.orderNumber,
            buyerMoblie: pushData.mobile
          },
          isUser: "yes"
        };
      }//商标注册【专家辅助申请】、商标注册【担保申请】和 除商标之外的产品


      var reqUrl = this.channelApiUrl + "/action/tmOrder/springBoard";

      this.logClient.error("jd", "req---->pushJdPayOrder---->params:" + JSON.stringify(param) + "，reqUrl:" + reqUrl);

      var resultUser = await this.execClient.execPostTK(param, reqUrl, tokenInfo.data.token);
      if (!resultUser) {
        this.logClient.error("jd", "req---->pushJdPayOrder---->error:" + JSON.stringify(resultUser));
        return system.getResult(null, "req error");
      }
      return resultUser;

    } catch (error) {
      this.logClient.error("jd", "req---->pushJdPayOrder---->操作error:" + error.stack);
      return system.getResultFail(-200, "操作error");
    }
  }
  //----------------------------jd------操作------------end

  //----------------------------gsb------操作------------start

  async opGsbPayPageInfo(pobj, orderResult, req) {//操作下单的数据跟渠道订单关联
    if (!pobj.actionBody.itemCode) {
      return system.getResult(null, "itemCode param is not empty");
    }
    try {
      var tokenInfo = await this.getToken(pobj.actionProcess);
      if (tokenInfo.status != 0) {
        return tokenInfo;
      }
      var param = {
        actionProcess: pobj.actionProcess,
        actionType: "subGsbOrderInfo",
        actionBody: {
          channelUserId: req.session.userPinInfo.channelUserId,
          channelItemCode: pobj.actionBody.itemCode,
          order_param: {
            mobile_phone: req.session.userPinInfo.userMoblie || "18888888888",//必填
            goods_list: [{//必填
              goods_name: pobj.actionBody.itemCode,
              goods_quantity: 1,
            }],
            order_price: 300,//必填
            province_name: "",//省
            city_name: "",//市
            district_name: ""//区
          }
        },
        isUser: "yes"
      };
      var reqUrl = this.channelApiUrl + "/action/tmOrder/springBoard";
      console.log("req---->opGsbPayPageInfo---->params:" + JSON.stringify(param) + "，reqUrl:" + reqUrl);
      var result = await this.execClient.execPostTK(param, reqUrl, tokenInfo.data.token);
      if (!result) {
        console.log("req---->opGsbPayPageInfo---->error:" + JSON.stringify(result));
        return system.getResult(null, "req error");
      }
      return result;

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

    return system.getResultSuccess();
  }
  async pushGsbPayOrder(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.skuId == "FW_GOODS-582064-1") {
        param = {
          actionProcess: pushData.actionProcess,
          actionType: "updateOrderPayStatus",
          actionBody: {
            channelUserId: pushData.jdPin,
            payStatus: "yfk",
            channelItemCode: pushData.serviceCode,
            needNoOrderNo: pushData.orderId,
            buyerMoblie: pushData.mobile
          },
          isUser: "yes"
        };
      }//自助注册产品
      else {
        //有返回用户信息进行用户ID加密
        param = {
          actionProcess: pushData.actionProcess,
          actionType: "addOrderAndDelivery",
          actionBody: {
            channelUserId: pushData.jdPin,
            needNo: pushData.skuId + "_" + pushData.orderId,
            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");
    }
  }
  //----------------------------gsb------操作------------end

}
module.exports = tmqueryCtl;
