<template>
  <div class="af-place-list-container">
    <!--头部-->
    <div class="header">
      <div class="store-name">
        <p>
          <img src="./image/icon_music@2x.png" alt="">
          <span>{{ objCurrentBarInfo.bar_name }}</span>
        </p>
      </div>
      <div class="open-time">
        <p>
          <img src="./image/icon_time@2x.png" alt="">
          <span>{{ objCurrentBarInfo.bar_place_reserve_start_time }}-{{ objCurrentBarInfo.bar_place_reserve_end_time
            }}开放预订</span>
        </p>
      </div>
    </div>
    <!--预约日期-->
    <van-tabs
      class="af-van-tab"
      :background="'transparent'"
      :ellipsis="false"
      :sticky="true"
      v-model="active"
      @change="handleChange"
      ref="afTabs">
      <van-tab
        v-for="(item, index) in placeList"
        :key="index">
        <template #title>
          <p class="week">{{ item.week }}</p>
          <p class="date">{{ item.time }}</p>
        </template>
        <div class="place-list"
             v-for="(place, idx) in item.list"
             :key="idx"
             @click="handleShowPopup(place, item.week)">
          <div class="left">
            <p class="name">{{ place.place_name }}</p>
            <p class="des">{{ place.place_desc }}</p>
          </div>
          <div class="right"
               v-if="place.place_num - place.place_pre_num > 0">
            <!--place_pre_type：座位预定类型(0整桌预定1座位预定) 整桌预定价格不变，座位预定价格由人数*价格-->
            <p class="price">
              <span>¥ {{ place.place_price | fen2Yuan }}</span>
              <span>{{ place.place_pre_type === 1 ? '起' : ''}}</span>
            </p>
            <p class="btn-wrap">
              <span class="btn">立即预订</span>
              <van-icon name="arrow" size="12px"/>
            </p>
          </div>
          <!--座位被定完-->
          <div class="sell-out" v-else>
            <img src="./image/sell_out@2x.png" alt="">
            <div>
              <p class="price disabled">
                <span>¥ {{ place.place_price | fen2Yuan }}</span>
                <span>{{ place.place_pre_type === 1 ? '起' : ''}}</span>
              </p>
              <p class="sell-des">已订满</p>
            </div>
          </div>
        </div>
        <p class="btimap" v-if="booFetch && !item.list.length">暂无数据</p>
      </van-tab>
    </van-tabs>
    <!--选择-->
    <van-popup
      v-model="showPopup"
      position="bottom"
      style="background: transparent;height: 90%;">
      <div class="af-popup-main">
        <van-icon
          class="af-van-icon"
          name="clear"
          size="28"
          @click="showPopup = false"/>
        <div class="af-popup-header">
          <div class="date-wrap">
            <p class="date">{{ objCurrentPlaceInfo.place_time ? objCurrentPlaceInfo.place_time.replace(/-/g, '/') : ''
              }}({{ objCurrentPlaceInfo.week }})</p>
            <p class="title">AF HOUSE 音乐空间</p>
          </div>
          <p class="outlet-name">{{ objCurrentPlaceInfo.place_name }}</p>
          <p class="place-name">{{ objCurrentPlaceInfo.place_desc }}</p>
        </div>
        <div class="af-popup-body">
          <p class="tip">
            <span>最晚到店时间</span>
            <span>（最晚为您保留{{ objCurrentPlaceInfo.place_max_time }}分钟，可提前入场）</span>
          </p>
          <div class="width-335">
            <p class="time">{{ objCurrentPlaceInfo.place_latest_time }}</p>
            <p class="people-label">到店人数</p>
            <div class="people-options">
          <span
            :class="{'active': order_user_num === i}"
            v-for="i in objCurrentPlaceInfo.place_user_max"
            :key="i"
            @click="order_user_num = i">{{ i }}人</span>
            </div>
            <van-field
              class="af-van-cell"
              v-model="order_user_phone"
              type="order_user_phone"
              readonly
              label="联系方式"/>
            <div class="name-wrap">
              <van-field
                class="af-van-cell"
                v-model.trim="order_user_name"
                placeholder="请预订人名字"
                label="您的称呼"/>
              <p class="gender">
                <span
                  :class="{'active': order_user_sex === item}"
                  v-for="(item, index) in ['先生', '女士']"
                  :key="index"
                  @click="order_user_sex = item">{{ item }}</span>
              </p>
            </div>
            <p class="explain">可抵扣到店消费，支付后需等待商家确认</p>
            <p class="explain">预定不成功自动退款，</p>
            <p class="explain">
              <span
                style="color: #D32323;"
                v-for="(str, index) in '预定到店时间已不足8小时'"
                :key="'a' + index">{{ str }}</span>
              <span
                v-for="(str, index) in '，下单后不可退订，不可转让'"
                :key="'b' + index">{{ str }}</span>
            </p>
            <!--支付宝、微信环境不显示-->
            <div class="payment-type">
              <p :class="{'active': order_pay_type === 2}"
                 @click="order_pay_type = 2">
                <img
                  class="icon"
                  src="./image/ic_select@2x.png"
                  alt=""
                  v-show="order_pay_type === 2">
                <img
                  class="alipay"
                  src="./image/ic_Alipay_sel@2x.png"
                  alt="" v-show="order_pay_type === 2">
                <img
                  class="alipay"
                  src="./image/ic_Alipay_nor@2x.png"
                  alt="" v-show="order_pay_type !== 2">
                <span>支付宝支付</span>
              </p>
              <p :class="{'active': order_pay_type === 1}"
                 @click="order_pay_type = 1">
                <img
                  class="icon"
                  src="./image/ic_select@2x.png"
                  alt=""
                  v-show="order_pay_type === 1">
                <img
                  class="wechat"
                  src="./image/ic_WeChat_sel@2x.png"
                  alt=""
                  v-show="order_pay_type === 1">
                <img
                  class="wechat"
                  src="./image/ic_WeChat_nor@2x.png"
                  alt=""
                  v-show="order_pay_type !== 1">
                <span>微信支付</span>
              </p>
            </div>
          </div>
        </div>
        <div class="af-popup-footer">
          <p class="count">
            <span>预付：</span>
            <span
              v-if="objCurrentPlaceInfo.place_pre_type === 1">￥{{
                objCurrentPlaceInfo.place_price * order_user_num | fen2Yuan
              }}</span>
            <span v-else>￥{{ objCurrentPlaceInfo.place_price | fen2Yuan }}</span>
          </p>
          <van-button
            class="btn"
            type="danger"
            :disabled="booLock"
            @click="onSubmit">确认支付
          </van-button>
        </div>
      </div>
    </van-popup>
  </div>
</template>

<script>
import { Tabs, Tab, Icon, Popup, Field, Toast, Button } from 'vant'
import { apiPlaceList, apiPlacePreOrder } from './api'
import { getCookieValue } from '../../../utils'
import { platform } from '../../../utils/platform'
import { mapGetters } from 'vuex'

export default {
  name: 'index',
  components: {
    'van-tabs': Tabs,
    'van-tab': Tab,
    'van-icon': Icon,
    'van-popup': Popup,
    'van-field': Field,
    'van-button': Button
  },
  data () {
    return {
      platform: platform,
      placeList: [],
      objCurrentPlaceInfo: {}, // 当前座位信息
      active: 0,
      listData: [],
      showPopup: false,
      bar_id: '',
      order_user_num: 1, // 用户数量
      order_user_phone: '', // 订单联系号码
      order_user_name: '', // 订单联系人姓名
      order_user_sex: '先生', // 订单联系人性别
      order_pay_type: 2, // 支付方式(1微信2支付宝)
      booLock: false,
      booFetch: false
    }
  },
  computed: {
    ...mapGetters({
      objCurrentBarInfo: 'common/objCurrentBarInfo'
    }),
    phone () {
      return this.$store.getters['common/phone'] || getCookieValue('afhousephone')
    },
    token () {
      return this.$store.getters['common/token'] || getCookieValue('afhousetoken')
    }
  },
  watch: {
    'objCurrentBarInfo.id': {
      immediate: true,
      handler: function () {
        console.log(111)
        this.fetchPlaceList()
      }
    }
  },
  async created () {
    if (platform.isWeixin) {
      this.order_pay_type = 1
    } else if (platform.isAlipay) {
      this.order_pay_type = 2
    }
  },
  async mounted () {
    await this.$nextTick()
    this.order_user_phone = this.phone
  },
  methods: {
    handleChange () {},
    // 获取订座列表
    async fetchPlaceList () {
      const { id } = this.objCurrentBarInfo
      if (!id) {
        return
      }
      try {
        const { data, status, msg } = await apiPlaceList(id)
        if (status) {
          const { place } = data
          this.placeList = place
        } else {
          Toast(msg)
        }
        this.booFetch = true
      } catch (err) {
        this.booFetch = true
      }
    },
    handleShowPopup (place, week) {
      if (!(this.phone && this.token)) {
        this.$router.push({ name: 'Login' })
        return
      }
      this.objCurrentPlaceInfo = {
        ...place,
        week
      }
      // 座位被定完了
      if (this.objCurrentPlaceInfo.place_num - this.objCurrentPlaceInfo.place_pre_num <= 0) {
        return
      }
      this.showPopup = true
    },
    async onSubmit () {
      const { id } = this.objCurrentPlaceInfo
      const postData = {
        bar_id: this.bar_id, // 酒吧ID
        place_id: id, // 座位ID
        order_user_phone: this.order_user_phone,
        order_user_name: this.order_user_name,
        order_user_sex: this.order_user_sex === '先生' ? '男' : '女',
        order_user_num: this.order_user_num,
        order_pay_type: this.order_pay_type
      }
      if (!this.order_user_name) {
        Toast('请预订人名字')
        return
      }
      const myToast = Toast.loading({
        message: '加载中...',
        duration: 1000 * 100,
        forbidClick: true
      })
      this.booLock = true
      try {
        const { status, data, msg } = await apiPlacePreOrder(postData)
        this.booLock = false
        myToast.clear()
        if (status) {
          const officialOrderNumber = data.official_order_number
          // 支付宝支付
          if (this.order_pay_type === 2) {
            if (platform.isWeixin) {
              this.$router.push({ name: 'PayBridge', query: { alipayForm: decodeURIComponent(officialOrderNumber) } })
            } else {
              const div = document.createElement('div')
              div.innerHTML = officialOrderNumber
              document.body.appendChild(div)
              document.forms[0].submit()
            }
          } else {
            // 微信支付
            if (platform.isWeixin) { // 微信内
              this.weixinPay(officialOrderNumber)
            } else if (platform.isAlipay) { // 支付宝内
              // this.$router.push({ name: 'PayBridge', query: { wxpayHref: '' } })
              Toast('请使用微信打开')
            } else {
              // window.location.replace()
              Toast('请使用微信打开')
            }
          }
        } else {
          Toast(msg)
        }
      } catch (err) {
        this.booLock = false
      }
    },
    async weixinPay (data) {
      if (typeof WeixinJSBridge === 'undefined') {
        if (document.addEventListener) {
          document.addEventListener('WeixinJSBridgeReady', this.onBridgeReady(data), false)
        } else if (document.attachEvent) {
          document.attachEvent('WeixinJSBridgeReady', this.onBridgeReady(data))
          document.attachEvent('onWeixinJSBridgeReady', this.onBridgeReady(data))
        }
      } else {
        this.onBridgeReady(data)
      }
    },
    onBridgeReady (data) {
      const vm = this
      /* eslint-disable-next-line */
      WeixinJSBridge.invoke(
        'getBrandWCPayRequest',
        {
          appId: data.app_id,
          timeStamp: data.time_stamp,
          nonceStr: data.nonce_str,
          package: data.package,
          signType: data.sign_type,
          paySign: data.pay_sign
        },
        function (res) {
          /* eslint-disable-next-line */
          if (res.err_msg == 'get_brand_wcpay_request:ok') {
            // 使用以上方式判断前端返回,微信团队郑重提示：
            // res.err_msg将在用户支付成功后返回ok，但并不保证它绝对可靠。
            vm.showPopup = false
            vm.$router.push({ name: 'PlaceReserve' })
          } else {
            Toast.fail('支付失败！')
          }
        }
      )
    }
  }
}
</script>

<style lang="scss" scoped>
@import "./style/index";
</style>
