<!------------------------------------------- template ------------------------------------------->
<template>
  <view class="dw-index-list">
    <scroll-view
      scroll-y
      @scroll="actionScroll"
      :scroll-into-view="selector"
      style="height: 100%;"
    >
      <view class="dw-index-list-group" v-for="group in getGroupList" :key="group.initial">
        <view class="dw-index-list-group-title" :id="group.initial">{{ group.initial }}</view>
        <view
          class="dw-index-list-group-item"
          @click="$emit('on-select', row)"
          v-for="(row, index) in group.children"
          :key="index"
        >
          <text
          class="row-title"
          v-for="(item, itemIndex) in calcHightlight(row.label)"
          :class="{ highlight: getKeywords.includes(item) }"
          :key="itemIndex">{{ item }}</text>
        </view>
      </view>
    </scroll-view>

    <view
      class="dw-index-list-nav"
      @touchstart="actionListTouchStart"
      @touchmove="actionListTouchMove"
      @touchend="actionListTouchEnd"
    >
      <!-- <view class="dw-index-list-nav-item">热门</view> -->
      <view
        class="dw-index-list-nav-item"
        :class="{ active: curIndex === index }"
        @click="actionScrollTo(item)"
        v-for="(item, index) in navList"
        :key="item"
      >{{ item }}</view>
    </view>
  </view>
</template>

<!-------------------------------------------- script -------------------------------------------->
<script>
function throttle(func, delay) {
  let lastCall = 0;  
  return function(...args) {  
    const now = Date.now();  
    if (now - lastCall < delay) {  
      return;  
    }  
    lastCall = now;  
    return func.apply(this, args);  
  };  
}
export default {
  name: '',
  components: {
  },
  options: {
    virtualHost: true
  },

  props: {
    data: {
      type: Object,
      default: () => {
        return {}
      }
    },
    needSort: {
      type: Boolean,
      default: true
    },
    keywords: {
      type: String,
      default: ''
    }
  },

  data() {
    return {
      timer: '',
      listMoveLock: false,
      indexArr: [], // 位置 Arr
      startY: 0, // 移动距离
      selector: '',
      startIndex: '',
      curSelector: '',
      curIndex: 0,
      targetIndex: '',
      catchList: [],
      originCompanyList: [],
      // 新字段
      groupList: [],
    }
  },

  /* 一.生命周期函数 */
  created() {
    this.initData()
  },

  /* 二.监控函数 */
  watch: {
    data () {
      this.initData()
    }
  },

  computed: {
    dataList () {
      const dataList = this.data?.dataList || []
      let arr = []
      if (this.keywords) {
        arr = dataList.filter(item => item.label.includes(this.keywords))
      }
      return arr.length ? arr : dataList
    },
    navList () {
      let dataList = this.dataList
      
      const navList = Array.from(new Set(this.dataList.map(i => i.initial)))
      if (this.needSort) {
        navList.sort((a, b) => a > b ? 1 : -1)
      }
      
      return navList
    },
    getGroupList() {
      let arr = []
      if (this.groupList.length === 0) return arr
      if (this.keywords) {
        arr = this.format(this.dataList.filter(item => item.label.includes(this.keywords)))
      }

      setTimeout(() => {
        const query = uni.createSelectorQuery().in(this)
        query.selectAll('.dw-index-list-group').boundingClientRect(res => {
          const startTop = res[0].top
          console.log(123123, res[0])
          this.indexArr = res.map(item => {
            return item.top - startTop + item.height
          })
        }).exec()
      }, 50)

      arr = arr.length ? arr : this.groupList
      this.curSelector = arr[0]?.initial
      return arr
    },
    getGroupListQuick() {
      let arr = []
      if (this.keywords) {
        arr = this.format(this.dataList.filter(item => item.label.includes(this.keywords)))
      }

      return arr.length ? arr : this.groupList
    },
    getKeywords() {
      return this.keywords.split(' ');
    }
  },

  /* 三.内部功能函数 */
  methods: {
    /* ----------------------事件调用函数------------------------ */
    actionScroll (e) {
      if (this.listMoveLock) return
      const { scrollTop } = e.detail
      const index = this.indexArr.findIndex(item => {
        return scrollTop <= item
      })
      this.curIndex = index
    },
    // 事件调用函数注释
    actionScrollTo(selector) {
      this.listMoveLock = true
      this.selector = selector
      this.curIndex = this.getGroupListQuick.findIndex(item => item.initial === selector)
      this.targetIndex = this.curIndex
    },

    // 滑动选择事件
    actionListTouchStart (e) {
      this.listMoveLock = true
      const position = e.changedTouches[0]
      this.catchList = this.getGroupListQuick.map(item => item.initial)
      this.startIndex = this.curIndex
      if (position) {
        this.startY = position.clientY
      }
      this.timer = setInterval(() => {
        this.curIndex = this.targetIndex
        this.selector = this.catchList[this.curIndex]
      }, 10)
    },
    actionListTouchMove: throttle(function (e) {
      const position = e.changedTouches[0]
      if (position) {
        const distance = position.clientY - this.startY
        this.targetIndex = this.startIndex + parseInt(distance / 20)
        if (this.targetIndex < 0) {
          this.targetIndex = 0
        } else {
          this.targetIndex = Math.min(this.targetIndex, this.catchList.length - 1)
        }
      }
    }, 20),
    actionListTouchEnd (e) {
      clearInterval(this.timer)
      setTimeout(() => {
        this.listMoveLock = false
        this.startY = 0
      }, 300)
    },
    /* ----------------------内部功能函数------------------------ */
    // 初始化数据
    initData () {
      console.log('初始化', this.data)
      this.groupList = this.format(this.dataList)
    },
    // 内部功能函数注释
    format(dataList) {
      const group = {}
      
      if (this.needSort) {
        dataList.sort((a, b) => a.initial > b.initial ? 1 : -1)
      }

      dataList.forEach(item => {
        const { initial } = item
        if (!group[initial]) {
          group[initial] = {
            initial,
            children: []
          }
        }

        group[initial].children.push(item)
      })

      return Object.values(group)
    },
    calcHightlight(companyName) {
      let productName = companyName;
      if (!productName || !this.keywords) return [productName];
      let arr = [productName];
      this.getKeywords.forEach(keywords => {
        const curArr = [];
        arr.forEach(item => {
          const splitArr = item.split(keywords);
          for (let i = splitArr.length - 1; i > 0; i--) {
            splitArr.splice(i, 0, keywords);
          }
          curArr.push(...splitArr);
        });
        arr = curArr;
      });

      return arr;
    },

    /* ----------------------服务请求函数------------------------ */
  }
}
</script>

<!-------------------------------------------- style -------------------------------------------->
<style scoped lang="scss">
.dw-index-list {
  width: 100%;
  position: relative;
  transform: translateZ(0);

  &-nav {
    position: absolute;
    display: flex;
    flex-direction: column;
    align-items: center;
    right: 0;
    max-height: 100%;
    overflow-y: scroll;
    top: 50%;
    transform: translateY(-50%);

    &-item {
      font-size: 20rpx;
      font-weight: 400;
      color: #666666;
      width: 36rpx;
      height: 36rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      border-radius: 50%;
      &.active{
        background: #ccc;
        color: #FFF;
      }
      &:active{
        background: #ccc;
        color: #FFF;
      }
    }
  }

  height: 100%;

  &-group {
    &-title {
      padding: 32rpx 68rpx 12rpx 24rpx;
      font-size: 24rpx;
      font-family: PingFangSC, PingFang SC;
      font-weight: 500;
      color: #333333;
    }

    &-item {
      position: relative;
      padding: 20rpx 68rpx 20rpx 24rpx;
      font-size: 28rpx;
      font-weight: 400;
      color: #333333;

      &::after {
        content: ' ';
        position: absolute;
        height: 1rpx;
        width: 100%;
        left: 24rpx;
        top: 0;
        background: #EBEBEB;
      }
    }
  }
}
.row-title{
  &.highlight{
    color: #ff7019;
  }
}
</style>
