import {throttle} from '@/utils'

export default {
  data () {
    return {
      y: 0,
      yLock: '',
      startY: 0,
      disY: 0,
      dir: '',
      transform: 'translateY(0)',
      allowScroll: true,
      topText: '',
      bottomText: ''
    }
  },
  methods: {
    resetScroll () {
      this.y = 0
      this.yLock = ''
      this.startY = 0
      this.disY = 0
      this.dir = ''
      this.transform = 'translateY(0)'
      this.top = 0
      // this.allowScroll = false
      this.topText = ''
      this.bottomText = ''
      // console.log(this.yLock)
    },
    touchstart (e) {
      // console.log('开始', e.touches[0])
      this.y = 0
      let tc = e.touches[0]
      // let startX = touch.clientX
      this.startY = tc.clientY
      this.disY = this.startY - this.y
    },
    // touchmove
    touchmove: throttle(function (e) {
      // if (!this.allowScroll) return false
      // console.log('move', e.touches[0])
      const tc = e.touches[0]
      // 判断方向
      if (this.dir === '') {
        if (Math.abs(tc.clientY - this.startY) >= 5) {
          this.dir = 'y'
        }
      } else {
        // 确定方向后
        let y = tc.clientY - this.disY
        this.y = y
        // console.log(y, this.yLock)
        if (y > 0) {
          if (this.yLock === 'up') {
            this.transform = `translateY(${this.y}px)`
            return false
          }
          this.yLock = 'down'
          if (y < 100) {
            this.topText = '下拉加载上一个'
          } else {
            this.topText = '释放加载上一个'
          }
        }
        if (y < 0) {
          if (this.yLock === 'down') {
            this.transform = `translateY(${this.y}px)`
            return false
          }
          this.yLock = 'up'
          if (y > -100) {
            this.bottomText = '上拉加载下一个'
          } else {
            this.bottomText = '释放加载下一个'
          }
        }
        this.transform = `translateY(${this.y}px)`
      }
    }, 0, {
      leading: true,
      trailing: true
    }),
    touchend (e) {
      const y = this.y
      if (y > 0) {
        if (this.yLock === 'up') {
          this.resetScroll()
          return false
        }
        if (y < 100) {
          this.transform = `translateY(0)`
        } else {
          console.log('load prev')
          this.searchGoods('prev')
        }
      }
      if (y < 0) {
        if (this.yLock === 'down') {
          this.resetScroll()
          return false
        }
        if (y > -100) {
          this.transform = `translateY(0)`
        } else {
          // console.log('load next')
          this.searchGoods('next')
        }
      }
      this.resetScroll()
    }
    // scrolltoupper () {
    //   console.log('到顶了')
    //   // this.allowScroll = true
    // },
    // scrolltolower () {
    //   console.log('到底了')
    //   // this.allowScroll = true
    // },
    // scroll () {
    //   console.log('滚动')
    //   // if (this.allowScroll) this.allowScroll = false
    // }
  }
}