<template>
  <view class="container">
    <button class="order" @click="toOrder()" v-show="showOrder">
      订单查询
    </button>
    <view
      class="mark"
      v-show="showSearch || showLeaveMess"
      @click="markClose()"
    ></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 class="bottom-a">
        <navigator
          url="#"
          open-type="navigate"
          hover-class="navigator-hover"
          @click="toSearch"
        >
          帮人代缴
        </navigator>
        <navigator
          url="#"
          open-type="navigate"
          hover-class="navigator-hover"
          @click="toLeaveMess"
        >
          信息有误？点击反馈
        </navigator>
      </view>
    </view>
    <view class="pop-up" v-show="showSearch">
      <view class="top">
        <text>代缴人信息</text>
        <view class="close" @click="close1">
          <view class="image"></view>
        </view>
      </view>
      <view class="name">
        <text>姓 名</text>
        <input
          v-model="SeaStudentName"
          type="text"
          placeholder="请输入姓名"
          placeholder-style="color:rgba(0, 0, 0, 0.29);"
        />
      </view>
      <view class="studentNo">
        <text>学 号</text>
        <input
          v-model="SeaStudentNo"
          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 class="leaveMess" v-show="showLeaveMess">
      <view class="top">
        <text>信息反馈</text>
        <view class="close" @click="close2">
          <view class="image"></view>
        </view>
      </view>
      <view class="name">
        <text>姓&#12288;名 :</text>
        <input
          type="text"
          placeholder="请输入姓名"
          v-model="feedbackPersonName"
          placeholder-style="color: #B3B3B3;"
        />
      </view>
      <view class="tel">
        <text>联系人 :</text>
        <input
          type="text"
          placeholder="请输入联系人手机号码"
          v-model="feedbackPersonPhone"
          placeholder-style="color: #B3B3B3;"
        />
      </view>
      <text class="title">反馈信息 ：</text>
      <textarea
        placeholder=""
        placeholder-class="textarea-placeholder"
        maxlength="512"
        v-model="feedbackInfo"
      />
      <button hover-class="button-hover" @click="putMess">提交</button>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      showLeaveMess: false,
      showSearch: false,
      showOrder: false,
      studentName: "",
      studentNo: "",
      SeaStudentNo: "",
      SeaStudentName: "",
      majorName: "",
      className: "",
      years: "",
      realPayAmount: "",
      Arr: [],
      payStatu1: true,
      payStatu2: false,
      homeUrl: "https://jtishfw.ncjti.edu.cn/jiaofei/backendApi",
      notifyUrl:
        "https://jtishfw.ncjti.edu.cn/jiaofei/backendApi/pay/jxnxs/notify/",
      openId: "",
      orderNo: "", //订单号
      cardNumber: "",
      //反馈者
      feedbackPersonName: "",
      feedbackPersonPhone: "",
      feedbackInfo: "",
      scrollTop: 0,
      //微信支付参数
      appId: "",
      timeStamp: "",
      nonceStr: "",
      package: "",
      signType: "",
      paySign: "",
    };
  },
  onLoad(options) {
    // this.loginFilter(); //获取用户cardNumber
  },
  methods: {
    toSearch() {
      this.showSearch = true;
    },
    close1() {
      this.showSearch = false;
    },
    close2() {
      this.showLeaveMess = false;
    },
    toLeaveMess() {
      this.showLeaveMess = true;
    },

    markClose() {
      this.showLeaveMess = false;
      this.showSearch = false;
    },

    //获取cardNumber
    loginFilter() {
      let cardNumber = sessionStorage.getItem("cardNumber");

      if (!cardNumber) {
        let cardNumber = this.getQueryString("cardNumber");
        let error = this.getQueryString("error");
        let errorMsg = this.getQueryString("errorMsg");
        let homeWeb = `https://open.wecard.qq.com/connect/oauth/authorize?app_key=2DDC9DBF32F28845&response_type=code&scope=snsapi_userinfo&ocode=1015730314&redirect_uri=${this.homeUrl}/wechat/weixiao/auth/&connect=curLogin&state=${this.homeUrl}/wechat/weixiao/auth/`;
        if (error) {
          uni.showToast({
            title: errorMsg,
            icon: "error",
            mask: true,
            duration: 1000,
          });
        } else if (!cardNumber) {
          window.location.href = homeWeb;
        } else {
          sessionStorage.setItem("cardNumber", cardNumber);
          this.getDetailMess();
        }
      } else {
        this.getDetailMess();
      }
    },

    //换取详情信息
    getDetailMess() {
      let that = this;

      let cardNumber = sessionStorage.getItem("cardNumber");

      let url = that.homeUrl + "/tuitionpayment/payableinfo/payableInfo";
      uni.showToast({
        title: "信息获取中",
        icon: "loading",
        mask: true,
        duration: 1500,
      });
      uni.request({
        url: url,
        data: {},
        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.data === null) {
            uni.redirectTo({ url: "/pages/parentPay/parentPay" });
          } else {
            let res = data.data;
            that.studentName = res.studentName;
            that.studentNo = res.studentNo;
            that.majorName = res.majorName;
            that.className = res.className;
            that.years = res.years;
            that.realPayAmount = res.realPayAmount;

            that.getPayDetail(res.payItemDetail);
            if (res.pay) {
              that.payStatu1 = false;
              that.payStatu2 = true;
              that.showOrder = true;
            } else {
              that.payStatu1 = true;
              that.payStatu2 = false;
            }
            that.getOpenId();
          }
        },
        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;
    },

    //获取openid
    getOpenId() {
      let openId = localStorage.getItem("openId");

      if (!openId) {
        let openId = this.getQueryString("openId");
        let error = this.getQueryString("error");
        let errorMsg = this.getQueryString("errorMsg");
        let homeWeb = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxd87cbe1db0437303&redirect_uri=${this.homeUrl}/wechat/pub/auth&response_type=code&scope=snsapi_base&state=pages/Pay/pay#wechat_redire`;
        if (error) {
          uni.showToast({
            title: errorMsg,
            icon: "error",
            mask: true,
            duration: 1000,
          });
        } else if (!openId) {
          window.location.href = homeWeb;
        } else {
          localStorage.setItem("openId", openId);
        }
      }
    },

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

    //获取订单号
    getOrderNo() {
      let that = this;

      let cardNumber = sessionStorage.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.getPayMethod();
          }
        },
        fail: (error) => {},
      });
    },

    //获取支付方式
    getPayMethod() {
      let url = this.homeUrl + "/payMethodSetting/currentPay";

      uni.request({
        url: url,
        data: {},
        header: {
          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 }) => {
          let res = data.data;
          if (data.success) {
            if (res.currentPayMethod === "1") {
              this.getwxParam();
            } else {
              this.nsPay();
            }
          } else {
            uni.showToast({
              title: data.message,
              icon: "error",
              mask: true,
              duration: 1000,
            });
          }
        },
        fail: (error) => {},
      });
    },

    //获取微信支付参数
    getwxParam() {
      let that = this;

      let cardNumber = sessionStorage.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();
      }
    },

    //拉起农商行支付
    nsPay() {
      let O = "5494ec3310685daa218382619dd20e27";

      let out_no = this.orderNo;

      let amount = this.realPayAmount;

      let appoint_notify = this.notifyUrl;

      let mainUrl = `https://q.jxnxs.com/newpay?O=${O}&out_no=${out_no}&amount=${amount}&appoint_notify=${appoint_notify}`;

      window.location.href = mainUrl;
    },

    //获取当前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]); // 输出指定的参数值 中文也可以
    },

    //代缴费
    searchDetailMess() {
      if (!this.SeaStudentNo || !this.SeaStudentName) {
        uni.showToast({
          title: "学号或姓名不能为空",
          icon: "error",
          mask: true,
          duration: 1000,
        });
      } else {
        let that = this;
        let cardNumber = sessionStorage.getItem("cardNumber");
        let url =
          that.homeUrl +
          `/tuitionpayment/payableinfo/payableInfo/${that.SeaStudentNo}/${that.SeaStudentName}`;
        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;
              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);
              that.SeaStudentNo = "";
              that.SeaStudentName = "";
              if (res.pay) {
                that.payStatu1 = false;
                that.payStatu2 = true;
                that.showOrder = true;
              } else {
                that.payStatu1 = true;
                that.payStatu2 = false;
              }
            }
          },
          fail: (error) => {},
        });
      }
    },

    //提交反馈信息
    putMess() {
      let that = this;

      let cardNumber = sessionStorage.getItem("cardNumber");

      let url = that.homeUrl + "/tuitionpayment/feedbackmsg/save";

      uni.request({
        url: url,
        data: {
          feedbackPersonName: that.feedbackPersonName,
          feedbackPersonPhone: that.feedbackPersonPhone,
          feedbackInfo: that.feedbackInfo,
        },
        header: {
          card_number: cardNumber,
          Accept: "application/json",
          "Content-Type": "application/json",
          "X-Requested-With": "XMLHttpRequest",
        },
        method: "POST",
        sslVerify: true,
        success: ({ data, statusCode, header }) => {
          if (data.success) {
            uni.showToast({
              title: data.message,
              icon: "success",
              mask: true,
              duration: 1000,
            });
            that.close2();
            that.feedbackPersonName = "";
            that.feedbackPersonPhone = "";
            that.feedbackInfo = "";
          } else {
            uni.showToast({
              title: data.message,
              icon: "error",
              mask: true,
              duration: 1000,
            });
          }
        },
        fail: (error) => {},
      });
    },

    //跳转订单页面
    toOrder() {
      uni.redirectTo({ url: "/pages/order/order" });
    },
  },
};
</script>

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