<template>
<view id="free">
    <view class="free-title">
        <image mode="widthFix" src="https://ibrand-miniprogram.oss-cn-hangzhou.aliyuncs.com/%E5%B0%8F%E7%A8%8B%E5%BA%8F/%E5%88%86%E7%BB%84(1).png">

        </image>
    </view>
    <view class="free-content">
        <view class="inputs-box">
            <view class="item mx-1px-bottom first-input">
                <span>会员名</span>
                <input type="text" disabled="true" :value="user.nick_name"></input>
            </view>
            <view class="item mx-1px-bottom second-input">
                <span>手机号</span>
                <input type="text" disabled="true" :value="user.mobile"></input>
            </view>
            <view class="item second-input">
                <span>免单金额</span>
                <input type="text" placeholder="请询问服务员后输入" placeholder-class="input-placeholder" @input="changeAmount" :value="amount"></input>
            </view>
        </view>
        <view class="pay-btn" @tap="soonPay">立即支付</view>
        <view class="pay-attention">*会员充值概不退款</view>
    </view>
    <view class="free-foot">
        <image mode="widthFix" src="https://ibrand-miniprogram.oss-cn-hangzhou.aliyuncs.com/%E5%B0%8F%E7%A8%8B%E5%BA%8F/%E5%88%86%E7%BB%8401.png"></image>
    </view>
</view>
</template>
<script>
import {pageLogin, getUrl,config,is} from '@/common/js/utils.js';

export default {
  data() {
    return {
      user: '',
      amount: ''
    };
  },

  onLoad(e) {
    pageLogin(getUrl(), token => {
      this.queryUserInfo(token);
    });
  },

  components: {},
  props: {},
  methods: {
    changeAmount(e) {
      var money = e.detail.value;

      if (!money) {
        money = '';
      } else if (/\S*$/.test(money)) {
        money = money.replace(/[^\d\.]|^\./g, '').replace(/\.{2}/g, '.').replace(/^([1-9]\d*|0)(\.\d{1,2})(\.|\d{1})?$/, '$1$2').replace(/^0\d{1}/g, '0');
      }

      this.setData({
        amount: money
      });
    },

    queryUserInfo(token) {
      this.$http.get({
        api: 'api/me',
        header: {
          Authorization: token
        }
      }).then(res => {
        if (res.statusCode == 200) {
          this.setData({
            user: res.data.data
          });
        } else {
          wx.showModal({
            title: '提示',
            content: '数据请求失败',
            success: res => {}
          });
        }
      });
    },

    //获取openid
    getOpenid() {
      return new Promise((resolve, reject) => {
        wx.login({
          success: res => {
            this.$http.post({
              api: `api/oauth/miniprogram/openid`,
              data: {
                code: res.code
              }
            }).then(res => {
              res = res.data;
              resolve(res.data.openid);
            }).catch(() => {
              reject('获取openid失败');
            });
          },
          fail: () => {
            wx.showModal({
              content: "接口请求失败"
            });
          }
        });
      });
    },

    soonPay() {
      var message = '';

      if (this.amount == '') {
        message = '请您输入免单金额';
        wx.showModal({
          content: message,
          showCancel: false
        });
      } else {
        //请求接口
        this.submitPay();
      }
    },

    //请求免单支付接口
    submitPay() {
      wx.showLoading({
        title: '加载中'
      });
      this.getOpenid().then(res => {
        var token = this.$cookieStorage.get('user_token');
        var data = {
          amount: this.amount * 100,
          channel: 'wx_lite',
          openid: res
        };
        this.$http.post({
          api: `api/users/balance/charge/amount`,
          data: data,
          header: {
            Authorization: token
          }
        }).then(res => {
          res = res.data;

          if (res.status) {
            this.newcharge(true, res.data.charge);
          } else {
            this.newcharge(false, res.message);
          }
        }).catch(rej => {
          wx.showModal({
            content: '请求支付失败，请重试！'
          });
        });
      }).catch(() => {
        wx.hideLoading();
        wx.showModal({
          content: '支付失败',
          showCancel: false
        });
      });
    },

    // 新版支付
    newcharge(success, charge) {
      if (success) {
        var that = this;

        if (charge.pay_scene == 'test') {
          wx.showModal({
            content: '不支持模拟支付',
            showCancel: false
          });
          wx.hideLoading();
        } else {
          wx.requestPayment({
            "timeStamp": charge.wechat.timeStamp,
            "nonceStr": charge.wechat.nonceStr,
            "package": charge.wechat.package,
            "signType": charge.wechat.signType,
            "paySign": charge.wechat.paySign,
            success: res => {
              if (res.errMsg == 'requestPayment:ok') {
                wx.hideLoading();
                wx.redirectTo({
                  url: `/pages/recharge/success/success?order_no=${charge.order_no}`
                });
              } else {
                wx.showModal({
                  content: '调用支付失败！',
                  showCancel: false
                });
              }
            },
            fail: err => {
              wx.hideLoading();

              if (err.errMsg == 'requestPayment:fail cancel') {
                wx.switchTab({
                  url: `/pages/user/personal/personal`
                });
              } else {
                wx.showModal({
                  content: '调用支付失败！',
                  showCancel: false
                });
              }
            }
          });
        }
      } else {
        wx.hideLoading();
        wx.showModal({
          content: charge || '请求支付失败，请重试！',
          showCancel: false
        });
      }
    },

    setData: function (obj) {
      let that = this;
      let keys = [];
      let val, data;
      Object.keys(obj).forEach(function (key) {
        keys = key.split('.');
        val = obj[key];
        data = that.$data;
        keys.forEach(function (key2, index) {
          if (index + 1 == keys.length) {
            that.$set(data, key2, val);
          } else {
            if (!data[key2]) {
              that.$set(data, key2, {});
            }
          }

          data = data[key2];
        });
      });
    }
  },
  computed: {},
  watch: {}
};
</script>
<style rel="stylesheet/less" lang="less">
    @import "free";
</style>