<template>
  <div class="alphabetically">
    <div class="title">
      <cr-icon type="arrow-left" color="#C8C9CC" size="22px" @click.native="back" />
      <div class="text">{{ title }}</div>
      <div class="rightBtn" @click.stop="confirm">{{ rightBtn }}</div>
    </div>
    <div ref="content" class="content" @scroll="calcSelectIndex">
      <template v-for="(item, idx) in sortData">
        <div
          v-if="item.length > 0"
          :id="idx"
          :ref="`item-${idx}`"
          :key="`sort-${idx}`"
          class="group"
        >
          <div class="group-title">
            {{ idx }}
          </div>
          <div
            v-for="(val, key) in item"
            :key="`item-${key}`"
            class="group-item"
            :class="{
              last: key == item.length - 1,
              first: key == 0,
              select: brandIds.indexOf(val.valueId) > -1
            }"
            @click.stop="clickBrandItem(val)"
          >
            <cr-icon type="success" size="14px" />
            {{ val.showName }}
          </div>
        </div>
      </template>
    </div>
    <div ref="sortIndexs" class="sortIndexs">
      <div
        v-for="(v, k) in letters"
        :ref="`index-${k}`"
        :key="`sortIndex-${k}`"
        class="text"
        :class="{ select: v == selectIndex }"
        @click="jumpTo(v)"
      >
        {{ v }}
      </div>
      <transition name="fade">
        <div v-if="showPopover" class="popover">
          {{ selectIndex }}
          <div class="popover__angle" />
        </div>
      </transition>
    </div>
  </div>
</template>
<script>
import { EventBus } from '@/service/utils.service';
const CLEAR_BRAND_SELECT_LIST = 'clearBrandSelectList';
export default {
  props: {
    title: {
      type: String,
      default: ''
    },
    rightBtn: {
      type: String,
      default: ''
    },
    sortData: {
      type: Object,
      default() {
        return {};
      }
    }
  },
  data() {
    return {
      selectIndex: '',
      brandSelectList: [],
      showPopover: false,
      popoverHideTimer: null // popover定时器
    };
  },
  computed: {
    brandIds() {
      return this.brandSelectList.map(item => item.valueId);
    },
    letters() {
      const arr = [];
      for (let i in this.sortData) {
        if (this.sortData[i] && this.sortData[i].length > 0) arr.push(i);
      }
      return arr;
    }
  },
  watch: {
    selectIndex() {
      this.showPopover = true;
      clearTimeout(this.popoverHideTimer);
      this.popoverHideTimer = setTimeout(() => {
        this.showPopover = false;
      }, 1500);
    }
  },
  beforeDestroy() {
    EventBus.$off(CLEAR_BRAND_SELECT_LIST);
  },
  created() {
    EventBus.$on(CLEAR_BRAND_SELECT_LIST, () => {
      this.brandSelectList = [];
    });
  },
  methods: {
    clickBrandItem(item) {
      // 选择品牌
      const { valueId } = item;
      if (!valueId) return;
      const index = this.brandSelectList.findIndex(item => item.valueId == valueId);
      if (index == -1) {
        this.brandSelectList.push(item);
      } else {
        // 已经存在进行去除
        this.brandSelectList.splice(index, 1);
      }
    },
    confirm() {
      EventBus.$emit('selectBrandBySortList', Array.from(new Set(this.brandSelectList)));
      this.back();
    },
    clear() {
      this.brandSelectList = [];
    },
    back() {
      this.$emit('back');
      this.$refs.content.scrollTop = 0;
    },
    jumpTo(index) {
      this.selectIndex = index;
      this.$refs.content.scrollTop = this.$refs[`item-${index}`][0].offsetTop;
    },
    calcSelectIndex(e) {
      const offsetTopMap = {};
      const indexMap = {};
      const numArr = [];
      for (let i = 0; i < this.letters.length; i++) {
        offsetTopMap[this.letters[i]] = this.$refs[`item-${this.letters[i]}`][0].offsetTop;
        numArr.push(this.$refs[`item-${this.letters[i]}`][0].offsetTop);
        indexMap[i] = this.letters[i];
      }
      const targetIndex = this.findCloseNum(numArr, e.target.scrollTop, indexMap);
      this.selectIndex = targetIndex;
    },
    findCloseNum(arr, num, indexMap) {
      let index = 0; // 保存最接近数值在数组中的索引
      let value = Number.MAX_VALUE; // 保存差值绝对值，默认为最大数值
      for (let i = 0; i < arr.length; i++) {
        let newValue = Math.abs(arr[i] - num); // 新差值
        if (newValue <= value) {
          // 如果新差值绝对值小于等于旧差值绝对值，保存新差值绝对值和索引
          if (newValue === value && arr[i] < arr[index]) {
            // 如果数组中两个数值跟目标数值差值一样，取大
            continue;
          }
          index = i;
          value = newValue;
        }
      }
      return indexMap[index]; // 返回最接近的数值
    }
  }
};
</script>
<style lang="less" scoped>
.alphabetically {
  width: 100%;
  height: 100%;
  padding: 0 20px 0 16px;
  box-sizing: border-box;
  // position: relative;
  .sortIndexs {
    width: 16px;
    position: absolute;
    right: @padding-sm;
    top: 50%;
    transform: translateY(-50%);
    background: #f2f3f5;
    border-radius: 8px;
    padding: @padding-xs 0;
    z-index: 3;
    .text {
      width: 100%;
      display: flex;
      align-items: center;
      justify-content: center;
      .text-size(11);
      color: @gray-4;
      &.select {
        color: @black;
        font-weight: bold;
      }
    }
  }
  .title {
    width: 100%;
    display: flex;
    justify-content: space-between;
    align-items: center;
    height: 30px;
    .text {
      font-size: 16px;
      color: @black;
      font-weight: bold;
    }
    .rightBtn {
      font-size: 14px;
      color: @black;
    }
  }
  .content {
    height: calc(100% - 30px);
    overflow-y: auto;
    overflow-x: hidden;
    background: @white;
    position: relative;
    .group-title {
      position: sticky;
      top: 0;
      background: @white;
      font-size: 14px;
      color: @black;
      font-weight: bold;
      box-shadow: 0 -1px @white;
      user-select: none;
      padding: @padding-lg 0 @padding-xs;
      z-index: 2;
    }
    .group-item {
      font-size: 12px;
      color: @black;
      margin-bottom: @padding-lg;
      user-select: none;
      padding: 0 20px 0 0;
      box-sizing: border-box;
      display: flex;
      align-items: center;
      /deep/ .cr-icon {
        display: none;
        margin-right: 4px;
      }
      &.select {
        font-weight: bold;
        /deep/ .cr-icon {
          display: inline-block;
          font-weight: normal;
          color: @red;
        }
      }
      a {
        visibility: hidden;
      }
      &.last {
        margin-bottom: 0;
      }
      &.first {
        margin-top: @padding-xs;
      }
    }
  }
}
.popover {
  position: absolute;
  right: 34px;
  top: 50%;
  transform: translateY(-50%);
  width: 30px;
  height: 30px;
  background: @white;
  border-radius: 50%;
  color: @gray-5;
  font-size: 16px;
  line-height: 30px;
  text-align: center;
  box-shadow: 0 2px 12px 0 rgba(100, 101, 102, 0.12);
  &__angle {
    position: absolute;
    top: 50%;
    right: -6px;
    transform: translateY(-50%);
    z-index: -1;
    &::after {
      content: '';
      content: '';
      display: block;
      border-color: transparent transparent @white;
      border-style: solid;
      border-width: 0 6px 6px;
      box-shadow: 0 2px 12px 0 rgba(100, 101, 102, 0.12);
      // margin-bottom: 50%;
      transform: rotate(90deg);
    }
  }
}
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.5s;
}
.fade-enter, .fade-leave-to /* .fade-leave-active below version 2.1.8 */ {
  opacity: 0;
}
</style>
