<template>
    <section class="test-wise-cashier">
      <textarea class="info" v-model="info"></textarea>
      <div class="btn-sure" @click="handleGoPay">确认支付</div>
      <textarea class="info res" v-model="res" v-if="res"></textarea>
    </section>
</template>

<script>
export default {
  data() {
    return {
      info: "参数",
      res: ""
    };
  },
  created() {
    this.info = JSON.stringify(this.$route.query);
  },
  mounted() {
    window.js_api_param = {};
    window.jsApiCall = () => {
      window.WeixinJSBridge.invoke(
        "getBrandWCPayRequest",
        window.js_api_param,
        function(res) {
          if (res.err_msg == "get_brand_wcpay_request:ok") {
            alert("支付成功");
          }

          if (res.err_msg == "get_brand_wcpay_request:cancel") {
            alert("取消支付");
          }

          if (res.err_msg == "get_brand_wcpay_request:fail") {
            alert("支付失败");
          }
        }
      );
    };
  },
  methods: {
    handleGoPay() {
      let params = {};
      params.url = "https://api.wisecashier.com/mp_pay";
      params.data = {
        ...this.$route.query
      };
      alert(`请求参数：${JSON.stringify(params)}`);
      this.$net.req(params, this).then(
        r => {
          if (r) {
            this.res = JSON.stringify(r);
            if (r.meta.success) {
              window.js_api_param = r.data.js_param;
              this.res =
                this.res + "/n/r" + JSON.stringify(window.js_api_param);
              if (typeof WeixinJSBridge == "undefined") {
                if (document.addEventListener) {
                  document.addEventListener(
                    "WeixinJSBridgeReady",
                    window.jsApiCall,
                    false
                  );
                } else if (document.attachEvent) {
                  document.attachEvent("WeixinJSBridgeReady", window.jsApiCall);
                  document.attachEvent(
                    "onWeixinJSBridgeReady",
                    window.jsApiCall
                  );
                }
              } else {
                window.jsApiCall();
              }
            }
          }
        },
        e => {
          if (e) {
            this.res = JSON.stringify(e);
          }
        }
      );
    }
  }
};
</script>

<style lang="less" scoped>
.test-wise-cashier {
  padding: 20px 10px 10px;
  .info {
    width: 100%;
    height: 200px;
    padding: 10px;
    border: 1px #000 solid;
    border-radius: 8px;
    &.res {
      height: 400px;
    }
  }
  .btn-sure {
    width: 80%;
    height: 40px;
    line-height: 40px;
    margin: 20px auto;
    text-align: center;
    color: #fff;
    border-radius: 8px;
    background-color: red;
    &:active {
      opacity: 0.8;
    }
  }
}
</style>
