<template>
  <div class="top-cats">
    <scroll-view class="scroll-x" :scroll-left="scrollLeft" scroll-x="true" :scroll-into-view="intoID" @scroll="scroll">
      <div class="scroll-area">
        <div
          :class="{
            'scroll-item': true,
            'cat-active': current === cat.id
          }"
          v-for="(cat, index) in cats"
          :key="cat.id"
          :id="'c' + cat.id"
          @click="clickCat(cat.id, index)"
        >
          {{cat.name}}
        </div>
        <div class="scroll-item-placeholder"></div>
      </div>
    </scroll-view>
    <div :class="{'btn-up-down': true, 'arrow-active': up}" @click="clickArrow"></div>
  </div>
</template>

<script>
import {debounce} from '@/utils'
export default {
  name: 'TopCats',
  props: ['cats', 'current', 'wallShow', 'up'],
  data () {
    return {
      intoID: 'c0',
      scrollLeft: 0,
      oldScroll: 0
    }
  },
  methods: {
    // 点击箭头
    clickArrow () {
      this.$emit('toggleCat2')
    },
    // 点击分类
    clickCat (id, index) {
      this.$emit('cat2Change', {
        id,
        index
      })
    },
    scrollInToIndex (index) {
      this.intoID = 'c' + this.cats[index - 1 >= 0 ? index - 1 : 0].id
    },
    // 设置位置
    // setScroll (id) {
    //   let index = this.cats.findIndex(item => item.id === id)
    //   this.intoID = 'c' + this.cats[index - 1 >= 0 ? index - 1 : 0].id
    // },
    // 滚动防抖
    scroll: debounce(function (e) {
      this.oldScroll = e.detail.scrollLeft
    }, 50)
  },
  watch: {
    cats (to, from) {
      if (from[1] && to[1] && to[1].id !== from[1].id) {
        // 回到原点
        this.scrollLeft = this.oldScroll
        this.$nextTick(() => {
          this.scrollLeft = 0
        })
      }
    }
  }
}
</script>

<style lang="scss">
@import "./top-cats.scss";
</style>