<template>
  <transition name="move">
    <div
      v-show="showFlag"
      ref="food"
      class="food">
      <div class="food-content">
        <div class="image-header">
          <img
            :src="food.product_img_url"
            alt="">
          <div
            class="back"
            @click="hide">
            <van-icon
              color="#fff"
              name="close"
              size="30px"/>
          </div>
        </div>
        <div class="content">
          <div class="title-wrap">
            <h1 class="title">{{ food.product_name }}</h1>
            <p v-if="false">{{ food.product_sale_num }}人推荐</p>
          </div>
          <div class="detail">
            <p class="options">
              <span
                v-for="(item, index) in food.product_skus"
                :key="index"
                :class="{'active': SKUId === item.id}"
                @click="selectSKU(item)">{{ item.product_sku }}</span>
            </p>
          </div>
          <div
            v-for="(item, index) in food.product_attachs"
            :key="index"
            class="detail">
            <div class="subtitle-wrap">
              <h1 class="title">{{ item.attach_name }}</h1>
              <p>（最多可选{{ item.attach_max_num }}个）</p>
            </div>
            <p class="options">
              <span
                :key="idx"
                v-for="(attr, idx) in item.attach_content"
                :class="{'active': Array.isArray(objProductAttachs[SKUId]) && Array.isArray(objProductAttachs[SKUId][index]) && objProductAttachs[SKUId][index].findIndex(attachName => attachName === attr) > -1}"
                @click="selectAttach(SKUId, index, attr, item.attach_max_num)">{{ attr }}</span>
            </p>
          </div>
          <!--商品详情传过来的是富文本，值有可能为空-->
          <div v-if="food.product_desc && food.product_desc.length"
               class="detail">
            <div class="subtitle-wrap">
              <h1 class="title">商品详情</h1>
            </div>
            <div class="des" v-html="food.product_desc"></div>
          </div>
          <div class="detail cartcontrol-wrapper">
            <div class="subtitle-wrap">
              <h1 class="title">购买数量</h1>
            </div>
            <cartcontrol :food="food" @add="addFood"/>
          </div>
        </div>
      </div>
      <div class="footer">
        <div
          :class="{'highlight':price * food.product_num > 0}"
          class="price">
          <span class="now">￥{{ price * food.product_num | fen2Yuan }}</span>
        </div>
        <transition name="fade">
          <div
            class="buy"
            :class="payClass"
            @click.stop.prevent="addFirst">{{ food.is_sell_out === 1 ? '售罄' : '加入购物车'}}
          </div>
        </transition>
      </div>
    </div>
  </transition>
</template>

<script type="text/ecmascript-6">
import BScroll from 'better-scroll'
import Vue from 'vue'
import cartcontrol from '../cartcontrol/cartcontrol'
import { Icon, Toast } from 'vant'
import { mapGetters } from 'vuex'
import { apiCartAdd } from '../goods/api'
import { formatArray } from '../../../utils'

export default {
  props: {
    food: {
      type: Object
    }
  },
  data () {
    return {
      showFlag: false,
      SKUId: '', // 商品skuID
      price: '', // 商品价格
      objProductAttachs: {} // 商品附加
    }
  },
  computed: {
    ...mapGetters({
      objCurrentBarInfo: 'common/objCurrentBarInfo'
    }),
    payClass () {
      if (this.food.product_num < 1 || this.food.is_sell_out === 1) {
        return 'not-enough'
      } else {
        return 'enough'
      }
    }
  },
  methods: {
    show () {
      this.SKUId = ''
      this.price = ''
      this.objProductAttachs = {}
      this.showFlag = true
      this.$nextTick(() => {
        const skus = this.food.product_skus
        const attachs = this.food.product_attachs
        this.SKUId = skus[0].id
        this.price = skus[0].product_price
        skus.forEach(SKU => {
          this.objProductAttachs[SKU.id] = attachs.map(() => [])
        })

        if (!this.scroll) {
          this.scroll = new BScroll(this.$refs.food, {
            click: true
          })
        } else {
          this.scroll.refresh()
        }
      })
    },
    hide () {
      this.showFlag = false
    },
    /**
     * 添加商品到购物车
     */
    async addFirst (event) {
      const { id } = this.objCurrentBarInfo
      const count = this.food.product_num
      const isSellOut = this.food.is_sell_out
      const allAttach = JSON.parse(JSON.stringify(this.objProductAttachs[this.SKUId]))
      const postData = {
        bar_id: id, // 酒吧ID
        product_id: this.food.id, // 商品ID
        product_sku_id: this.SKUId, // 商品skuID
        num: count, // 商品数量
        product_attach: formatArray(allAttach).join(',') // 商品附加
      }
      if (!event._constructed) {
        return
      }
      if (isSellOut === 1 || count < 1) {
        return
      }
      try {
        const { status, msg } = await apiCartAdd(postData)
        if (status) {
          this.hide()
          this.$emit('initCartList')
        } else {
          Toast(msg)
        }
      } catch (err) {}
    },
    addFood () {},
    /**
     * 选择SKU
     * @param item SKU信息
     */
    selectSKU (item) {
      this.SKUId = item.id
      this.price = item.product_price
    },
    /**
     * 选择商品附加
     * @param SKUId SKU ID
     * @param index 附加列表下标
     * @param attachName 附加名
     * @param max 当前附加做多可选值
     */
    selectAttach (SKUId, index, attachName, max) {
      // 刷新SKUId，不然数据更新不生效
      this.SKUId = ''
      this.$nextTick(() => {
        this.SKUId = SKUId
        const allAttach = JSON.parse(JSON.stringify(this.objProductAttachs[SKUId]))
        // 当前选择的附加
        const curAttach = allAttach[index]
        const idx = curAttach.findIndex(item => item === attachName)

        if (idx > -1) {
          curAttach.splice(idx, 1)
        } else if (max > 0) {
          if (curAttach.length >= max) {
            curAttach.pop()
          }
          curAttach.push(attachName)
        }
        allAttach.splice(index, 1, curAttach)
        Vue.set(this.objProductAttachs, SKUId, allAttach)
      })
    }
  },
  components: {
    cartcontrol,
    'van-icon': Icon
  }
}
</script>

<style lang="scss" scoped>
.food {
  position: fixed;
  left: 0;
  top: 20px;
  bottom: 0;
  z-index: 60;
  width: 100%;
  transform: translate3d(0, 0, 0);

  &.move-enter-active, &.move-leave-active {
    transition: all 0.2s linear;
  }

  &.move-enter, &.move-leave-active {
    transform: translate3d(0, 100%, 0);
  }

  .food-content {
    min-height: 90%;
    padding-top: 8px;
    padding-bottom: 100px;
    border-radius: 16px 16px 0 0;
    background: #fff;
  }

  .image-header {
    position: relative;
    width: calc(100% - 16px);
    height: 210px;
    margin: 0 auto;
    overflow: hidden;

    img {
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
    }

    .back {
      position: absolute;
      right: 5px;
      top: 5px;
      display: flex;
      align-items: center;
    }
  }

  .content {
    padding-bottom: 68px;

    .title {
      font-size: 18px;
      font-family: PingFangSC-Semibold, PingFang SC;
      font-weight: 600;
      color: #1F1E1E;
      line-height: 25px;
      letter-spacing: 1px;
    }

    .title-wrap {
      padding: 13px 0 11px 20px;
      border-bottom: 1px solid #F2F2F2;

      p {
        margin-top: 2px;
        font-size: 12px;
        color: #736F6F;
        line-height: 17px;
      }
    }
  }
}

.detail {
  padding-left: 20px;

  .subtitle-wrap {
    display: flex;
    align-items: center;
    margin-top: 20px;

    p {
      margin-left: 4px;
      font-size: 14px;
      color: #D32323;
      line-height: 20px;
    }
  }

  .options {
    display: flex;
    flex-flow: row wrap;

    span {
      width: 98px;
      height: 32px;
      border-radius: 16px;
      border: 1px solid #F2F2F2;
      margin-left: 20px;
      margin-top: 14px;
      font-size: 14px;
      color: #1F1E1E;
      line-height: 32px;
      text-align: center;

      &:nth-of-type(3n+1) {
        margin-left: 0;
      }

      &.active {
        border: none;
        color: #FFFFFF;
        background: #D32323;
        box-shadow: 0 2px 4px 0 rgba(210, 199, 199, 0.31);
      }
    }
  }

  .des {
    margin-top: 16px;

    ::v-deep p {
      font-size: 12px;
      font-family: PingFangSC-Medium, PingFang SC;
      font-weight: 500;
      color: #1F1E1E;
      line-height: 17px;
    }
  }
}

.cartcontrol-wrapper {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-right: 20px;
  margin-top: 20px;

  .subtitle-wrap {
    margin-top: 0;
  }
}

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

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

    &.highlight {
      color: #D32323;
    }
  }

  .buy {
    position: absolute;
    right: 20px;
    top: 18px;
    width: 110px;
    height: 32px;
    border-radius: 20px;
    font-size: 14px;
    font-family: PingFangSC-Medium, PingFang SC;
    font-weight: 500;
    line-height: 32px;
    text-align: center;

    &.not-enough {
      color: #999;
      background: #333;
    }

    &.enough {
      color: #FFF;
      background: #D32323;
    }
  }
}
</style>
