<template>
	<view class="main-content">
    <!--主要图片-->
    <image class="main-image" :src='info.image' mode="widthFix"></image>
    <!--支付按钮-->
    <view class="bottom-btn" @click="joinActivityShow">加入活动</view>
    <!--授权登录-->
    <authorize @onLoadFun="onLoadFun" :isAuto="isAuto" :isShowAuth="isShowAuth" @authColse="authClose"></authorize>
    <!--参加活动弹框-->
    <uni-popup ref="joinActivity" type="center">
      <view class="join-activity-content">
        <view class="top">
          <view class="text">——</view>
          <view class="text">&nbsp;完善信息&nbsp;</view>
          <view class="text">——</view>
        </view>
        <view class="store-info" v-if="Object.values(current_mer).length > 0">
          <image class="main-image" :src='current_mer.mer_avatar'></image>
          <view class="info">
            <view class="title">{{ current_mer.mer_name }}</view>
            <view class="distance" v-if="current_mer.distance > 0">距离:{{ current_mer.distance_text }}</view>
            <view class="address">{{ current_mer.mer_address }}</view>
          </view>
        </view>
        <view class="other-store" @click="changeMerShow">
          {{ Object.values(current_mer).length > 0 ? '选择其他烟酒店' : '请选择烟酒店' }} <text class="iconfont icon-xiangyou"></text>
        </view>
        <!--选择支付方式-->
        <view class="pay-type" v-if="Number(pay_money) > 0">
          <view class="box-title">支付方式</view>
          <view class="box-content">
            <radio-group name="pay_type" @change="changePayType">
              <view class="pay-label" v-for="(item,index) in pay_list" :key="index" v-if="item.payStatus==1">
                <label>
                  <view class="pay-item">
                    <view class="left">
                      <view :class="['iconfont','animated',item.icon]"></view>
                      <view class="pay-item-info">
                        <view class="pay-name">{{ item.name }}</view>
                        <view class='tip'>
                          {{item.title}}
                          <block v-if="item.value == 'balance'">
                            {{now_money}}
                          </block>
                        </view>
                      </view>
                    </view>
                    <view class="right">
                      <radio :value="item.value" :checked="item.value == pay_info.pay_type ? true : false" />
                    </view>
                  </view>
                </label>
              </view>
            </radio-group>
          </view>
        </view>
        <!--提交按钮-->
        <view class="group-btn">
          <view class="add-btn" @click="submitInfo">{{ Number(pay_money) > 0 ? '去支付 ¥' + pay_money : '立即加入' }}</view>
        </view>
      </view>
    </uni-popup>
    <!--切换代理身份-->
    <uni-popup ref="changeMer" type="bottom">
      <view class="change-agent-content">
        <scroll-view scroll-y="true">
          <radio-group name="store_name" @change="changeMer">
            <template v-for="(item,index) in mer_list">
              <div class="store-list">
                <label :key="item.id" class="store-list-item">
                  <view class="text">{{ item.mer_name }}</view>
                  <radio class="radio" :value="index" :checked="current_mer.mer_id == item.mer_id ? true : false" />
                </label>
              </div>
            </template>
          </radio-group>
        </scroll-view>
      </view>
    </uni-popup>
	</view>
</template>

<script>
import {mapGetters} from "vuex";
import authorize from '@/components/Authorize';
import { activityDetail,activityJoin } from "@/api/activity";
import {getUserInfo} from "@/api/user";
import {searchMer} from '@/api/exchange.js';

export default {
  name: 'business',
  components: {
    authorize
  },
  computed: {
    ...mapGetters(['isLogin', 'uid', 'userInfo', 'viewColor'])
  },
  data() {
    return {
      // 登录相关
      isAuto: false, //没有授权的不会自动授权
      isShowAuth: false,//是否隐藏授权
      // 活动信息
      activity_id: '',
      info: {},
      current_mer: {},
      mer_list: {},
      // 定位
      lat: '',
      lng: '',
      //支付方式
      pay_list: [
        {
          "name": "微信支付",
          "icon": "icon-weixin2",
          value: 'weixin',
          title: '微信快捷支付',
          payStatus: 1,
        },
        {
          name: "支付宝支付",
          icon: "icon-icon34",
          // #ifdef H5 || APP-PLUS
          value: 'alipay',
          // #endif
          // #ifdef MP
          value: 'alipayQr',
          // #endif
          title: '支付宝支付',
          payStatus: this.$store.getters.globalData.alipay_open
        },
        {
          "name": "余额支付",
          "icon": "icon-icon-test",
          value: 'balance',
          title: '可用余额:',
          payStatus: this.$store.getters.globalData.yue_pay_status,
        },
        {
          "name": "线下支付",
          "icon": "icon-yinhangqia",
          value: 'offline',
          title: '线下支付',
          payStatus: 2,
        },
      ],
      now_money: 0,
      pay_money: 0,// 支付金额
      pay_info: {
        pay_type: 'weixin',
        // #ifdef H5
        return_url: 'http://' + window.location.host + '/pages/users/order_list/index',
        // #endif
      },
    }
  },
  onLoad(options) {
    this.activity_id = options.activity_id || 0;
    if(this.activity_id <= 0){
      uni.showModal({
        title: '非法访问',
        content: '活动不存在或已结束!',
        confirmText: '返回首页',
        showCancel: false,
        success: (res) => {
          if (res.confirm) {
            uni.switchTab({
              url: '/pages/index/index'
            });
          }
        }
      });
      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 () {
      let _this = this;
      // 获取用户信息
      getUserInfo().then(res => {
        _this.now_money = res.data.now_money
      });
      // 定位
      _this.lat = uni.getStorageSync('user_latitude') || '';
      _this.lng = uni.getStorageSync('user_longitude') || '';
      if(_this.lat && _this.lng){
        this.getDetail();
        this.getMerList();
      }else{
        _this.getLocation();
      }
    },
    // 获取用户定位信息
    getLocation(){
      let _this = this;
      // 获取定位
      uni.getLocation({
        type: 'gcj02',
        success: (res) => {
          uni.setStorageSync('user_latitude', res.latitude);
          uni.setStorageSync('user_longitude', res.longitude);
          _this.lat = res.latitude;
          _this.lng = res.longitude;
        },
        fail: (err) => {},
        complete: (res) => {
          this.getDetail();
          this.getMerList();
        }
      });
    },
    // 获取活动详情
    getDetail(){
      let _this = this;
      activityDetail(_this.activity_id).then(res => {
        _this.info = res.data || {};
        _this.pay_money = res.data.money || 0;
      }).catch(err => {
        this.$util.Tips({title: err});
      });
    },
    // 参加活动弹框
    joinActivityShow(){
      this.$refs.joinActivity.open('center');
    },
    // 门店选择 - 获取门店列表
    getMerList(){
      let _this = this;
      searchMer({ merchant_type: 3, lat: _this.lat, lng: _this.lng }).then(res => {
        _this.mer_list = res.data || {};
        _this.current_mer = res.data[0] || {};
      }).catch(err => {
        this.$util.Tips({
          title: err
        });
      });
    },
    // 商户选择弹框
    changeMerShow(){
      this.$refs.changeMer.open('center');
    },
    // 商户改变
    changeMer(e){
      let index = e.detail.value || e.target.value;
      this.current_mer = this.mer_list[index] || {};
      this.$refs.changeMer.close();
    },
    // 提交申请信息
    submitInfo(){
      let _this = this;
      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
      }
      payInfo.activity_id = _this.activity_id;
      payInfo.mer_id = _this.current_mer.mer_id;
      // 提交申请
      activityJoin(payInfo).then(res => {
        if (res.status == 200) {
          if(Number(_this.pay_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 => {
        this.$util.Tips({title: err});
      });
    },
    // 修改支付方式
    changePayType(e){
      this.pay_info.pay_type = e.detail.value || e.target.value;
    },



  }
}
</script>

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

  .main-image{
    width: 100vw!important;
  }

  .bottom-btn{
    position: fixed;
    bottom: 100rpx;
    left: calc((100vw - 80vw) / 2);
    width: 80vw;
    height: 70rpx;
    line-height: 70rpx;
    background-color: #d60000;
    color: #ffffff;
    text-align: center;
    border-radius: 80rpx;
    font-size: 30rpx;
  }

  .join-activity-content{
    border-radius: 30rpx;
    background: #ffffff;
    width: calc(100vw - (30rpx * 2));
    padding: 20rpx;
    margin: auto;
    .top{
      width: 100%;
      height: 80rpx;
      display: inline-flex;
      flex-direction: row;
      flex-wrap: nowrap;
      align-items: center;
      justify-content: center;
      .text{
        font-size: 30rpx;
        font-weight: bold;
      }
    }
    .store-info{
      width: 100%;
      border-radius: 20rpx;
      border: 2rpx solid #efefef;
      padding: 20rpx;
      display: inline-flex;
      flex-direction: row;
      flex-wrap: nowrap;
      align-items: center;
      justify-content: flex-start;
      .main-image{
        width: 80rpx!important;
        height: 80rpx!important;
        border-radius: 50%;
      }
      .info{
        width: calc(100% - 80rpx) !important;
        padding-left: 20rpx;
        height: 150rpx;
        display: inline-flex;
        flex-direction: column;
        flex-wrap: nowrap;
        align-items: flex-start;
        justify-content: center;
        .title{
          font-size: 30rpx;
          font-weight: bold;
        }
        .distance{
          font-size: 24rpx;
          font-weight: bold;
        }
        .address{
          font-size: 24rpx;
          color: #7f7f7f;
        }
      }
    }
    .other-store{
      height: 60rpx;
      line-height: 50rpx;
      font-size: 26rpx;
      font-weight: bold;
      text-align: center;
      .icon{
        font-size: 26rpx;
      }
    }
    .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;
          }
        }
      }
    }
    .group-btn{
      margin-top: 80rpx!important;
      width: 100%;
      display: inline-flex;
      flex-wrap: nowrap;
      justify-content: center;
      align-items: center;
      flex-direction: row;
      .add-btn{
        height: 80rpx;
        line-height: 80rpx;
        width: 100%;
        text-align: center;
        font-size: 30rpx;
        color: #fff;
        background-color: #409eff;
        border-color: #409eff;
        border-radius: 15rpx;
      }
    }
  }
  // 切换代理
  .change-agent-content{
    width: 100vw !important;
    height: 80vh !important;
    background-color: #fff;
    border-top-left-radius: 30rpx !important;
    border-top-right-radius: 30rpx !important;
    padding: 30rpx !important;
    position: fixed;
    bottom: 0;
    left: 0;
    overflow: auto;
    .store-list{
      width: 100% !important;
      height: 120rpx;
      line-height: 120rpx;
      .store-list-item{
        width: 100%;
        display: inline-flex;
        flex-direction: row;
        flex-wrap: nowrap;
        justify-content: space-between;
        align-items: center;
      }
      .store-list-item:not(:last-child){
        border-bottom: 2rpx solid #f6f6f6;
      }
      .title{
        width: calc(100% - 80rpx) !important;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
      }
    }

    /deep/ radio .wx-radio-input.wx-radio-input-checked, /deep/radio .uni-radio-input.uni-radio-input-checked {
      border: 1px solid #2291F8 !important;
      background-color: #2291F8 !important
    }
  }
}
</style>
