<template>
  <!-- Ŀǰ�汾��С����slot��������� -->
  <view class="wk-drag-sort">
    <view
      v-for="(item, index) in list"
      :id="`wk-drag-sort-item-` + index"
      :key="index"
      class="wk-drag-sort-item"
      @touchstart="handleTouchstart($event, index)"
      @touchmove.stop.prevent="handleTouchmove($event, index)"
      @touchend="handleTouchend($event, index)">
      <slot :scope-data="{ data: item, $index: index}" />
    </view>
		
    <view
      :style="{
        left: moveLeft + 'px',
        top: moveTop + 'px',
        width: itemWidth + 'px',
        height: itemHeight + 'px',
        visibility: showMoveItem ? 'unset' : 'hidden'
      }"
      class="move-item">
      <slot
        name="move"
        :data="moveItemData" />
    </view>
  </view>
</template>

<script>
	/**
	 * ��ק����
	 */
  import { deepCopy } from '@/utils/lib.js'
	
  export default {
    name: 'WkDragSort',
    props: {
      list: {
        type: Array,
        required: true
      },
      dealy: {
        type: Number,
        default: 100
      }
    },
    data() {
      return {
        allBoundary: [],
        moveItemData: {},
        activeIndex: -1,
				
        moveTop: 0,
        moveLeft: 0,
        itemWidth: 0,
        itemHeight: 0,
        showMoveItem: false,
				
        dealyTimer: null
      }
    },
    computed: {
      moveStyle() {
        return {
          left: this.moveLeft + 'px',
          top: this.moveTop + 'px',
          width: this.itemWidth + 'px',
          height: this.itemHeight + 'px',
          visibility: this.showMoveItem ? 'unset' : 'hidden'
        }
      }
    },
    watch: {
      list: {
        handler() {
          this.moveItemData = this.list[0]
          this.$nextTick(function() {
            this.getAllBoundary()
          })
        },
        deep: true,
        immediate: true
      },
      moveItemData: {
        handler() {
          this.$emit('set-move', this.moveItemData)
        },
        deep: true
      }
    },
    methods: {
      getAllBoundary() {
        const that = this
        uni.createSelectorQuery()
          .in(this)
          .selectAll('.wk-drag-sort-item')
          .boundingClientRect(data => {
            console.log('getAllBoundary: ', data)
            that.allBoundary = data.map(item => {
              return {
								...item,
								beginX: item.left,
								endX: item.left + item.width,
								beginY: item.top,
								endY: item.top + item.height,
              }
            })
          })
          .exec();
      },
			
      handleTouchstart(evt, index) {
        if (this.dealyTimer) {
          clearTimeout(this.dealyTimer)
          this.dealyTimer = null
        }
        this.dealyTimer = setTimeout(() => {
          const query = uni.createSelectorQuery().in(this);
          query.select(`#wk-drag-sort-item-${index}`).boundingClientRect(data => {
            this.moveTop = data.top
            this.moveLeft = data.left
						
            this.moveItemData = this.list[index]
            this.activeIndex = index
						
            this.itemWidth = data.width
            this.itemHeight = data.height
            this.showMoveItem = true; // ������ʼ
            console.log('start move')
						
            clearTimeout(this.dealyTimer)
            this.dealyTimer = null
          }).exec();
        }, this.dealy)
      },
			
      handleTouchmove(evt, index) {
        const touch = evt.touches[0];
        this.moveLeft = touch.clientX - this.itemWidth / 2
        this.moveTop = touch.clientY - this.itemHeight / 2
      },
			
      handleTouchend(evt, index) {
        const overIndex = this.findOverIndex()
				
        if (overIndex !== -1) {
          const arr = deepCopy(this.list)
          arr[overIndex] = arr.splice(this.activeIndex, 1, arr[overIndex])[0]
          console.log('sort: ', arr)
          this.$emit('sort', arr)
        }
				
        this.showMoveItem = false // ��������
        this.activeIndex = -1
        this.moveLeft = 0
        this.moveTop = 0
      },
			
      // �ҵ�ͣ�µ�Ԫ�ص��±�
      findOverIndex() {
        for (let i = 0; i < this.allBoundary.length; i++) {
          const item = this.allBoundary[i]
          if (
            this.moveLeft > item.beginX &&
            this.moveLeft < item.endX &&
            this.moveTop > item.beginY &&
            this.moveTop < item.endY
          ) {
            return i
          }
        }
        return -1
      }
    }
  }
</script>

<style scoped lang="scss">
	.wk-drag-sort {
		.wk-drag-sort-item {}
		.move-item {
			position: fixed;
			visibility: hidden;
			z-index: 10;
		}
	}
</style>
