<template>
  <div>
    <div class="rechargeImg"></div>

    <!--<p class="balanceTitle">车牌{{carNumber}}的余额: {{acctBalance==0?0:(acctBalance/100).toFixed(2)}}元</p>-->
    <p class="balanceTitle">车牌<span style="color: #4194EF;font-weight: 600">  {{carNumber}}</span>的余额: <span style="color: #4194EF;font-weight: 600">{{(acctBalance/100).toFixed(2)}}</span>元</p>

    <ul class="rechargeList">
      <li v-for="(i, index) in dataList" @click="chooseMoney(index,i)">
        <div :class="{isActive:index==currentIndex}">{{i}} 元</div>
      </li>

    </ul>

    <div class="submit-box" @click="toRecharge">
      确定充值
    </div>
  </div>
</template>

<script>
import { getOpenId, vxPayQuery } from "@/api/orderPay/orderPay";
export default {
  name: "rechargeList",
  data() {
    return {
      acctBalance: "",
      fileOrder: 100,
      dataList: ["0.1", "0.2", "300", "400", "500", "600"],
      currentIndex: 0,
      webAppCode: "",
      custId:'',
      currentMoney:0.1
    };
  },
  created() {
    this.acctBalance = this.$route.query.acctBalance; //车牌颜色
    this.carNumber = this.$route.query.carNumber;
    this.custId = this.$route.query.custId;
    console.log(this.clientBrowser)
    if (this.$utils.clientBrowser() == "微信") {
      this.webAppCode = this.getCode();
    }
  },
  methods: {
    toRecharge() {
      let me = this
      var codeParams = {
        code: this.webAppCode,
        appId: this.$utils.myVxAppId
      };
      getOpenId(codeParams).then(res => {
        if (res.code == 0) {
          me.vxPay(res.data);
        } else if (res.code == 40163) { //code been used, hints[重复code问题]
          this.$msgbox('提示', '请重新支付！重复code问题')
          console.log(res.message);
        } else {
          this.$msgbox('提示', '请重新支付')
        }
      });
    },
    vxPay(openidData) {
      let vm = this;
      var wxParams = {};
      wxParams.backType = 2;
      wxParams.orgId = this.$utils.myOrgId;
      wxParams.payType = 4;// 1:支付宝 2：微信 3：银联 10:H5   4微信公众号
      wxParams.terminalSource = 7;//请求端来源 1： 任你停 2：pda 3：微信公共号 7:H5扫码 10页面支付
      wxParams.carNumber = this.carNumber;
      wxParams.paySrcType = 201;//101停车支付  201充值
      wxParams.openId = openidData
      wxParams.appId = this.$utils.myVxAppId;
      wxParams.acctType = '1'
      wxParams.custId = this.custId
      wxParams.rechargeID = this.custId
      wxParams.rechargeType = '2'
      wxParams.realPayMoney = this.currentMoney*100  // 实付金额
      wxParams.rechargeFee = this.currentMoney*100  //充值实际得到金额
      wxParams.acctBalance = this.acctBalance  //账户余额


      vxPayQuery(wxParams).then(res => {
        if (res.code == 0) { //
          if (res.data) {
            var data = res.data;
            console.log(JSON.stringify(data));
            if (typeof WeixinJSBridge === "undefined") { // 微信浏览器内置对象。参考微信官方文档
              if (document.addEventListener) {
                document.addEventListener("WeixinJSBridgeReady", vm.onBridgeReady(data), false);
              } else if (document.attachEvent) {
                document.attachEvent("WeixinJSBridgeReady", vm.onBridgeReady(data));
                document.attachEvent("onWeixinJSBridgeReady", vm.onBridgeReady(data));
              }
            } else {
              console.log("准备调用微信支付");
              vm.onBridgeReady(data);
            }
          } else {
            alert("没有找到返回值");
          }
        } else if (res.code == 1002) {//其他情况如【该卡号场内已存在】
          console.log(res.message);
          MessageBox.confirm("", {
            message: res.message,
            title: "温馨提示",
            showCancelButton: false,
            confirmButtonText: "确定"
          }).then(action => {
            if (action == "confirm") {     //确认的回调
              console.log("确定");
              this.$router.go(-1);
            }
          }).catch(err => {
            if (err == "cancel") {     //取消的回调
              console.log("取消");
            }
          });
        } else {
          alert(res.message);
        }
      });
    },
    onBridgeReady(params) {
      let me = this;
      console.log("调用微信支付WeixinJSBridge");
      WeixinJSBridge.invoke(
        "getBrandWCPayRequest", params,
        //
        // 'getBrandWCPayRequest', { // 下面参数内容都是后台返回的
        //   'appId': data.appId, // 公众号名称，由商户传入
        //   'timeStamp': data.timeStamp, // 时间戳
        //   'nonceStr': data.nonceStr, // 随机串
        //   'package': data.package, // 预支付id
        //   'signType': data.signType, // 微信签名方式
        //   'paySign': data.paySign // 微信签名
        // },
        function(res) {
          // 使用以上方式判断前端返回,微信团队郑重提示：res.err_msg将在用户支付成功后返回ok，但并不保证它绝对可靠。
          if (res.err_msg === "get_brand_wcpay_request:ok") {
            console.log("成功");
            // this.$msgbox('提示', '支付成功')
            // alert(me.acctBalance)
            // alert(me.currentMoney*100)
            me.acctBalance = Number(me.acctBalance)+Number(me.currentMoney*100)
            // alert(this.acctBalance)
            alert('支付成功')
            // me.$router.go(-2);
          } else {
            console.log("失败");
            // this.$msgbox('提示', '')
            alert('支付失败')
            me.$router.go(-2);
          }
        }
      );
    },
    getCode() {
      var appID = this.$utils.myVxAppId;
      var code = this.getUrlParam("code");
      var local = window.location.href;
      if (code == null || code === "") {
        window.location.href = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + appID + "&redirect_uri=" + encodeURIComponent(local) + "&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect";
      } else {
        return code;
      }
    },
    getUrlParam(name) {
      var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
      var r = window.location.search.substr(1).match(reg);
      if (r != null) return unescape(r[2]);
      return null;
    },
    chooseMoney(index,i) {
      this.currentIndex = index;
      this.currentMoney = i
    }
  },
  directives: {
    numberOnly: {
      bind: function(el) {
        el.handler = function() {
          el.value = Number(el.value.replace(/\D+/, ""));
        };
        el.addEventListener("input", el.handler);
      },
      unbind: function(el) {
        el.removeEventListener("input", el.handler);
      }
    }
  }
};
</script>

<style scoped lang="scss">
  .rechargeImg {
    width: 80px;
    height: 80px;
    margin: 20px auto;
    background: url("../../assets/images/recharge.png");
  }

  .balanceTitle {
    padding: 15px;
    background: #ccc;
    font-size: 16px;
    /*color: #fff;*/
  }

  .rechargeList {
    display: flex;
    flex-wrap: wrap;
    > li {
      flex: 0 0 50%;

      padding: 10px;
      > div {
        height: 50px;
        line-height: 50px;
        text-align: center;
        background: #f00;
        color: #fff;
        font-size: 18px;
        border-radius: 4px;
      }
      .isActive {
        background: linear-gradient(180deg, #3885D9 0%, #4194EF 100%);
      }
    }
  }

  .submit-box {
    width: 80%;
    height: 44px;
    line-height: 44px;
    border-radius: 4px;
    font-size: 20px;
    margin: 58px auto 0;
    background: linear-gradient(180deg, #3885D9 0%, #4194EF 100%);
    color: #fff;
    text-align: center;
  }

</style>
