<template>
  <div class="pay-detail">
    <div class="order-status">
      <p>待支付</p>
      <router-link
        :to="{name: 'SellGoods'}"
        replace
        tag="p">取消订单
      </router-link>
    </div>
    <ul class="goods-list">
      <li
        v-for="food in _selectFoods"
        :key="food.id">
        <div class="goods-cover">
          <img
            :src="food.product_img_url"
            alt=""
            height="60"
            width="60">
        </div>
        <div class="info">
          <p class="top">
            <span>{{ food.product_name }}</span>
            <span>￥{{ food.product_price | fen2Yuan }}</span>
          </p>
          <p class="bottom">
            <span>{{ food.product_attach }}</span>
            <span>*{{ food.product_num }}</span>
          </p>
        </div>
      </li>
      <li
        v-show="selectFoods.length > 2"
        @click="isHideGoods = !isHideGoods">
        <p class="more">{{ isHideGoods ? '展开' : '收起'}}（共{{ totaoNum }}件）</p>
      </li>
    </ul>
    <ul class="amount-detail">
      <li @click="showAdvancePopup">
        <p class="label">订座预约款</p>
        <!--1、接口未获取成功，2、获取成功：有、没有-->
        <template v-if="fetchAdvanceListStatus">
          <p v-if="advanceList.length" class="value">
            {{ curAdvance.order_price >= 0 ? '-¥' : '' }}{{ curAdvance.order_price | fen2Yuan }}</p>
          <p v-else class="value">暂无可用预约款</p>
        </template>
      </li>
      <li @click="showCouponPopup">
        <p class="label">优惠券</p>
        <template v-if="fetchCouponListStatus">
          <p v-if="couponList.length" class="value">
            {{ curCoupon.coupon_price >= 0 ? '-¥' : ''}}{{ curCoupon.coupon_price | fen2Yuan }}</p>
          <p v-else class="value">暂无可用优惠券</p>
        </template>
      </li>
      <li>
        <p class="label">小计</p>
        <p class="label">¥{{ totalPrice | fen2Yuan }}</p>
      </li>
    </ul>
    <payment class="margin-top-20"
             @onChange="handlePayment"/>
    <div class="footer">
      <p class="price">￥{{ totalPrice | fen2Yuan }}</p>
      <van-button
        class="btn"
        type="warning"
        @click="addOrder">去结算
      </van-button>
    </div>
    <!--选择优惠券-->
    <van-popup
      v-model="couponPopup"
      class="af-van-popup"
      position="bottom"
      style="border-radius: 16px 16px 0 0;">
      <h1 class="title">选择优惠券</h1>
      <div class="af-popup-main">
        <div
          v-for="(item, index) in couponList"
          :key="index"
          class="coupon"
          @click="selectCoupon(item)">
          <div class="money">
            <p>{{ item.coupon_price | fen2Yuan }}</p>
            <p>元</p>
          </div>
          <div class="des">
            <p class="name">{{ item.coupon_name }}</p>
            <p class="expire">有效期：{{ item.coupon_start_time }}至{{ item.coupon_end_time }}</p>
          </div>
          <!--选中图标-->
          <img
            v-show="curCoupon.id === item.id"
            alt=""
            class="icon icon-coupon"
            src="./image/ic_select@2x.png">
        </div>
      </div>
    </van-popup>
    <!--选择预约款-->
    <van-popup
      v-model="advancePopup"
      class="af-van-popup"
      position="bottom"
      style="border-radius: 16px 16px 0 0;">
      <h1 class="title">选择预约款</h1>
      <div class="af-popup-main">
        <div
          v-for="(item, index) in advanceList"
          :key="index"
          class="down-payment"
          @click="selectAdvance(item)">
          <div class="money">
            <p>预约款</p>
            <p>￥{{ item.order_price | fen2Yuan }}</p>
            <p>订单满{{ item.place_min_price | fen2Yuan }}可使用</p>
          </div>
          <div class="des">
            <p>{{ item.bar_name }}</p>
            <p>{{ item.place_name }}</p>
            <p>{{ item.order_pre_time }}</p>
          </div>
          <!--选中图标-->
          <img
            v-show="curAdvance.id === item.id"
            alt=""
            class="icon icon-advance"
            src="./image/ic_select@2x.png">
        </div>
      </div>
    </van-popup>
  </div>
</template>

<script>
import payment from '../../common/payment'
import { Button, Popup, Toast, Dialog } from 'vant'
import orderPay from '../../../mixin/orderPay'
import { mapGetters } from 'vuex'
import { apiAdvanceList, apiCouponList, apiAddOrder } from './api'

export default {
  name: 'index',
  mixins: [orderPay],
  components: {
    payment,
    'van-button': Button,
    'van-popup': Popup
  },
  data () {
    return {
      isHideGoods: true,
      advancePopup: false, // 选择预约款弹窗
      advanceList: [], // 预付款列表
      curAdvance: {}, // 当前选择的预付款
      fetchAdvanceListStatus: false, // 获取预付款列表状态
      couponPopup: false, // 优惠券选择弹窗
      couponList: [], // 优惠券列表
      curCoupon: {},
      fetchCouponListStatus: false // 获取优惠券列表状态
    }
  },
  computed: {
    ...mapGetters({
      objCurrentBarInfo: 'common/objCurrentBarInfo'
    }),
    _selectFoods () {
      let result = []
      if (!this.isHideGoods || this.selectFoods.length <= 2) {
        result = this.selectFoods
      } else if (this.selectFoods.length > 2) {
        result = this.selectFoods.slice(0, 2)
      }
      return result
    },
    selectFoods: {
      get () {
        return this.$store.getters['shopcart/selectFoods']
      },
      set (val) {
        this.$store.commit('shopcart/UPDATE_SELECTFOODS', val)
      }
    },
    placeNum: {
      get () {
        return this.$store.getters['shopcart/placeNum']
      },
      set (val) {
        this.$store.commit('shopcart/UPDATE_PLACENUM', val)
      }
    },
    totalPrice () {
      const couponPrice = this.curCoupon.coupon_price
      const orderPrice = this.curAdvance.order_price
      let total = 0
      if (Object.prototype.toString.call(couponPrice) === '[object Number]') {
        total -= couponPrice
      }
      if (Object.prototype.toString.call(orderPrice) === '[object Number]') {
        total -= orderPrice
      }
      this.selectFoods.forEach((food) => {
        total += food.product_price * food.product_num
      })
      return total > 0 ? total : 0
    },
    totaoNum () {
      let total = 0
      this.selectFoods.forEach((food) => {
        total += food.product_num
      })
      return total
    }
  },
  watch: {
    'objCurrentBarInfo.id': {
      immediate: true,
      handler: function (newVal) {
        if (newVal) {
          this.fetchAdvanceList()
          this.fetchCouponList()
        }
      }
    }
  },
  methods: {
    handlePayment (val) {
      this.order_pay_type = val
    },
    showAdvancePopup () {
      if (!this.advanceList.length) {
        return
      }
      this.advancePopup = true
    },
    showCouponPopup () {
      if (!this.couponList.length) {
        return
      }
      this.couponPopup = true
    },
    selectCoupon (item) {
      this.curCoupon = item.id === this.curCoupon.id ? {} : { ...item }
      this.couponPopup = false
    },
    selectAdvance (item) {
      this.curAdvance = item.id === this.curAdvance.id ? {} : { ...item }
      this.advancePopup = false
    },
    // 获取预付款
    async fetchAdvanceList () {
      const { id } = this.objCurrentBarInfo
      if (!id) {
        return
      }
      try {
        const { data, status, msg } = await apiAdvanceList(id)
        if (status) {
          this.advanceList = data
        } else {
          Toast(msg)
        }
        this.fetchAdvanceListStatus = true
      } catch (err) {}
    },
    // 获取优惠券
    async fetchCouponList () {
      const { id } = this.objCurrentBarInfo
      if (!id) {
        return
      }
      try {
        const { data, status, msg } = await apiCouponList(id)
        if (status) {
          this.couponList = data
        } else {
          Toast(msg)
        }
        this.fetchCouponListStatus = true
      } catch (err) {}
    },
    async addOrder () {
      const vm = this
      const { id } = this.objCurrentBarInfo
      const cartIds = this.selectFoods.map(item => item.id)
      if (!(cartIds && this.placeNum)) {
        Dialog.alert({
          message: '返回上一页选择商品(当前未选择商品或未输入正确的桌号)'
        }).then(() => {
          vm.$router.go(-1)
        })
        return
      }

      const postData = {
        bar_id: id, // 酒吧ID
        cart_ids: cartIds, // 购物车ID(以数组方式传递)
        place_number: this.placeNum, // 桌号
        order_prepare_id: this.curAdvance.id || 0, // 预约订单款ID(0代表无预约款)
        coupon_id: this.curCoupon.id || 0, // 优惠券ID(0代表无优惠券)
        order_pay_type: this.order_pay_type // 支付方式(1微信2支付宝3现场支付)
      }
      try {
        const { status, msg, data } = await apiAddOrder(postData)
        if (status) {
          this.selectFoods = []
          this.placeNum = ''
          this.AFPayBridge({
            ...data,
            callback: () => {
              this.$router.replace({ name: 'OrderList' })
            }
          })
        } else {
          Toast(msg)
        }
      } catch (err) {}
    }
  }
}
</script>

<style lang="scss" scoped>
.pay-detail {
  padding-bottom: 68px;
}

.margin-top-20 {
  margin-top: 20px;
}

.order-status {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;

  p:nth-of-type(1) {
    font-size: 21px;
    font-family: PingFangSC-Medium, PingFang SC;
    font-weight: 500;
    color: #D32323;
    line-height: 29px;
  }

  p:nth-of-type(2) {
    font-size: 14px;
    color: #736F6F;
    line-height: 20px;
  }
}

.goods-list {
  padding: 0 20px;

  li {
    display: flex;
    margin-top: 12px;

    &:nth-of-type(1) {
      margin-top: 0;
    }
  }

  .info {
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    width: calc(100% - 60px);
  }

  .top,
  .bottom {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding-left: 10px;
  }

  .top {

    span {
      font-size: 16px;
      font-family: PingFangSC-Medium, PingFang SC;
      font-weight: 500;
      color: #1F1E1E;
      line-height: 22px;
      letter-spacing: 1px;
    }
  }

  .bottom {
    span {
      font-size: 14px;
      color: #736F6F;
      line-height: 20px;
    }
  }

  .more {
    width: 100%;
    font-size: 14px;
    color: #CCC6C6;
    line-height: 20px;
    text-align: center;
  }
}

.goods-cover {
  width: 60px;
  height: 60px;
  border-radius: 8px;
  overflow: hidden;
}

.amount-detail {
  margin-top: 14px;
  background: #fff;

  li {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 12px 20px;
    border-bottom: 1px solid #F2F2F2;

    &:nth-last-child(1) {
      border-bottom: none;
    }
  }

  p {
    font-size: 18px;
    font-family: PingFangSC-Medium, PingFang SC;
    font-weight: 500;
    line-height: 25px;
  }

  .label {
    color: #1F1E1E;
  }

  .value {
    color: #D32323;
  }
}

.footer {
  position: fixed;
  left: 0;
  bottom: 0;
  right: 0;
  z-index: 50;
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
  height: 68px;
  padding: 0 20px;
  background: #FFFFFF;
  box-shadow: 0 -2px 4px 0 rgba(13, 13, 13, 0.03);

  .price {
    font-size: 21px;
    font-family: PingFangSC-Medium, PingFang SC;
    font-weight: 500;
    color: #D32323;
    line-height: 29px;
  }
}

.btn {
  width: 124px;
  height: 40px;
  background: #D32323;
  border-radius: 25px;
  border: none;

  ::v-deep .van-button__text {
    font-size: 16px;
    font-family: PingFangSC-Semibold, PingFang SC;
    font-weight: 600;
    color: #FFFFFF;
    line-height: 40px;
  }
}

.af-van-popup {
  .title {
    padding: 20px 0 12px 20px;
    font-size: 18px;
    font-family: PingFangSC-Medium, PingFang SC;
    font-weight: 500;
    color: #1F1E1E;
    line-height: 25px;
  }
}

.af-popup-main {
  position: relative;
  left: 0;
  top: 0;
  height: 335px;
  overflow-y: scroll;
  -webkit-overflow-scrolling: touch;
  padding-bottom: 20px;

  .icon {
    position: absolute;
    z-index: 1;
    width: 32px;
    height: 30px;

    &.icon-coupon {
      right: 10px;
      top: 2px;
    }

    &.icon-advance {
      right: 20px;
      top: 0;
    }
  }
}

.coupon {
  display: flex;
  align-items: center;
  width: 365px;
  height: 90px;
  margin: 0 auto;
  background: url("./image/bg_coupon@2x.png") center center/100% 100% no-repeat;

  .money {
    display: flex;
    justify-content: flex-end;
    align-items: flex-end;
    width: 32%;
    padding-right: 10px;

    p {
      &:nth-of-type(1) {
        font-size: 36px;
        font-family: PingFangSC-Medium, PingFang SC;
        font-weight: 500;
        color: #1F1E1E;
        line-height: 50px;
      }

      &:nth-of-type(2) {
        padding-bottom: 10px;
        margin-left: 6px;
        font-size: 10px;
        color: #736F6F;
        line-height: 14px;
      }
    }
  }

  .des {
    padding-left: 20px;

    .name {
      font-size: 16px;
      font-family: PingFangSC-Medium, PingFang SC;
      font-weight: 500;
      color: #1F1E1E;
      line-height: 22px;
      letter-spacing: 1px;
    }

    .expire {
      margin-top: 8px;
      font-size: 10px;
      color: #736F6F;
      line-height: 14px;
    }
  }
}

.down-payment {
  display: flex;
  align-items: center;
  width: 335px;
  height: 110px;
  margin: 10px auto 0;
  background: url("./image/bg_money@2x.png") center center/100% 100% no-repeat;

  &:nth-of-type(1) {
    margin: 0 auto;
  }

  .money {
    width: 40%;

    p {
      padding-left: 16px;

      &:nth-of-type(1) {
        font-size: 12px;
        color: #1F1E1E;
        line-height: 17px;
      }

      &:nth-of-type(2) {
        font-size: 24px;
        font-family: PingFangSC-Medium, PingFang SC;
        font-weight: 500;
        color: #D32323;
        line-height: 33px;
      }

      &:nth-of-type(3) {
        font-size: 12px;
        color: #CCC6C6;
        line-height: 17px;
      }
    }
  }

  .des {
    display: flex;
    flex-direction: column;
    align-items: flex-end;
    padding-right: 16px;
    width: 60%;

    p {
      &:nth-of-type(1) {
        font-size: 16px;
        font-family: PingFangSC-Medium, PingFang SC;
        font-weight: 500;
        color: #1F1E1E;
        line-height: 22px;
      }

      &:nth-of-type(2) {
        margin: 10px 0 4px;
        font-size: 12px;
        color: #736F6F;
        line-height: 17px;
      }

      &:nth-of-type(3) {
        font-size: 12px;
        color: #D32323;
        line-height: 17px;
      }
    }
  }
}
</style>
