<template>
    <view>
        <!--<view class="order-title">-->
        <!--订单详情-->
        <!--</view>-->
        <view class="rechargeTop">
            <view class="toDetail uni-list-cell-pd uni-right">明细 ></view>
            <view class="rechargeNum uni-center">¥17.34</view>
        </view>



        <uni-section title="充值金额" type="line" padding>
            <uni-grid :column="3" :highlight="true" :showBorder="false" :square="false" @change="change">
                <uni-grid-item v-for="(item, index) in ListData" :index="index" :key="index"
                               >
                    <view class="grid-item-box" style="background-color: #fff;">
                        <view class="text" :class="currentIndex==index?'itemActive':''">{{item.text}}</view>
                    </view>
                </uni-grid-item>
            </uni-grid>
        </uni-section>

        <view class="uni-list-cell-pd">
            温馨提示：暂不支持退款，请谨慎选择充值金额！
        </view>
        <view class="border-bg"></view>


        <!--<view class="order-line-bold"></view>-->
        <view class="order-title">
            支付方法
        </view>
        <view class="order-line"></view>

        <view class="orderwaysview" @click="selPaywaysClick(0)">
            <image src="../../static/orderInfo/orderinfo-wechat.png" class="orderways"></image>
            <view class="order-info" style="margin-left: 8px;">
                微信支付
            </view>

            <image v-show="payWaysSel != 0" src="../../static/orderInfo/orderinfo-unsel.png"
                   class="orderwaysSel"></image>
            <image v-show="payWaysSel == 0" src="../../static/orderInfo/orderinfo-sel.png" class="orderwaysSel"></image>


        </view>

        <button @click="payClick" class="button-sp-area" type="primary" plain="true">确认充值</button>
        <view v-show="alertFlag">
            <div class="alertFlag">请先登录</div>
        </view>
    </view>
</template>

<script>
import common from "../../common/common.js";
export default {
  data() {
    return {
      ListData: [
        {
          text: '100元'
        },
        {
          text: '200元'
        },
        {
          text: '300元'
        },
        {
          text: '600元'
        },
        {
          text: '1000元'
        },
        {
          text: '其他'
        },
      ],
      currentIndex: 0,
      mycarNumber: '',
      myorderId: '',
      myparkCode: '',
      myorderinfo1: {},
      myorderinfo: {},
      payWaysSel: 0,
      myorderState: 0,
      mypaySrcType: '',
      selCoupon: {},
      appOrderTimeout: '',
      loginflag: 0,
      phoneNumb: '',
      totalFee: '', //应收
      alertFlag: false,
      unPayFee: '' //实收
    }
  },
  onLoad(params) {
    wx.showShareMenu({
      withShareTicket: true
    })
    this.mycarNumber = params.carNumber;
    this.myorderId = params.orderId;
    this.myparkCode = params.parkCode;
    this.myorderState = params.orderState;
    this.totalFee = params.totalFee
    this.unPayFee = params.unPayFee
    if (params.orderState == 5) {
      //停车补缴单 103
      this.mypaySrcType = '103'
    } else {
      this.mypaySrcType = '101'
    }
    // this.GetbillQueryInfo(this.mycarNumber, this.myorderId, this.myparkCode);
    this.getWxCode();
    this.PDlogin();
    //console.log("xxxmake = "+this.makedateFormat());
  },
  onShow() {
    var me = this;
    var userInfo = me.getGlobalUser("globalUser");
    if (userInfo != null) {
      me.phoneNumb = userInfo.userPhone;
    }
    var pages = getCurrentPages();
    var currPage = pages[pages.length - 1]; //当前页面
    console.log('currPage.data.selCoupon = ' + currPage.data.selCoupon);
    me.selCoupon = currPage.data.selCoupon;
    console.log(JSON.stringify(me.selCoupon));
    me.GetbillQueryInfo(me.mycarNumber, me.myorderId, me.myparkCode, me.selCoupon.cardNo, me.selCoupon.couponType, me.selCoupon
      .discValue);
    // GetbillQueryInfo(carnum, orderId, parkCode, cardNo, couponType, disValue) {
  },
  methods: {
    change(e) {

      let {
        index
      } = e.detail
      // this.list[index].badge && this.list[index].badge++
      this.currentIndex = index
      uni.showToast({
        title: `点击第${index + 1}个宫格`,
        icon: 'none'
      })
    },
    PDlogin() {
      var me = this;
      // var loginflag = 0;
      var globalUser = me.getGlobalUser("globalUser");
      if (globalUser == undefined || globalUser == null || globalUser.token == null || globalUser.token == undefined ||
        globalUser.token.length == 0) {
        me.loginflag = 0;
      } else {
        me.loginflag = 1;
      }
    },
    //选择优惠券
    DiscountClick() {
      console.log("gotoDiscountView");
      var me = this;
      if (me.loginflag == 0) {
        uni.showToast({
          title: '请先登录',
          icon: 'none',
          duration: 4000
        })
        return;
      }
      var myurl = 'use_couponList/use_couponList?plNo=' + me.myparkCode + '&parkingDura=' + me.myorderinfo.staytime +
        '&parkingFee=' + me.myorderinfo.orderTotalFee + '&carNumber=' + me.mycarNumber + '&carType=' + me.myorderinfo.carType;
      uni.navigateTo({
        url: myurl
      });
    },
    //选择支付方式
    selPaywaysClick(selNumb) {
      let me = this
      this.payWaysSel = selNumb;
      console.log("this.payWaysSel: " + this.payWaysSel);
      console.log(me.loginflag)
      if (this.payWaysSel == 1) {
        if (me.loginflag == 0) {
          uni.showToast({
            title: '请先登录',
            icon: 'none',
            duration: 2000
          })
          return;
        }
      }
    },
    payClick() {
      var me = this;
      me.goPay_billQueryInfo(me.mycarNumber, me.myorderId, me.myparkCode, me.selCoupon.cardNo, me.selCoupon.couponType,
        me.selCoupon.discValue);
      // if(me.myorderinfo.orderFee == 0){
      // 	uni.showModal({
      // 		title: '提示',
      // 		content: '0元无需支付',
      // 		showCancel: false,
      // 		success: function(res) {
      // 			if (res.confirm) {
      // 				console.log('0元无需支付');
      // 				me.GetbillQueryInfo(me.mycarNumber, me.myorderId, me.myparkCode ,me.selCoupon.cardNo ,me.selCoupon.couponType ,me.selCoupon.discValue);
      // 			}
      // 		}
      // 	});
      // 	return;
      // }
      // //用户选择微信支付
      // if (me.payWaysSel == 0) {
      // 	me.getWxPayinfo();
      // } else {
      // 	me.UseAccountPay();
      // }
    },
    getWxPayinfo() {
      var me = this;
      uni.showLoading({
        mask: true,
        title: "请稍后..."
      });
      uni.showNavigationBarLoading();
      var getwxpayinfoUrl = common.getwxpayinfoUrl;
      if (me.mypaySrcType == 101) {
        me.payQuery(100)
      } else {
        me.rltOrderId()
      }
    },
    rltOrderId() {
      var me = this;
      console.log(me.totalFee)
      console.log(me.unPayFee)
      var jsondata = {
        parkOrderIds: [me.myorderId],
        orderBigType: 100,
        payOrderType: 103,
        terminalSource: 11,
        operCode: me.phoneNumb,//订单生成操作人 如果是车主 传 custId
        operName: me.phoneNumb,//订单生成操作人名称 如果是车主 传车主名称或手机号
        orgId: common.public_orgId,
        orderActFee: me.myorderinfo.orderFee,
        orderTotalFee: me.unPayFee,
      };
      uni.request({
        url: common.doOrderCreate,
        data: JSON.stringify(jsondata),
        // url: getwxPayUnifiedorderUrl,
        // data: JSON.stringify(common.requestSign(jsondata)),
        dataType: "json",
        method: "POST",
        success: (res) => {
          if (res.data.code == 0) {
            console.log(res.data.data.rltOrderId);
            me.myorderId = res.data.data.rltOrderId
            console.log(me.myorderId)
            me.payQuery(100)
            // uni.hideNavigationBarLoading();
            // uni.hideLoading();
          } else {
            uni.showModal({
              title: '提示',
              content: res.data.message,
              showCancel: false,
              success: function (res) {
              }
            });
            // uni.showToast({
            // 	title: res.data.message,
            // 	// icon: none;
            // 	duration: 2000
            // })
          }
        },
        complete: () => {
          // uni.hideNavigationBarLoading();
          // uni.hideLoading();
        }
      });
    },
    payQuery(_orderBigType) {
      var me = this;
      console.log(me.totalFee)
      console.log(me.unPayFee)
      console.log(me.mypaySrcType)
      var jsondata = {
        orderBigType: _orderBigType,
        payOrderType: me.mypaySrcType,
        rltOrderId: me.myorderId,
        payType: 2,
        terminalSource: 11,
        orderActFee: me.myorderinfo.orderFee,
        orderTotalFee: me.unPayFee,
        // totalFee: '', //应收
        // unPayFee: '' //实收
        payUserId: me.getWxOpenid("WxOpenid"),
        terminalOS: uni.getSystemInfoSync().platform == 'android' ? 'AND' : 'IOS',
        //terminalOS:isAndroid?'AND':'IOS',
        //uni.getSystemInfoSync().platform
      };
      uni.request({
        //url: getwxpayinfoUrl,
        url: common.doPayUrl,
        data: JSON.stringify(jsondata),
        //data: JSON.stringify(common.requestSign(jsondata)),
        header: {
          'content-type': 'application/json'
        },
        dataType: "json",
        method: "POST",
        success: (res) => {
          console.log(res)
          if (res.statusCode == 200) {
            me.myorderinfo1 = res.data;
            // var code = res.data.code;
            console.log(JSON.stringify(res.data));
            // var mydata = res.data;
            var mydata = JSON.parse(res.data.data.jsPayRequest);
            me.MakeWxPay(mydata);
            uni.hideNavigationBarLoading();
            uni.hideLoading();
          }
        },
        complete: () => {
          uni.hideNavigationBarLoading();
          uni.hideLoading();
        }
      });
    },
    // 调用微信支付
    MakeWxPay(mydata) {
      console.log('3')
      var me = this;
      uni.requestPayment({
        provider: 'wxpay',
        timeStamp: mydata.timeStamp,
        //随机字符串，长度为32个字符以下
        nonceStr: mydata.nonceStr,
        //统一下单接口返回的 prepay_id 参数值，提交格式如：prepay_id=xx。
        package: mydata.package,
        signType: mydata.signType,
        paySign: mydata.paySign,
        success: function (res) {
          console.log('success:' + JSON.stringify(res));
          var myurl = '../wxPaySuccess/wxPaySuccess?carNumber=' + me.mycarNumber + '&payWays=微信&payMoney=' + me.myorderinfo
            .orderFee + '&appOrderTimeout=' + me.appOrderTimeout;
          uni.reLaunch({
            url: myurl
          });
        },
        fail: function (err) {
          console.log('fail:' + JSON.stringify(err));
          uni.showModal({
            title: '提示',
            content: '支付失败/取消',
            showCancel: false,
            success: function (res) {
              if (res.confirm) {
                console.log('支付失败');
              }
            }
          });
        }
      });
    },
    goPay_billQueryInfo(carnum, orderId, parkCode, cardNo, couponType, disValue) {
      var me = this;
      // uni.showLoading({
      // 	mask: true,
      // 	title: "请稍后..."
      // });
      uni.showNavigationBarLoading();
      var billQueryUrl = common.billQueryUrl;
      var jsondata = {
        carNumber: carnum,
        orderId: orderId,
        terminalSource: '11',
        parkCode: parkCode,
        cardNo: cardNo,
        couponType: couponType,
        disValue: disValue
      }
      uni.request({
        url: billQueryUrl,
        // data: JSON.stringify(jsondata),
        data: JSON.stringify(common.requestSign(jsondata)),
        header: {
          'content-type': 'application/json'
        },
        dataType: "json",
        method: "POST",
        success: (res) => {
          console.log(JSON.stringify(res.data));
          uni.hideNavigationBarLoading();
          uni.hideLoading();
          if (res.data.code == 0) {
            me.myorderinfo = res.data.data;
            me.appOrderTimeout = res.data.data.appOrderTimeout;
            if (me.myorderinfo.orderFee == 0) {


              // 101:停车付款单,102：停车预付单，103:停车补缴单，201：余额充值单,202：押金充值；301：会员卡购买单，302：会员卡续费
              //个人使用的卡券cardId
              // couponPersonId:
              // paySrcType: me.mypaySrcType,
              me.zeroPayUrl(me.mypaySrcType, res.data.data.orderId, me.selCoupon.custCardId);
            } else {
              //用户选择微信支付
              if (me.payWaysSel == 0) {
                me.getWxPayinfo();
              } else {
                me.UseAccountPay();
              }
            }
            // me.myorderinfo1 = res.data.data ;
            //
            // var code = res.data.code;
            //console.log(JSON.stringify(res.data));
          } else if (res.data.code == -10000) {
            uni.showModal({
              title: '提示',
              content: res.data.message,
              showCancel: false,
              success: function (res) {
                if (res.confirm) {
                  console.log('登录失效');
                  uni.clearStorageSync();
                }
              }
            });
          }
        },
        complete: () => {
          uni.hideNavigationBarLoading();
          uni.hideLoading();
        }
      });
    },
    // 0元支付
    zeroPayUrl(payOrderType, orderId, couponPersonId) {
      var me = this;
      uni.showLoading({
        mask: true,
        title: "请稍后..."
      });
      uni.showNavigationBarLoading();
      var zeroPayUrl = common.zeroPayUrl;
      var jsondata = {
        payOrderType: payOrderType,
        orderId: orderId,
        terminalSource: '11',
        couponPersonId: couponPersonId
      }
      uni.request({
        url: zeroPayUrl,
        // data: JSON.stringify(jsondata),
        data: JSON.stringify(common.requestSign(jsondata)),
        header: {
          'content-type': 'application/json'
        },
        dataType: "json",
        method: "POST",
        success: (res) => {
          console.log(JSON.stringify(res.data));
          uni.hideNavigationBarLoading();
          uni.hideLoading();
          if (res.data.code == 0) {
            uni.showModal({
              title: '提示',
              content: '支付成功！',
              showCancel: false,
              success: function (res) {
                me.GetbillQueryInfo(me.mycarNumber, me.myorderId, me.myparkCode, me.selCoupon.cardNo, me.selCoupon.couponType,
                  me.selCoupon
                    .discValue);
              }
            });
            // me.myorderinfo = res.data.data;
            // me.appOrderTimeout = res.data.data.appOrderTimeout;
            // // me.myorderinfo1 = res.data.data ;
            //
            // var code = res.data.code;
            //console.log(JSON.stringify(res.data));
          } else if (res.data.code == -10000) {
            uni.showModal({
              title: '提示',
              content: res.data.message,
              showCancel: false,
              success: function (res) {
                if (res.confirm) {
                  console.log('登录失效');
                  uni.clearStorageSync();
                }
              }
            });
          } else {
            uni.showModal({
              title: '提示',
              content: res.data.message,
              showCancel: false,
              success: function (res) {
                me.GetbillQueryInfo(me.mycarNumber, me.myorderId, me.myparkCode, me.selCoupon.cardNo, me.selCoupon.couponType,
                  me.selCoupon
                    .discValue);
              }
            });
          }
        },
        complete: () => {
          uni.hideNavigationBarLoading();
          uni.hideLoading();
        }
      });
    },
    //初始化订单信息
    GetbillQueryInfo(carnum, orderId, parkCode, cardNo, couponType, disValue) {
      var me = this;
      uni.showLoading({
        mask: true,
        title: "请稍后..."
      });
      uni.showNavigationBarLoading();
      var billQueryUrl = common.billQueryUrl;
      var jsondata = {
        carNumber: carnum,
        orderId: orderId,
        terminalSource: '11',
        parkCode: parkCode,
        cardNo: cardNo,
        couponType: couponType,
        disValue: disValue
      }
      uni.request({
        url: billQueryUrl,
        // data: JSON.stringify(jsondata),
        data: JSON.stringify(common.requestSign(jsondata)),
        header: {
          'content-type': 'application/json'
        },
        dataType: "json",
        method: "POST",
        success: (res) => {
          console.log(JSON.stringify(res.data));
          uni.hideNavigationBarLoading();
          uni.hideLoading();
          if (res.data.code == 0) {
            me.myorderinfo = res.data.data;
            me.appOrderTimeout = res.data.data.appOrderTimeout;
            // me.myorderinfo1 = res.data.data ;
            //
            // var code = res.data.code;
            //console.log(JSON.stringify(res.data));
          } else if (res.data.code == -10000) {
            uni.showModal({
              title: '提示',
              content: res.data.message,
              showCancel: false,
              success: function (res) {
                if (res.confirm) {
                  console.log('登录失效');
                  uni.clearStorageSync();
                }
              }
            });
          }
        },
        complete: () => {
          uni.hideNavigationBarLoading();
          uni.hideLoading();
        }
      });
    },
    // 获取openid
    getWxCode() {
      var that = this;
      uni.login({
        provider: 'weixin',
        success: function (loginRes) {
          console.log(JSON.stringify(loginRes));
          console.log(loginRes.code);
          that.get_WxOpenid(loginRes.code);
        }
      });
    },
    get_WxOpenid(code) {
      var me = this;
      console.log('123456');
      uni.showLoading({
        mask: true,
        title: "请稍后..."
      });
      uni.showNavigationBarLoading();
      var getOpenidUrl = common.getOpenidUrl;
      uni.request({
        url: getOpenidUrl,
        data: {
          appId: common.hs_wxPay_appId,
          code: code
        },
        header: {
          'content-type': 'application/json'
        },
        dataType: "json",
        method: "POST",
        success: (res) => {
          console.log(res)
          if (res.data.code == 0) {
            console.log('id')
            // me.myorderinfo = res.data.data;
            // // var code = res.data.code;
            uni.setStorageSync("WxOpenid", res.data.data.openid);
            console.log(JSON.stringify(res.data));
            console.log("wxopenid = " + res.data.data.openid);
            uni.hideNavigationBarLoading();
            uni.hideLoading();
          }
        },
        complete: () => {
          uni.hideNavigationBarLoading();
          uni.hideLoading();
        }
      });
    },
    // 使用余额支付
    UseAccountPay() {
      var me = this;
      console.log(me.loginflag + 'aaaaa')
      if (me.loginflag == 0) {
        console.log('123123')
        // this.alertFlag = true
        // uni.showToast({
        // 	title: '请先登录',
        // 	icon: 'none',
        // 	duration: 4000
        // })
        uni.showModal({
          title: '提示',
          showCancel: false,
          content: '未登录状态，请先登录！',
          success: function (res) {
            if (res.confirm) {
              console.log('用户点击确定');
            }
          }
        });
      } else {
        console.log('bbbb')
        uni.showLoading({
          mask: true,
          title: "请稍后...",
          duration: 4000
        });
        uni.showNavigationBarLoading();
        var accountPayUrl = common.accountPayUrl;
        var jsondata = {
          payType: '5', //支付方式-- 1:支付宝 2：微信 3：银联 4:微信公众号 5 个人账户
          orderId: me.myorderId,
          payFee: me.myorderinfo.orderFee,
          //支付单来源 101：停车付款单 102：停车预付单 103：停车补缴单 104 共享车位 201 余额充值单 202 押金充值单 301 会员卡购买单 302 会员卡续费
          paySrcType: me.mypaySrcType,
          terminalSource: '11', //小程序
          //个人使用的卡券cardId
          couponPersonId: me.selCoupon.custCardId,
          carNumber: me.mycarNumber,
          orderId: me.myorderId,
          paySource: '3',
          sourceType: '3',
          terminalSource: '11', //小程序
          recordArreaInfos: JSON.stringify([{
            "orderId": me.myorderId,
            "orderNotPayFee": me.myorderinfo.orderFee,
            "parkId": me.myparkCode
          }])
        };
        uni.request({
          url: accountPayUrl,
          data: JSON.stringify(common.requestSign(jsondata)),
          header: {
            'content-type': 'application/json'
          },
          dataType: "json",
          method: "POST",
          success: (res) => {
            uni.hideNavigationBarLoading();
            uni.hideLoading();
            console.log('余额支付 = ' + JSON.stringify(res.data));
            if (res.data.code == 0) {
              var myurl = '../wxPaySuccess/wxPaySuccess?carNumber=' + me.mycarNumber + '&payWays=余额&payMoney=' + me.myorderinfo
                .orderFee + '&appOrderTimeout=' + me.appOrderTimeout;
              uni.reLaunch({
                url: myurl
              });
            } else {
              uni.showToast({
                title: res.data.message,
                icon: 'none',
                duration: 4000
              })
            }
          },
          complete: () => {
            // uni.hideNavigationBarLoading();
            // uni.hideLoading();
          }
        });
      }
    }
  }
}
</script>

<style scoped lang="scss">
    .rechargeTop{
        height: 100px;
        background: #007AFF;
        color: #fff;
        position: relative;
    }
    .toDetail{
        /*text-align: right;*/

    }
    .rechargeNum{
        font-size: 30px;
    }
    .text {
        width: 80%;
        height: 60px;
        line-height: 60px;
        margin: 10px auto;
        border: 1px solid #ccc;
        text-align: center;
    }

    .itemActive {
        background: #f0ad4e;
    }

    .order-title {
        font-size: 18px;
        margin-left: 16px;
        margin-top: 15px;
        font-weight: bold;
        color: #404040;
    }

    .order-info {
        font-size: 14px;
        margin-left: 15px;
        margin-top: 12px;
        color: #404040;
    }

    .order-line {
        background: #D9D9D9;
        height: 1px;
        margin-top: 12px;
        margin-left: 15px;
        padding: 0px;
        overflow: hidden;
        /* 透明度 */
        opacity: 0.5;
    }

    .order-line-bold {
        background: #FAFAFA;
        height: 12px;
        margin-top: 12px;
        padding: 0px;
        overflow: hidden;
    }

    .flex-row-justify-between {
        display: flex;
        flex-direction: row;
        justify-content: space-between;
    }

    .flex-row-justify-end {
        display: flex;
        flex-direction: row;
        /* 水平对齐*/
        align-items: baseline;

    }

    .order-discount {
        color: #C8C7CC;
        margin-right: 20 upx;
        /* margin-right: 12px ; */
        /* margin-top:12px ; */

    }

    .orderwaysview {
        display: flex;
        flex-direction: row;
    }

    .orderways {
        width: 18px;
        height: 18px;
        margin-left: 15px;
        margin-top: 14px;
    }

    .orderwaysSel {
        width: 16px;
        height: 16px;
        margin-left: auto;
        margin-right: 14px;
        margin-top: 14px;
        /* justify-content:flex-end; */
    }

    .button-sp-area {
        margin: 0 auto;
        width: 60%;
        margin-top: 40px;

    }
</style>
