<template>
  <div>
    <div class="shopcart">
      <!--底部栏：去购买-->
      <div
        class="content"
        @click="toggleList">
        <div class="content-left">
          <div class="logo-wrapper">
            <div class="logo">
              <img src="./image/shop_car@2x.png" alt="">
            </div>
            <div
              v-show="totalCount>0"
              class="num">{{totalCount}}
            </div>
          </div>
          <div
            :class="{'highlight': totalPrice > 0}"
            class="price">￥{{ totalPrice | fen2Yuan }}
          </div>
        </div>
        <div
          class="content-right"
          @click.stop.prevent="pay">
          <div
            :class="payClass"
            class="pay">去结算
          </div>
        </div>
      </div>
      <!--小球飞入动画-->
      <div class="ball-container">
        <div
          v-for="(ball, index) in balls"
          :key="index">
          <transition
            name="drop"
            @enter="dropping"
            @before-enter="beforeDrop"
            @after-enter="afterDrop">
            <div
              v-show="ball.show"
              class="ball">
              <div class="inner inner-hook"></div>
            </div>
          </transition>
        </div>
      </div>
      <!--购物车列表-->
      <transition name="fold">
        <div
          v-show="listShow"
          class="shopcart-list">
          <div class="list-header">
            <h1 class="title">购物车</h1>
            <p class="empty" @click="empty">
              <img src="./image/delete@2x.png" alt="">
              <span>清空购物车</span>
            </p>
          </div>
          <div class="list-content" ref="listContent">
            <ul>
              <li
                v-for="(food, idx) in selectFoods"
                :key="idx"
                class="food">
                <div class="icon">
                  <img
                    :src="food.product_img_url"
                    alt=""
                    height="60"
                    width="60">
                </div>
                <div class="name-wrap">
                  <div class="name">
                    <p>{{ food.product_name }}</p>
                    <p>{{ food.product_attach ? '(' + food.product_attach + ')' : '' }}</p>
                  </div>
                  <div class="price">
                    <span class="now">￥{{ food.product_price * food.product_num | fen2Yuan }}</span>
                  </div>
                  <div class="cartcontrol-wrapper">
                    <cartcontrol
                      :food="food"
                      @add="addFood"
                      @decrease="decreaseFood"></cartcontrol>
                  </div>
                </div>
                <div class="cartcontrol-wrapper">
                  <cartcontrol
                    :food="food"
                    @add="addFood"
                    @decrease="decreaseFood"></cartcontrol>
                </div>
              </li>
            </ul>
          </div>
        </div>
      </transition>
    </div>
    <transition name="fade">
      <div
        v-show="listShow"
        class="list-mask"
        @click="hideList"></div>
    </transition>
  </div>
</template>

<script type="text/ecmascript-6">
import BScroll from 'better-scroll'
import cartcontrol from '../cartcontrol/cartcontrol'
import { Toast, Dialog } from 'vant'
import { mapGetters } from 'vuex'
import { apiCartList, apiCartClear, apiCartUpdate } from '../goods/api'

export default {
  data () {
    return {
      balls: [
        {
          show: false
        },
        {
          show: false
        },
        {
          show: false
        },
        {
          show: false
        },
        {
          show: false
        }
      ],
      dropBalls: [],
      fold: true,
      scroll: null,
      pagenum: 1,
      pagesize: 100,
      numFetchStatus: 0, // 购物车列表加载状态
      arrFetchStatus: ['正在努力加载～', '到底了'],
      booFetchData: false, // 页面第一次获取数据是否成功
      isFetchLock: false // 接口调用加锁
    }
  },
  computed: {
    ...mapGetters({
      objCurrentBarInfo: 'common/objCurrentBarInfo'
    }),
    totalPrice () {
      let total = 0
      this.selectFoods.forEach((food) => {
        total += food.product_price * food.product_num
      })
      return total
    },
    totalCount () {
      let count = 0
      this.selectFoods.forEach((food) => {
        count += food.product_num
      })
      return count
    },
    payClass () {
      if (this.totalPrice < 1) {
        return 'not-enough'
      } else {
        return 'enough'
      }
    },
    listShow () {
      if (!this.totalCount) {
        this.fold = true
        return false
      }
      return !this.fold
    },
    selectFoods: {
      get () {
        return this.$store.getters['shopcart/selectFoods']
      },
      set (val) {
        this.$store.commit('shopcart/UPDATE_SELECTFOODS', val)
      }
    }
  },
  watch: {
    'objCurrentBarInfo.id': {
      immediate: true,
      handler: function (newVal) {
        newVal && this.init()
      }
    }
  },
  methods: {
    init () {
      this.selectFoods = []
      this.pagenum = 1
      this.pagesize = 100
      this.numFetchStatus = 0
      this.booFetchData = false
      this.isFetchLock = false

      this.$nextTick(() => {
        this.fetchCartList()
      })
    },
    async fetchCartList () {
      const { id } = this.objCurrentBarInfo
      if (this.numFetchStatus === 1) {
        return
      }
      if (this.isFetchLock) {
        return
      }
      this.isFetchLock = true
      try {
        const { status, msg, data } = await apiCartList(id, this.pagenum, this.pagesize)
        if (status) {
          const { list } = data
          this.pagenum++
          this.booFetchData = true
          if (Array.isArray(list)) {
            this.selectFoods = this.selectFoods.concat(list)
            if (list.length < this.pagesize) {
              this.numFetchStatus = 1
            }
            this.$nextTick(() => {
              if (!this.scroll) {
                this.scroll = new BScroll(this.$refs.listContent, {
                  click: true,
                  pullUpLoad: {
                    threshold: -20
                  },
                  scrollbar: true
                })

                this.scroll.on('pullingUp', () => {
                  this.fetchCartList()
                })
              } else {
                this.scroll.refresh()
                this.scroll.finishPullUp()
              }
            })
          }
        } else {
          Toast(msg)
        }
        this.isFetchLock = false
      } catch (err) {
        this.isFetchLock = false
      }
    },
    drop (el) {
      for (let i = 0; i < this.balls.length; i++) {
        const ball = this.balls[i]
        if (!ball.show) {
          ball.show = true
          ball.el = el
          this.dropBalls.push(ball)
          return
        }
      }
    },
    toggleList () {
      if (!this.totalCount) {
        return
      }
      this.fold = !this.fold
    },
    hideList () {
      this.fold = true
    },
    /*
    * 清空购物车
    * */
    empty () {
      const vm = this
      const { id } = this.objCurrentBarInfo
      Dialog.confirm({
        message: '清空购物车？'
      }).then(async () => {
        vm.selectFoods.forEach((food) => {
          food.product_num = 0
        })
        try {
          const { status, msg } = await apiCartClear(id)
          if (status) {
            vm.init()
          } else {
            Toast(msg)
          }
        } catch (err) {}
      }).catch(() => {
        // on cancel
      })
    },
    pay () {
      if (this.totalPrice < 1) {
        return
      }
      this.$emit('handleJumpPay')
    },
    // 单个商品增加
    addFood (target, food) {
      this.cartUpdate(food.id, 1)
      this.drop(target)
    },
    // 单个商品减少
    decreaseFood (target, food) {
      const index = this.selectFoods.findIndex(item => item.id === food.id)
      if (food.product_num <= 0 && index > -1) {
        this.selectFoods.splice(index, 1)
        if (this.scroll) {
          this.scroll.refresh()
        }
      }
      this.cartUpdate(food.id, 0)
    },
    /**
     * 更新购物车数量
     * @param id 购物车数据ID
     * @param type 类型(0减少1增加)
     * @returns {Promise<void>}
     */
    async cartUpdate (id, type) {
      try {
        const { status, msg } = await apiCartUpdate(id, type)
        if (status) {} else {
          Toast(msg)
        }
      } catch (err) {}
    },
    beforeDrop (el) {
      let count = this.balls.length
      while (count--) {
        const ball = this.balls[count]
        if (ball.show) {
          const rect = ball.el.getBoundingClientRect()
          const x = rect.left - 32
          const y = -(window.innerHeight - rect.top - 22)
          el.style.display = ''
          el.style.webkitTransform = `translate3d(0,${y}px,0)`
          el.style.transform = `translate3d(0,${y}px,0)`
          const inner = el.getElementsByClassName('inner-hook')[0]
          inner.style.webkitTransform = `translate3d(${x}px,0,0)`
          inner.style.transform = `translate3d(${x}px,0,0)`
        }
      }
    },
    dropping (el, done) {
      /* eslint-disable no-unused-vars */
      const rf = el.offsetHeight
      this.$nextTick(() => {
        el.style.webkitTransform = 'translate3d(0,0,0)'
        el.style.transform = 'translate3d(0,0,0)'
        const inner = el.getElementsByClassName('inner-hook')[0]
        inner.style.webkitTransform = 'translate3d(0,0,0)'
        inner.style.transform = 'translate3d(0,0,0)'
        el.addEventListener('transitionend', done)
      })
    },
    afterDrop (el) {
      const ball = this.dropBalls.shift()
      if (ball) {
        ball.show = false
        el.style.display = 'none'
      }
    }
  },
  components: {
    cartcontrol
  }
}
</script>

<style lang="scss" scoped>
.shopcart {
  position: fixed;
  left: 0;
  bottom: 0;
  z-index: 50;
  width: 100%;

  .content {
    display: flex;
    align-items: center;
    font-size: 0;
    height: 68px;
    padding: 0 20px;
    background: #FFFFFF;
    box-shadow: 0 -2px 4px 0 rgba(13, 13, 13, 0.03);

    .content-left {
      flex: 1;
      display: flex;
      align-items: center;

      .logo-wrapper {
        position: relative;
        display: flex;
        align-items: center;
        justify-content: center;
        width: 56px;
        height: 56px;

        .logo {
          img {
            display: block;
            width: 26px;
            height: 24px;
          }
        }

        .num {
          position: absolute;
          top: 0;
          right: 0;
          width: 24px;
          height: 16px;
          line-height: 16px;
          text-align: center;
          border-radius: 16px;
          font-size: 9px;
          font-weight: 700;
          color: #fff;
          background: rgb(240, 20, 20);
          box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.4);
        }

      }

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

        &.highlight {
          color: #D32323;
        }
      }
    }

    .content-right {
      flex: 0 0 124px;
      width: 124px;
      text-align: center;

      .pay {
        width: 100%;
        height: 40px;
        color: #fff;
        font-size: 16px;
        font-family: PingFangSC-Semibold, PingFang SC;
        font-weight: 600;
        line-height: 40px;
        border-radius: 25px;

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

        &.enough {
          color: #FFFFFF;
          background: #D32323;
        }
      }
    }
  }
}

.ball-container {
  .ball {
    position: fixed;
    left: 32px;
    bottom: 22px;
    z-index: 200;
    transition: all 0.4s cubic-bezier(0.49, -0.29, 0.75, 0.41);

    .inner {
      width: 16px;
      height: 16px;
      border-radius: 50%;
      background: #D32323;
      transition: all 0.4s linear;
    }
  }
}

.shopcart-list {
  position: absolute;
  left: 0;
  top: 0;
  z-index: -1;
  width: 100%;
  transform: translate3d(0, -100%, 0);
  background: #FFFFFF;
  box-shadow: 0 -2px 4px 0 rgba(13, 13, 13, 0.15);
  border-radius: 16px 16px 0 0;

  &.fold-enter-active, &.fold-leave-active {
    transition: all 0.5s;
  }

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

  .list-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 16px 20px 7px;

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

    .empty {
      display: flex;
      align-items: center;

      img {
        width: 12px;
        height: 14px;
      }

      span {
        margin-left: 6px;
        font-size: 12px;
        color: #736F6F;
        line-height: 17px;
      }
    }
  }

  .list-content {
    height: 217px;
    padding: 0 20px;
    overflow: hidden;

    .food {
      position: relative;
      display: flex;
      align-items: center;
      margin: 12px 0;

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

      .name-wrap {
        width: calc(100% - 70px);
        margin-left: 10px;
      }

      .name {
        display: flex;
        align-items: center;
        flex-wrap: nowrap;
        width: 100%;
        white-space: nowrap;

        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-left: 5px;
            font-size: 12px;
            color: #736F6F;
            line-height: 17px;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
          }
        }
      }

      .price {
        display: flex;
        align-items: center;
        margin-top: 12px;

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

      .cartcontrol-wrapper {
        position: absolute;
        right: 0;
        bottom: 6px;
      }
    }
  }
}

.list-mask {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 40;
  background: rgba(0, 0, 0, 0.8);

  &.fade-enter-active, &.fade-leave-active {
    transition: all 0.5s;
  }

  &.fade-enter, &.fade-leave-active {
    opacity: 0;
    background: rgba(7, 17, 27, 0);
  }
}
</style>
