/*
 * @Description: 支付微信h5, jsapi, 第三方收银台，跳转）
 * @Date: 2020-07-28 15:03:52
 * @LastEditors: gzw
 * @LastEditTime: 2020-07-31 10:46:33
 */

import { Notify } from "@qg/cherry-ui";
import qs from "qs";

/**
 * payByWeixinJsapi
 * @description: 微信通过jsapi支付
 *               可以在微信浏览器调起支付
 * @param {type}
 * @return:
 */
function payByWeixinJsapi(info, callback) {
  function onBridgeReady() {
    // eslint-disable-next-line no-undef
    WeixinJSBridge.invoke(
      "getBrandWCPayRequest",
      {
        appId: info.appId, //公众号名称，由商户传入
        timeStamp: info.timeStamp, //时间戳，自1970年以来的秒数
        nonceStr: info.nonceStr, //随机串
        package: `prepay_id=${info.prepayId}`,
        signType: "MD5", //微信签名方式：
        paySign: info.sign //微信签名
      },
      function(res) {
        if (res.err_msg == "get_brand_wcpay_request:ok") {
          // 使用以上方式判断前端返回,微信团队郑重提示：
          //res.err_msg将在用户支付成功后返回ok，但并不保证它绝对可靠。
          callback("ok");
        } else if (res.err_msg == "get_brand_wcpay_request:cancel") {
          // 支付取消
          callback("cancel");
        } else {
          // 支付失败
          callback("fail");
        }
      }
    );
  }
  if (typeof WeixinJSBridge == "undefined") {
    if (document.addEventListener) {
      document.addEventListener("WeixinJSBridgeReady", onBridgeReady, false);
    } else if (document.attachEvent) {
      document.attachEvent("WeixinJSBridgeReady", onBridgeReady);
      document.attachEvent("onWeixinJSBridgeReady", onBridgeReady);
    }
  } else {
    onBridgeReady();
  }
}

/**
 * payByWeixinH5
 * @description: 微信通过H5支付
 *               可以在浏览器调起微信支付
 * @param {type}
 * @return:
 */
function payByWeixinH5(info) {
  if (!info.url) return;
  const currentPath = encodeURIComponent(
    window.location.href + qs.stringify(info.params, { encode: true, addQueryPrefix: true })
  );
  window.location.href = `${info.url}&redirect_url=${currentPath}`;
}

/**
 * payByThirdPartyCashier
 * @description: 第三方收银台
 * @param {type}
 * @return:
 */
function payByThirdPartyCashier(info) {
  if (!info.url) return;
  const currentPath = encodeURIComponent(
    window.location.href + qs.stringify(info.params, { encode: true, addQueryPrefix: true })
  );
  window.location.href = `${info.url}&redirect_uri=${currentPath}`;
}

/**
 * @description: 支付方式判断， 返回promise
 * @param {String} type 支付方式，THIRD -> 第三方，MWEB -> H5支付， JSAPI -> jsapi支付，默认支付方式，THIRD
 * @param {Object/String} payInfo 支付信息
 * @return {Promise} 回调
 */
export function payByWay(type = "THIRD", payInfo) {
  return new Promise(resolve => {
    if (type === "JSAPI") {
      payByWeixinJsapi(payInfo, function(e) {
        if (e === "ok") {
          Notify({ type: "success", message: "支付成功" });
        } else {
          Notify({ type: "warning", message: "支付失败" });
        }
        resolve(e);
      });
    } else if (type === "MWEB") {
      payByWeixinH5(payInfo);
      resolve();
    } else {
      payByThirdPartyCashier(payInfo);
      resolve();
    }
  });
}
