<template>
	<view class="page-content">
    <!--主要内容-->
    <view class="main-content">
      <!--顶部内容-->
      <view class="top">
        <image class="top-img" :src="top_icon"></image>
        <view class="top-title">{{ pay_info.money > 0 ? '确认支付' : '确认开通' }}</view>
      </view>
      <!-- 兑换码信息 -->
      <view class="info">
        <view class="bg-bar"></view>
        <view class="info-content">
          <view class="price" v-if="pay_info.money > 0">
            <view class="price-unit">¥</view>
            <view class="money">{{ pay_info.money || 0 }}</view>
          </view>
          <view class="coding">会员卡号：{{ code }}</view>
        </view>
      </view>
      <!--奖励列表-->
      <view class="give">
        <view class="give-content" v-if="svip_info">
          <view class="title">开通赠送</view>
          <view class="give-list">
            <view class="give-item" v-if="svip_info.quota > 0">
              <view class="left">
                <image class="top-img" :src="use_invite_4" mode="heightFix"></image>
                <view class="give-title">瓶装酒额度</view>
              </view>
              <view class="right">{{ svip_info.quota }}</view>
            </view>
            <view class="give-item" v-if="svip_info.wine_quota > 0">
              <view class="left">
                <image class="top-img" :src="use_invite_2" mode="heightFix"></image>
                <view class="give-title">封坛酒额度</view>
              </view>
              <view class="right">{{ svip_info.wine_quota }}</view>
            </view>
            <view class="give-item" v-if="svip_info.vegetable_quota > 0">
              <view class="left">
                <image class="top-img" :src="use_invite_1" mode="heightFix"></image>
                <view class="give-title">特色菜卡额度</view>
              </view>
              <view class="right">{{ svip_info.vegetable_quota }}</view>
            </view>
            <view class="give-item" v-if="Object.values(svip_info.coupon || {}).length > 0">
              <view class="left">
                <image class="top-img" :src="use_invite_3" mode="heightFix"></image>
                <view class="give-title">会员礼包</view>
              </view>
              <view class="right">{{ Object.values(svip_info.coupon || {}).length }}</view>
            </view>
          </view>
        </view>
      </view>
      <!--支付相关-->
      <view class="pay-info">
        <!--支付方式-->
        <view class="pay-type" v-if="pay_info.money > 0">
          <pay :payType="pay_info.pay_type" @change="changePayType"></pay>
        </view>
        <!--支付按钮-->
        <view class="pay-btn" v-if="pay_info.money > 0" @click="confirmPayment">确认支付</view>
        <view class="pay-btn" v-else @click="confirmPayment">确认开通</view>
      </view>


    </view>
    <!-- 授权登录 -->
    <authorize @onLoadFun="onLoadFun" :isAuto="isAuto" :isShowAuth="isShowAuth" @authColse="authClose"></authorize>
  </view>
</template>

<script>
import {mapGetters} from "vuex";
import authorize from '@/components/Authorize';
import { HTTP_REQUEST_URL } from '@/config/app.js';
import { vipExchangeCodeInfo, vipExchangeCodePayment} from "@/api/user";
import pay from "@/components/payment/pay";

export default {
  name: 'business',
  components: {
    authorize,
    pay
  },
  computed: {
    ...mapGetters(['isLogin', 'uid', 'userInfo', 'viewColor'])
  },
  data() {
    return {
      code: '',
      top_icon: '',
      info: {},
      svip_info: {},
      // 登录相关
      isAuto: false, //没有授权的不会自动授权
      isShowAuth: false,//是否隐藏授权
      // 支付相关
      pay_info: {
        money: 0.00,// 支付金额
        pay_type: 'weixin',
        // #ifdef H5
        return_url: 'http://' + window.location.host + '/pages/users/order_list/index',
        // #endif
      },
      // 图标
      use_invite_1: '',
      use_invite_2: '',
      use_invite_3: '',
      use_invite_4: '',
    }
  },
  onReady() {
    this.top_icon = `${HTTP_REQUEST_URL}/static/images/icon/invitation_code_icon.png`;
    this.use_invite_1 = `${HTTP_REQUEST_URL}/static/images/icon/use_invite_1.png`;
    this.use_invite_2 = `${HTTP_REQUEST_URL}/static/images/icon/use_invite_2.png`;
    this.use_invite_3 = `${HTTP_REQUEST_URL}/static/images/icon/use_invite_3.png`;
    this.use_invite_4 = `${HTTP_REQUEST_URL}/static/images/icon/use_invite_4.png`;
  },
  onLoad(options) {
    this.code = options.code || '';
    // 判断：如果不存在兑换码  返回个人中心
    if(this.code.length <= 0){
      this.errorAndBack('无有效兑换码！');
      return false;
    }
    // 判断：是否登录
    if (!this.isLogin) {
      // 未登录  授权登录
      this.isAuto = true;
      this.isShowAuth = true
    }else{
      // 已登录  获取信息
      this.init();
    }
  },
  methods: {
    // 授权回调
    onLoadFun() {
      if(this.isLogin){
        this.isShowAuth = false;
        this.init();
      }
    },
    // 授权关闭
    authClose(e) {
      this.isShowAuth = e
    },
    // 授权成功 初始化
    init () {
      this.getCodeInfo();
    },
    // 错误提示 并且返回个人中心
    errorAndBack(tips){
      this.$util.tips({ content: tips}, function () {
        uni.switchTab({
          url: '/pages/user/index',
        });
      });
    },
    // 获取兑换码信息
    getCodeInfo(){
      let _this = this;
      vipExchangeCodeInfo({
        exchange_code: _this.code
      }).then(res => {
        if (res.status == 200) {
          let data = res.data || {};
          let status = Number(data.status);
          // 状态：0=未激活，1=已激活，2=已使用，3=作废
          switch (status){
            case 0:
              _this.errorAndBack('兑换码未激活！');
              break;
            case 1:
              _this.pay_info.money = data.svip_price || 0;
              _this.svip_info = data.svip_info || {};
              break;
            case 2:
              _this.errorAndBack('兑换码已使用！');
              break;
            case 3:
              _this.errorAndBack('兑换码已作废！');
              break;
            default:
              _this.errorAndBack('无有效兑换码！');
          }
        }
      }).catch(err => {
        _this.errorAndBack(err);
      });
    },
    // 修改支付方式
    changePayType(value){
      this.pay_info.pay_type = value;
    },
    // 确认付款
    confirmPayment(){
      let _this = this;
      let payInfo = Object.assign({},_this.pay_info);
      payInfo.code = _this.code;
      // console.log('支付类型',payInfo.pay_type)
      // 提示
      let config = {
        content: payInfo.money > 0 ? '是否确认支付并且开通当前会员卡？' : '是否确认开通当前会员卡？',
        confirmText: payInfo.money > 0 ? '支付' : '开通',// 确认按钮文字
        showCancel: true, // 是否显示取消按钮
        cancelText: '取消', // 取消按钮文字
      };
      _this.$util.tips(config, function () {
        if (payInfo.pay_type == 'weixin') {
          // #ifdef H5
          payInfo.pay_type = _this.$wechat.isWeixin() ? 'weixin' : 'h5'
          // #endif
          // #ifdef MP
          payInfo.pay_type = 'routine'
          // #endif
          // #ifdef APP-PLUS
          payInfo.pay_type = 'weixin'
          // #endif
        }
        uni.showLoading({title: '处理中...', mask: true});
        vipExchangeCodePayment(payInfo).then(res => {
          if (res.status == 200) {
            if(Number(_this.pay_info.money) > 0){
              let status = res.data.status,
                  orderId = res.data.result.order_id,
                  callback_key = res.data.result.pay_key,
                  jsConfig = res.data.result.config;
              // let goPages = '/pages/order_pay_status/index?order_id=' + orderId + '&msg=' + res.message;
              let goPages = '/pages/user/index';
              switch (status) {
                case 'ORDER_EXIST':
                case 'EXTEND_ORDER':
                case 'PAY_ERROR':
                case 'error':
                  return _this.$util.Tips({
                    title: res.message
                  }, {
                    tab: 1,
                    url: goPages
                  });
                  break;
                case 'success':
                  return _this.$util.Tips({
                    title: res.message,
                    icon: 'success'
                  }, {
                    tab: 1,
                    url: goPages
                  });
                  break;
                case 'alipay':
                case "alipayQr":
                  uni.navigateTo({
                    url: '/pages/order_pay_back/index?keyCode=' + callback_key + '&url=' +
                        jsConfig
                  })
                  return;
                  break;
                  // #ifndef MP
                case "wechat":
                case "weixin":
                case "weixinApp":
                  jsConfig.timeStamp = jsConfig.timestamp;
                  // #ifndef APP-PLUS
                  _this.$wechat.pay(jsConfig).then(res => {
                    return _this.$util.Tips({
                      title: res.message,
                      icon: 'success'
                    }, {
                      tab: 1,
                      url: goPages
                    });
                  }).catch(res => {
                    if (res.errMsg == 'chooseWXPay:cancel') return _this.$util.Tips({
                      title: '取消支付'
                    }, {
                      tab: 1,
                      url: goPages + '&status=0'
                    });
                  })
                  // #endif
                  // #ifdef APP-PLUS
                  let mp_pay_name=''
                  if(uni.requestOrderPayment){
                    mp_pay_name='requestOrderPayment'
                  }else{
                    mp_pay_name='requestPayment'
                  }
                  uni[mp_pay_name]({
                    provider: 'wxpay',
                    orderInfo: jsConfig,
                    success: (e) => {
                      // let url = '/pages/order_pay_status/index?order_id=' + orderId + '&msg=支付成功';
                      let url = '/pages/user/index';

                      return _this.$util.Tips({
                        title: '支付成功',
                        icon: 'success'
                      }, {
                        tab: 1,
                        url: url
                      });
                    },
                    fail: (e) => {
                      // let url = '/pages/order_pay_status/index?order_id=' + orderId + '&msg=取消支付';
                      let url = '/pages/user/index';
                      return _this.$util.Tips({
                        title: '取消支付',
                      }, {
                        tab: 1,
                        url: url
                      });
                    },
                    complete: () => {
                      // let url = '/pages/order_pay_status/index?order_id=' + orderId + '&msg=取消支付';
                      let url = '/pages/user/index';
                      return _this.$util.Tips({
                        title: '',
                      }, {
                        tab: 1,
                        url: url
                      });
                    },
                  });
                  // #endif
                  break;
                  // #endif
                  // #ifdef MP
                case "routine":
                  jsConfig.timeStamp = jsConfig.timestamp;
                  _this.toPay = true;
                  let mp_pay_name=''
                  if(uni.requestOrderPayment){
                    mp_pay_name='requestOrderPayment'
                  }else{
                    mp_pay_name='requestPayment'
                  }
                  uni[mp_pay_name]({
                    ...jsConfig,
                    success: function(res) {
                      uni.hideLoading();
                      return _this.$util.Tips({
                        title: '支付成功',
                        icon: 'success'
                      }, {
                        tab: 1,
                        url: goPages
                      });
                    },
                    fail: function(e) {
                      // let pages = '/pages/order_pay_status/index?order_id=' + orderId + '&msg=取消支付'
                      let pages = '/pages/user/index';
                      return _this.$util.Tips({
                        title: '取消支付'
                      }, {
                        tab: 1,
                        // url: pages + '&status=0'
                        url: pages
                      });
                    },
                  })
                  break;
                  // #endif
                case "balance":
                  //余额
                  return _this.$util.Tips({
                    title: res.msg
                  }, {
                    tab: 1,
                    url: goPages + '&status=1'
                  });
                  break;
                  // #ifdef H5
                case 'h5':
                  let host = window.location.protocol + "//" + window.location.host;
                  // let url = `${host}/pages/order_pay_status/index?order_id=${orderId}&msg=${res.message}`
                  let url = '/pages/user/index';
                  let eUrl = encodeURIComponent(url)
                  let jsurl = jsConfig.mweb_url || jsConfig.h5_url
                  let locations = `${jsurl}&redirect_url=${eUrl}`
                  setTimeout(() => {
                    location.href = locations;
                  }, 100);
                  break;
                  // #endif
                  // #ifdef APP-PLUS
                case 'alipayApp':
                  uni.requestPayment({
                    provider: 'alipay',
                    orderInfo: jsConfig,
                    success: (e) => {
                      return _this.$util.Tips({
                        title: '支付成功',
                        icon: 'success'
                      }, {
                        tab: 1,
                        url: goPages
                      });
                    },
                    fail: (e) => {
                      // let pages = '/pages/order_pay_status/index?order_id=' + orderId + '&msg=支付失败'
                      let pages = '/pages/user/index';
                      return _this.$util.Tips({
                        title: '支付失败'
                      }, {
                        tab: 1,
                        url: pages
                      });
                    },
                    complete: () => {
                      uni.hideLoading();
                      // let pages = '/pages/order_pay_status/index?order_id=' + orderId + '&msg=取消支付'
                      let pages = '/pages/user/index';
                      return _this.$util.Tips({
                        title: ''
                      }, {
                        tab: 1,
                        url: pages
                      });
                    },
                  });
                  break;
                  // #endif
                default:
                  // let pages = '/pages/order_pay_status/index?order_id=' + orderId + '&msg=取消支付'
                  let pages = '/pages/user/index';
                  return _this.$util.Tips({
                    title: '取消支付'
                  }, {
                    tab: 1,
                    // url: pages + '&status=0'
                    url: pages
                  });
              }
            }else{
              _this.$util.Tips({
                title: '操作成功！',
              },{
                tab: 1,
                url: '/pages/user/index'
              });
            }
          }
        }).catch(err => {
          uni.hideLoading();
          _this.$util.Tips({
            title: err
          });
        });
      });
    },


  }
}
</script>

<style scoped lang="scss">
.page-content{
  width: 100vw;
  min-height: 100vh;
  background-color: #f0f0f0;

  // 顶部信息
  .top{
    width: 100%;
    height: 300rpx;
    background: #c10100;
    display: inline-flex;
    flex-direction: row;
    flex-wrap: nowrap;
    align-items: center;
    justify-content: center;
    padding-bottom: 30rpx;
    .top-img{
      width: 160rpx;
      height: 160rpx;
      margin-right: 15rpx;
    }
    .top-title{
      font-size: 35rpx;
      font-weight: bold;
      color: #fcfdfb;
    }
  }
  // 兑换码信息
  .info{
    padding: 0 10rpx;
    position: relative;
    top: -75rpx;
    .bg-bar{
      background: #a60807;
      border-radius: 50rpx;
      width: 100%;
      height: 20rpx;
    }
    .info-content{
      background: #ffffff;
      margin: 0 20rpx;
      position: relative;
      top: calc(0rpx - (20rpx / 2));

      .price{
        display: inline-flex;
        flex-direction: row;
        flex-wrap: nowrap;
        align-items: baseline;
        justify-content: center;
        width: 100%;
        height: 130rpx;
        border-bottom: 2rpx dashed #f8f8f8;
        padding-top: 30rpx;
        box-shadow: inset 0rpx 20rpx 30rpx 0rpx #feeeee;
        .price-unit{
          font-size: 28rpx;
        }
        .money{
          font-size: 50rpx;
          font-weight: bold;
        }
      }
      .coding{
        height: 90rpx;
        line-height: 90rpx;
        padding-left: 30rpx;
        font-size: 26rpx;
        color: #575757;
      }
    }
  }
  // 奖励信息
  .give{
    width: 100vw;
    padding: 20rpx;
    position: relative;
    top: -75rpx;
    .give-content{
      padding: 20rpx;
      background: #ffffff;
      border-radius: 15rpx;
      .title{
        width: 100%;
        height: 70rpx;
        line-height: 50rpx;
        font-size: 30rpx;
        font-weight: bold;
      }
      .give-list{
        width: 100%;
        display: inline-flex;
        flex-direction: column;
        flex-wrap: nowrap;
        justify-content: flex-start;
        align-items: center;
        .give-item{
          width: 100%;
          display: inline-flex;
          flex-direction: row;
          flex-wrap: nowrap;
          justify-content: space-between;
          align-items: center;
          .left{
            display: inline-flex;
            flex-direction: row;
            flex-wrap: nowrap;
            justify-content: flex-start;
            align-items: center;
            .top-img{
              width: 60rpx;
              height: 60rpx;
              border-radius: 50%;
            }
            .give-title{
              font-size: 28rpx;
              padding-left: 30rpx;
            }
          }
          .right{
            color: #c40000;
            width: 150rpx;
            text-align: right;
          }
        }
        .give-item:not(:last-child){
          margin-bottom: 30rpx;
        }
      }
    }
  }
  // 支付相关
  .pay-info{
    width: 100vw;
    padding: 20rpx;
    position: relative;
    top: -75rpx;

    .box-title{
      margin: 30rpx 0;
      height: 50rpx;
      line-height: 50rpx;
      font-size: 28rpx;
      padding-left: 20rpx;
      font-weight: bold;
      position: relative;
    }
    .box-title:after{
      content: "";
      position: absolute;
      left: 0;
      top: calc((50rpx - 30rpx) / 2);
      width: 10rpx;
      height: 30rpx;
      background: #1777ff;
    }
    // 支付方式
    .pay-type{
      .box-content{
        .pay-label:not(:last-child){
          margin-bottom: 20rpx;
        }
        .pay-item{
          height: 120rpx;
          padding: 20rpx;
          width: 100%;
          border: 2rpx solid #d9dce4;
          border-radius: 15rpx;
          display: inline-flex;
          flex-direction: row;
          flex-wrap: nowrap;
          align-items: center;
          justify-content: space-around;
          .left{
            width: calc(100% - 80rpx);
            display: inline-flex;
            flex-direction: row;
            flex-wrap: nowrap;
            align-items: center;
            justify-content: flex-start;
            .animated{
              width: 44rpx;
              height: 44rpx;
              border-radius: 50%;
              text-align: center;
              line-height: 44rpx;
              background-color: #fe960f;
              color: #fff;
              font-size: 30rpx;
              margin-right: 15rpx;
            }
            .icon-weixin2 {
              background-color: #41b035;
            }
            .icon-icon34 {
              background-color: #4295D5;
            }
            .pay-item-info{
              .pay-name{
                text-align: left;
                border-right: 1px solid #eee;
                justify-content: left;
              }
              .tip{
                text-align: left;
                font-size: 26rpx;
                color: #aaa;
              }
            }
          }
          .right{
            width: 80rpx;
            display: inline-flex;
            flex-direction: row;
            flex-wrap: nowrap;
            align-items: center;
            justify-content: flex-end;
          }
        }
      }
    }
    // 确认支付
    .pay-btn{
      width: 100%;
      background: #1777ff;
      color: #FFFFFF;
      border-radius: 15rpx;
      font-size: 30rpx;
      text-align: center;
      height: 70rpx;
      line-height: 70rpx;
      margin-top: 100rpx;
    }
    .not-btn{
      background-color: #909399;
      color: #fff;
    }
  }
}
</style>
