<template>
  <view class="container">
    <view class="content1" v-if="content1">
      <view class="mark" v-show="showSearch"></view>
      <view class="messageBg1"></view>
      <view class="messageBg2"></view>
      <view class="messageCard">
        <image src="../../static/images/null.png" mode="scaleToFill" />
        <text>暂无缴费信息</text>
        <button hover-class="button-hover" @click="toSearch">帮人代缴</button>
      </view>
      <view class="pop-up" v-show="showSearch">
        <view class="top">
          <text>代缴人信息</text>
          <image
            src="../../static/images/close.png"
            mode="scaleToFill"
            @click="close1"
          />
        </view>
        <view class="name">
          <text>姓 名</text>
          <input
            v-model="studentName"
            type="text"
            placeholder="请输入姓名"
            placeholder-style="color:rgba(0, 0, 0, 0.29);"
          />
        </view>
        <view class="studentNo">
          <text>身份证</text>
          <input
            v-model="studentNo"
            type="text"
            placeholder="请输入身份证"
            placeholder-style="color:rgba(0, 0, 0, 0.29);"
          />
        </view>
        <view class="remark">
          说明：新生输入身份证号码代替学号，老生输入学号
        </view>
        <view class="confirm">
          <button hover-class="button-hover" @click="close1">取消</button>
          <button hover-class="button-hover" @click="searchDetailMess">
            确认
          </button>
        </view>
      </view>
    </view>
    <view class="content2" v-if="showMess">
      <view class="order">订单号：{{ orderNo }}</view>
      <view class="mark" v-show="showSearch"></view>
      <view class="messageBg1"></view>
      <view class="messageBg2"></view>
      <view class="messageCard">
        <view class="item-form">
          <view class="item">
            <text class="ite">收费单位 </text>
            <text class="content">南昌交通学院</text>
          </view>
          <view class="item">
            <text class="ite">姓名 </text>
            <text class="content">{{ studentName }}</text>
          </view>
          <view class="item">
            <text class="ite">证件号 </text>
            <text class="content">{{ studentNo }}</text>
          </view>
          <view class="item">
            <text class="ite">专业 </text>
            <text class="content">{{ majorName }}</text>
          </view>
          <view class="item">
            <text class="ite">班级 </text>
            <text class="content">{{ className }}</text>
          </view>
          <view class="item">
            <text class="ite">缴费学年 </text>
            <text class="content">{{ years }}</text>
          </view>
          <!-- <template v-if="(itemArr.length = 0)"> -->
          <view class="item-pay" v-for="item in Arr">
            <text class="ite">{{ item.id }} </text>
            <text class="content">¥{{ item.money }}</text>
          </view>
          <!-- </template> -->
          <view class="item">
            <text class="ite">总金额 </text>
            <text class="content">¥{{ realPayAmount }}</text>
          </view>
        </view>

        <button @click="getPay()" hover-class="button-hover" v-if="payStatu1">
          支付
        </button>
        <text class="okPay" v-if="payStatu2">已支付</text>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      content1: true,
      showMess: false,
      showSearch: false,
      studentName: "",
      studentNo: "",
      majorName: "",
      className: "",
      years: "",
      realPayAmount: "",
      Arr: [],
      payStatu1: true,
      payStatu2: false,
      homeUrl: "https://jtishfw.ncjti.edu.cn/jiaofei/backendApi",
      openId: "",
      cardNumber: "",
      orderNo: "", //订单号
      //微信支付参数
      appId: "",
      timeStamp: "",
      nonceStr: "",
      package: "",
      signType: "",
      paySign: "",
    };
  },
  onLoad(options) {
    this.getOpenId();
  },
  methods: {
    toSearch() {
      this.showSearch = !this.showSearch;
    },
    close1() {
      this.showSearch = !this.showSearch;
    },
    toShowMess() {
      this.showMess = !this.showMess;
      this.content1 = false;
    },

    //获取openId
    getOpenId() {
      let openId = localStorage.getItem("openId");
      if (!openId) {
        let openId = this.getQueryString("openId");
        let error = this.getQueryString("error");
        let homeWeb =
          "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxd87cbe1db0437303&redirect_uri=https://jtishfw.ncjti.edu.cn/jiaofei/backendApi/wechat/pub/auth&response_type=code&scope=snsapi_base&state=pages/parentPay/parentPay#wechat_redire";
        if (!openId) {
          window.location.href = homeWeb;
        } else if (error) {
          uni.showToast({
            title: "openId获取失败",
            icon: "error",
            mask: true,
            duration: 1000,
          });
        } else {
          localStorage.setItem("openId", openId);
        }
      }
    },

    //代缴费
    searchDetailMess() {
      let that = this;
      let cardNumber = localStorage.getItem("cardNumber");
      let url =
        that.homeUrl +
        `/tuitionpayment/payableinfo/payableInfo/${that.studentNo}/${that.studentName}`;
      uni.request({
        url: url,
        header: {
          card_number: cardNumber,
          Accept: "application/json",
          "Content-Type": "application/x-www-form-urlencoded;charset=utf-8",
          "X-Requested-With": "XMLHttpRequest",
        },
        method: "GET",
        sslVerify: true,
        success: ({ data, statusCode, header }) => {
          if (!data.success) {
            uni.showToast({
              title: data.message,
              icon: "error",
              mask: true,
              duration: 1000,
            });
          } else {
            uni.showToast({
              title: "信息查询中",
              icon: "loading",
              mask: true,
              duration: 500,
            });
            that.showSearch = !that.showSearch;
            that.toShowMess();
            let res = data.data;
            that.studentName = res.studentName;
            that.studentNo = res.studentNo;
            that.years = res.years;
            that.majorName = res.majorName;
            that.className = res.className;
            that.realPayAmount = res.realPayAmount;
            that.getPayDetail(res.payItemDetail);
            if (res.pay) {
              that.payStatu1 = false;
              that.payStatu2 = true;
            } else {
              that.payStatu1 = true;
              that.payStatu2 = false;
            }
          }
        },
        fail: (error) => {},
      });
    },

    //获取学费明细
    getPayDetail(len) {
      //获取明细款项名称数组
      var arr = len.match(/[^\\u4e00-\\u9fa5]+/g);
      var itemIdArr = arr.filter(function (value) {
        return value !== ".";
      });
      //获取明细金额数组
      var itemMoneyArr = len.match(/([0-9]+\.[0-9]+)+/g);
      //拼接成对象数组
      var item = [];
      for (var i in (itemIdArr, itemMoneyArr)) {
        var c = {
          id: itemIdArr[i],
          money: itemMoneyArr[i],
        };
        item.push(c);
      }
      this.Arr = item;
    },

    //支付
    getPay() {
      uni.showToast({
        title: "支付中，请稍等",
        icon: "loading",
        mask: true,
        duration: 1000,
      });
      this.getOrderNo(); //获取订单号
    },

    //获取订单号
    getOrderNo() {
      let that = this;
      let cardNumber = localStorage.getItem("cardNumber");
      let url =
        that.homeUrl + `/tuitionpayment/payorder/${that.studentNo}/create`;
      uni.request({
        url: url,
        data: {},
        header: {
          card_number: cardNumber,
          Accept: "application/json",
          "Content-Type": "application/json",
          "X-Requested-With": "XMLHttpRequest",
        },
        method: "POST",
        sslVerify: true,
        success: ({ data, statusCode, header }) => {
          let res = data.data;
          that.orderNo = res.orderNo;
          if (!data.success) {
            uni.showToast({
              title: data.message,
              icon: "error",
              mask: true,
              duration: 2000,
            });
          } else {
            that.getwxParam(); //拿微信支付参数
          }
        },
        fail: (error) => {},
      });
    },

    //获取微信支付参数
    getwxParam() {
      let that = this;
      let cardNumber = localStorage.getItem("cardNumber");
      let openId = localStorage.getItem("openId");
      let url = that.homeUrl + "/pay/ccb/getJsApiParam";
      uni.request({
        url: url,
        data: {
          orderNo: that.orderNo,
          openId: openId,
        },
        header: {
          card_number: cardNumber,
          Accept: "application/json",
          "Content-Type": "application/json",
          "X-Requested-With": "XMLHttpRequest",
        },
        method: "GET",
        sslVerify: true,
        success: ({ data, statusCode, header }) => {
          if (!data.success) {
            uni.showToast({
              title: data.message,
              icon: "error",
              mask: true,
              duration: 2000,
            });
          } else {
            let res = data.data;
            that.appId = res.appId;
            that.timeStamp = res.timeStamp;
            that.nonceStr = res.nonceStr;
            that.package = res.package;
            that.signType = res.signType;
            that.paySign = res.paySign;
            that.wxPay();
          }
        },
        fail: (error) => {},
      });
    },

    //吊起微信支付
    wxPay() {
      let that = this;
      function onBridgeReady() {
        WeixinJSBridge.invoke(
          "getBrandWCPayRequest",
          {
            appId: that.appId, //公众号ID，由商户传入
            timeStamp: that.timeStamp, //时间戳，自1970年以来的秒数
            nonceStr: that.nonceStr, //随机串
            package: that.package,
            signType: that.signType, //微信签名方式：
            paySign: that.paySign, //微信签名
          },
          function (res) {
            if (res.err_msg == "get_brand_wcpay_request:ok") {
              // 使用以上方式判断前端返回,微信团队郑重提示：
              //res.err_msg将在用户支付成功后返回ok，但并不保证它绝对可靠。
            }
          }
        );
      }
      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();
      }
    },

    //获取当前URL指定参数
    getQueryString(name) {
      let url = window.location.href; // 获取URL
      let pattern = new RegExp("[\?\&]" + name + "=([^\&]+)", "i"); // 正则匹配URL
      let matcher = pattern.exec(url);
      if (matcher == null || matcher.length < 1) {
        return false;
      }
      return decodeURIComponent(matcher[1]); // 输出指定的参数值 中文也可以
    },
  },
};
</script>

<style lang="scss" scoped>
@import url("./css/parentPay.min.css");
</style>
