<template>
  <view class="container">支付加载中... </view>
</template>

<script>
/**
 * 页面(url)传参字符串进行编码,解码
 * @param {Object} query
 * @description 页面跳转携带中文参数时,可使用
 */

export function qsDecode(query) {
  if (!query && typeof query !== "object") {
    throw new Error("error arguments", "qsDecode");
  }
  const target = {};
  Object.keys(query).forEach((key) => {
    target[key] = decodeURIComponent(query[key]);
  });
  return target;
}

/**
 * 获取上一个页面实例 $vm
 * @param {number} delta 页面层数
 * @description 可用于修改上一页数据
 */
export function getPrevPage(delta = 1) {
  const pages = getCurrentPages();
  if (delta > pages.length) {
    // 页面层数大于现有页面数
    return null;
  }
  const prevPage = pages[pages.length - (delta + 1)];
  if (prevPage) {
    return prevPage.$vm;
  }
  return null;
}

export default {
  data() {
    return {
      pageQuery: {},
    };
  },
  onLoad(options) {
    console.log("page onLoad", options);
    this.pageQuery = qsDecode(options);

    this.openPayment();
  },
  methods: {
    /**
     * 微信小程序支付
     */
    openPayment() {
      const paymentOptions = {
        timeStamp: this.pageQuery.timeStamp,
        nonceStr: this.pageQuery.nonceStr,
        package: this.pageQuery.package,
        signType: this.pageQuery.signType,
        paySign: this.pageQuery.paySign,
      };

      wx.requestPayment({
        ...paymentOptions,
        success: (res) => {
          console.log("[wx.requestPayment success]", res);

          this.goNext({
            code: "SUCCESS",
            orderNo: this.pageQuery.orderNo,
          });
        },
        fail: (err) => {
          console.error("[wx.requestPayment fail]", err);
          let msg = "支付失败";
          if (err.errMsg.includes("fail cancel")) {
            msg = "支付取消";
          }
          uni.showToast({
            icon: "none",
            title: msg,
            duration: 1500,
          });

          this.goNext({
            code: "FAIL",
            orderNo: this.pageQuery.orderNo,
          });
        },
      });
    },
    goNext({ code = "FAIL", orderNo }) {
      const { dealPage } = this.pageQuery;
      const prevPage = getPrevPage();
      const payResultUrl = `${dealPage}${
        dealPage.includes("?") ? "&" : "?"
      }code=${code}&orderNo=${orderNo}`;

      prevPage.weburl = payResultUrl;
      uni.navigateBack();
    },
  },
};
</script>

<style lang="scss" scoped>
.container {
  text-align: center;
  color: #999;
  padding: 30px;
}
</style>
