<template>
  <view class="page-content">
    <!--主要内容-->
    <view class="main-content" :style="{ 'background-image': `url(${top_icon})`}">
      <!--商户信息-->
      <view class="block" v-if="mer_info">
        <view class="block-title">确认邀请店铺</view>
        <view class="mer">
          <image class="mer_avatar" :src="mer_info.mer_avatar || '/static/images/f.png'" />
          <view class="mer_name">{{ mer_info.mer_name || '' }}</view>
        </view>
      </view>
      <!--赠送信息-->
      <view class="block" v-if="level_info.quota > 0 || level_info.wine_quota > 0 || level_info.vegetable_quota > 0 || level_info.oil_quota > 0 || Object.values(coupon_list).length > 0">
        <view class="block-title">加入赠送奖励</view>
        <view class="give-item" v-if="level_info.quota > 0">
          <view class="left">
            <image class="give-icon" :src="quota_icon" />
            <view class="give-title">瓶装酒额度</view>
          </view>
          <view class="give-num">{{ level_info.quota || 0 }}</view>
        </view>
        <view class="give-item" v-if="level_info.vegetable_quota > 0">
          <view class="left">
            <image class="give-icon" :src="vegetable_quota_icon" />
            <view class="give-title">菜卡额度</view>
          </view>
          <view class="give-num">{{ level_info.vegetable_quota || 0 }}</view>
        </view>
        <view class="give-item" v-if="level_info.oil_quota > 0">
          <view class="left">
            <image class="give-icon" :src="oil_quota_icon" />
            <view class="give-title">油卡额度</view>
          </view>
          <view class="give-num">{{ level_info.oil_quota || 0 }}</view>
        </view>
        <view class="give-item" v-if="level_info.wine_quota > 0">
          <view class="left">
            <image class="give-icon" :src="wine_quota_icon" />
            <view class="give-title">封坛酒额度</view>
          </view>
          <view class="give-num">{{ level_info.wine_quota || 0 }}</view>
        </view>
        <view class="give-item" v-if="Object.values(coupon_list).length > 0">
          <view class="left">
            <image class="give-icon" :src="coupon_icon" />
            <view class="give-title">赠送优惠券</view>
          </view>
          <view class="give-coupon-list">
            <view class="coupon-item" v-for="(couponItem,couponIndex) in coupon_list" :key="couponIndex">
              {{ couponItem.title || '' }}
            </view>
          </view>
        </view>
        <view class="give-item" v-if="Number(level_info.integral_switch) == 1">
          <view class="left">
            <image class="give-icon" :src="integral_icon" />
            <view class="give-title">餐费积分</view>
          </view>
          <view class="give-num">{{ integralNum || '0.00' }}</view>
        </view>
      </view>
      <!--选择支付方式-->
      <view class="pay-type" v-if="Number(level_info.price) > 0">
        <pay :payType="pay_info.pay_type" @change="changePayType"></pay>
      </view>
      <!--操作按钮-->
      <view class="join-btn">
        <view class="join-btn-content" @click="submitJoinApplyInfo">
          <view class="join-text">立即加入</view>
          <view class="join-price" v-if="Number(level_info.price) > 0">需支付¥{{ Number(level_info.price) }}</view>
        </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 {merShareholderLevelInfo, merShareholderMerInfo, merShareholderSubmitJoinInfo, merShareholderGetJoinInfo} from "@/api/store";
import pay from "@/components/payment/pay";

export default {
  name: 'business',
  components: {
    authorize,
    pay
  },
  computed: {
    ...mapGetters(['isLogin', 'uid', 'userInfo', 'viewColor']),
    // 餐费积分数量
    integralNum(){
      let info = Object.assign({}, this.level_info);
      let type = Number(info.integral_give_type) || 0;
      let num = Number(info.integral_give_num) || 0;
      if(type === 1) num = Number(info.integral_give_num) * Number(info.integral_cycle_num)

      return Number(num).toFixed(2);
    },
  },
  data() {
    return {
      // 登录相关
      isAuto: false, //没有授权的不会自动授权
      isShowAuth: false,//是否隐藏授权
      // 图片
      top_icon: '',
      quota_icon: '',
      wine_quota_icon: '',
      vegetable_quota_icon: '',
      oil_quota_icon: '',
      coupon_icon: '',
      integral_icon: '',
      // 邀请相关参数
      level_id: '',
      mer_id: '',
      mer_info: {},
      level_info:{},
      coupon_list: {},
      join_info: {},
      //支付方式
      pay_info: {
        pay_type: 'weixin',
        // #ifdef H5
        return_url: 'http://' + window.location.host + '/pages/users/order_list/index',
        // #endif
      },
    }
  },
  onReady() {
    this.top_icon = `${HTTP_REQUEST_URL}/static/images/mer/shareholder/bg002.png`;
    this.quota_icon = `${HTTP_REQUEST_URL}/static/images/mer/shareholder/2.png`;
    this.wine_quota_icon = `${HTTP_REQUEST_URL}/static/images/mer/shareholder/3.png`;
    this.vegetable_quota_icon = `${HTTP_REQUEST_URL}/static/images/mer/shareholder/4.png`;
    this.oil_quota_icon = `${HTTP_REQUEST_URL}/static/images/mer/shareholder/5.png`;
    this.coupon_icon = `${HTTP_REQUEST_URL}/static/images/mer/shareholder/6.png`;
    this.integral_icon = `${HTTP_REQUEST_URL}/static/images/mer/shareholder/7.png`;
  },
  onLoad(options) {
    let _this = this;
    if(options.scene){
      console.log('转换前参数：',options.scene)
      let scene = _this.$util.getUrlParams(decodeURIComponent(options.scene));
      // console.log("接收参数",scene)
      _this.mer_id = scene.mid || 0;
      _this.level_id = scene.lv || 0;
    }
    // 判断：不存在商户或者等级信息  抛出错误，返回个人中心
    if(Number(_this.mer_id) <= 0 && Number(this.level_id) <= 0){
      _this.$util.Tips({
        title: '非法访问！',
      },{tab:1,url:'/pages/user/index'});
    }
    // 判断：是否登录
    if (!this.isLogin) {
      this.isAuto = true;
      this.isShowAuth = true;// 未登录  授权登录
    }
    else this.init();// 已登录  获取信息
  },
  watch: {},
  methods: {
    // 授权回调
    onLoadFun() {
      if(this.isLogin){
        this.isShowAuth = false;
        this.init();
      }
    },
    // 授权关闭
    authClose(e) {
      this.isShowAuth = e
    },
    // 授权成功 初始化
    init () {
      this.getJoinInfo();
      this.getMerInfo();
      this.getLevelInfo();
    },
    // 获取申请信息
    getJoinInfo(){
      let _this = this;
      let params = {
        mer_id: _this.mer_id,
        level_id: _this.level_id
      };
      merShareholderGetJoinInfo(params).then(res => {
        let data = res.data || {};
        _this.join_info = data || {};
        // 如果存在申请信息  进行对应的判断及操作
        let joinId = data.id || 0;
        if(joinId > 0){
          // 存在申请信息  判断等级id是否一致，不一致报错并且返回用户中心
          if(Number(_this.level_id) !== Number(_this.join_info.level_id)){
            _this.$util.tips({ content: '已存在本商户股东信息，请勿重复申请！'}, function () {
              uni.switchTab({
                url: '/pages/user/index',
              });
            });
            return false;
          }
          // 存在申请信息  等级一致  状态是否已经支付，已支付则报错并且返回个人中心
          if(Number(_this.join_info.status) === 1){
            _this.$util.tips({ content: '已成为本商户共创股东，请勿重复申请！'}, function () {
              uni.switchTab({
                url: '/pages/user/index',
              });
            });
            return false;
          }
        }
      })
    },
    // 获取商户信息
    getMerInfo(){
      let _this = this;
      merShareholderMerInfo(_this.mer_id).then(res => {
        _this.mer_info = res.data || {};
      })
    },
    // 获取等级信息
    getLevelInfo(){
      let _this = this;
      merShareholderLevelInfo(_this.level_id).then(res => {
        _this.level_info = res.data || {};
        _this.coupon_list = res.data.coupon_list || {};
      })
    },
    // 修改支付方式
    changePayType(value){
      this.pay_info.pay_type = value;
    },
    // 提交加入申请信息
    submitJoinApplyInfo(){
      let _this = this;
      let applyInfo = {
        mer_id: _this.mer_id,
        level_id: _this.level_id
      };
      let payInfo = Object.assign({}, _this.pay_info);
      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
      }
      applyInfo.pay_type = payInfo.pay_type
      applyInfo.return_url = payInfo.return_url
      // 提交申请
      merShareholderSubmitJoinInfo(applyInfo).then(res => {
        if (res.status == 200) {
          let backUrl = '/pages/user/index';
          let backTab = 1;
          if(Number(_this.level_info.price) > 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 = backUrl;
            switch (status) {
              case 'ORDER_EXIST':
              case 'EXTEND_ORDER':
              case 'PAY_ERROR':
              case 'error':
                return _this.$util.Tips({
                  title: res.message
                }, {
                  tab: backTab,
                  url: goPages
                });
                break;
              case 'success':
                return _this.$util.Tips({
                  title: res.message,
                  icon: 'success'
                }, {
                  tab: backTab,
                  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: backTab,
                    url: goPages
                  });
                }).catch(res => {
                  if (res.errMsg == 'chooseWXPay:cancel') return _this.$util.Tips({
                    title: '取消支付'
                  }, {
                    tab: backTab,
                    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=支付成功';
                    return _this.$util.Tips({
                      title: '支付成功',
                      icon: 'success'
                    }, {
                      tab: backTab,
                      url: backUrl
                    });
                  },
                  fail: (e) => {
                    // let url = '/pages/order_pay_status/index?order_id=' + orderId + '&msg=取消支付';
                    return _this.$util.Tips({
                      title: '取消支付',
                    }, {
                      tab: backTab,
                      url: backUrl
                    });
                  },
                  complete: () => {
                    // let url = '/pages/order_pay_status/index?order_id=' + orderId + '&msg=取消支付';
                    return _this.$util.Tips({
                      title: '',
                    }, {
                      tab: backTab,
                      url: backUrl
                    });
                  },
                });
                // #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: backTab,
                      url: goPages
                    });
                  },
                  fail: function(e) {
                    // let pages = '/pages/order_pay_status/index?order_id=' + orderId + '&msg=取消支付'
                    return _this.$util.Tips({
                      title: '取消支付'
                    }, {
                      tab: backTab,
                      // url: pages + '&status=0'
                      url: backUrl
                    });
                  },
                })
                break;
                // #endif
              case "balance":
                //余额
                return _this.$util.Tips({
                  title: res.msg
                }, {
                  tab: backTab,
                  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 eUrl = encodeURIComponent(backUrl)
                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: backTab,
                      url: goPages
                    });
                  },
                  fail: (e) => {
                    // let pages = '/pages/order_pay_status/index?order_id=' + orderId + '&msg=支付失败'
                    return _this.$util.Tips({
                      title: '支付失败'
                    }, {
                      tab: backTab,
                      url: backUrl
                    });
                  },
                  complete: () => {
                    uni.hideLoading();
                    // let pages = '/pages/order_pay_status/index?order_id=' + orderId + '&msg=取消支付'
                    return _this.$util.Tips({
                      title: ''
                    }, {
                      tab: backTab,
                      url: backUrl
                    });
                  },
                });
                break;
                // #endif
              default:
                // let pages = '/pages/order_pay_status/index?order_id=' + orderId + '&msg=取消支付'
                return _this.$util.Tips({
                  title: '取消支付'
                }, {
                  tab: backTab,
                  // url: pages + '&status=0'
                  url: backUrl
                });
            }
          }else{
            _this.$util.Tips({
              title: '操作成功！',
            },{
              tab: backTab,
              url: backUrl
            });
          }
        }
      }).catch(err => {
        this.$util.Tips({title: err});
      });
    },


  },
  // 滚动到底部
  onReachBottom() {},
}
</script>

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

  .main-content{
    width: 100vw;
    background-color: #f6f6f6;
    min-height: 100vh;
    background-size: 100% auto;
    background-repeat: no-repeat;
    padding: 30rpx;

    .block:not(:last-child){
      margin-bottom: 20rpx;
    }
    .block{
      padding: 30rpx;
      border-radius: 15rpx;
      background-color: #ffffff;

      .block-title{
        width: 100%;
        text-align: left;
        font-size: 34rpx;
        font-weight: bold;
      }

      .mer{
        width: 100%;
        background-color: #fef4f3;
        margin-top: 20rpx;
        padding: 20rpx;
        display: inline-flex;
        flex-direction: row;
        flex-wrap: nowrap;
        justify-content: flex-start;
        align-items: center;
        .mer_avatar{
          height: 80rpx !important;
          width: 80rpx !important;
          border-radius: 50%;
        }
        .mer_name{
          font-size: 28rpx;
          font-weight: bold;
          padding-left: 20rpx;
        }
      }

      .give-item{
        width: 100%;
        padding: 20rpx;
        margin-top: 30rpx;
        border-radius: 15rpx;
        border: 2rpx solid #f4f4f4;
        box-shadow: 0 0 10rpx 0 #f5f5f5;
        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;
          .give-icon{
            height: 50rpx !important;
            width: 50rpx !important;
            background: #f1f2f6;
            padding: 15rpx;
            border-radius: 50%;
          }
          .give-title{
            font-size: 30rpx;
            font-weight: bold;
            text-align: left;
            padding-left: 20rpx;
          }
        }
        .give-num{
          color: #ff0400;
          font-size: 30rpx;
          text-align: right;
        }
        .give-coupon-list{
          width: calc(100% - 300rpx);
          display: inline-flex;
          flex-direction: row;
          flex-wrap: wrap;
          justify-content: flex-end;
          align-items: center;
          align-content: flex-start;
          .coupon-item{
            border: 2rpx solid #fa2a2a;
            background-color: #ffeef1;
            color: #fa2a2a;
            font-size: 24rpx;
            height: 40rpx;
            line-height: 38rpx;
            padding: 0 10rpx;
            border-radius: 6rpx;
            margin-right: 8rpx;
            margin-bottom: 8rpx;
          }
        }
      }
    }

    .pay-type{
      .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;
      }
      .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;
          }
        }
      }
    }

    .join-btn{
      padding: 60rpx 0;
      width: 100vw;
      display: inline-flex;
      flex-direction: row;
      flex-wrap: nowrap;
      justify-content: center;
      align-items: center;
      .join-btn-content{
        background-color: #ff3833;
        color: #ffffff;
        width: 80%;
        height: 100rpx;
        border-radius: 200rpx;
        display: inline-flex;
        flex-direction: column;
        flex-wrap: nowrap;
        align-items: center;
        justify-content: center;
        .join-text{
          font-size: 36rpx;
          height: 50rpx;
          line-height: 50rpx;
        }
        .join-price{
          font-size: 26rpx;
        }
      }
    }
  }
}
</style>
