// components/v-tab/v-tab.js
const sliderWidth = 65
const app = getApp()
Component({
  /**
     * 组件的属性列表
     */
  externalClasses: ['extra-class'],
  properties: {
    dataList: {
      type: Array,
      value: [],
      observer(selectIndex) {
        this.menuData()
      }
    },
    type: {
      type: String,
      value: 'array' // array 为 [1,2,3] 格式 objectArray 为 [{}]格式
    },
    selectIndex: {
      type: Number,
      value: 0,
      observer(selectIndex) {
        this.menuData()
      }
    }
  },

  /**
     * 组件的初始数据
     */
  data: {
    sliderOffset: 0,
    sliderLeft: 0
  },

  // observers: {
  //     'selectIndex': function(selectIndex) {
  //         this.menuData()
  //     }
  //   },

  lifetimes: {
    attached() {
      this.menuData()
    }
  },

  /**
     * 组件的方法列表
     */
  methods: {
    menuData() {
      wx.getSystemInfo({
        success: res => {
          this.setData({
            sliderLeft: (res.windowWidth / this.data.dataList.length - sliderWidth) / 2,
            sliderOffset: res.windowWidth / this.data.dataList.length * this.data.selectIndex
          })
        }
      })
    },
    tabClick(e) {
      const { offsetLeft, id } = e.currentTarget
      this.setData({
        sliderOffset: offsetLeft,
        selectIndex: id
      })
      if (this.data.type === 'array') {
        this.triggerEvent('selectIndex', Number(id))
      }
      if (this.data.type === 'objectArray') {
        this.triggerEvent('selectIndex', this.data.dataList[id].id)
      }
    }
  }
})