<template>
  <view class="u-vtabs" :style="[vtabsStyle]">
    <scroll-view
      class="u-vtabs__bar"
      ref="u-vtabs__bar"
      :style="[getBarStyle]"
      :scroll-y="barScrollable"
      :scroll-x="scrollX"
      :show-scrollbar="false"
      :scroll-with-animation="true"
      :scroll-top="barScrollTop"
      :scroll-into-view="barScrollToView"
    >
      <view
        :class="[
          'u-vtabs__bar-item',
          `u-vtabs__bar-item--${index}`,
          index == activeIndex && 'u-vtabs__bar-item-active',
        ]"
        :ref="`u-vtabs__bar-item--${index}`"
        v-for="(item, index) in dataSource"
        :key="index"
        :id="`bar_${index}`"
        :style="[itemStyle(index)]"
        @tap.stop="clickHandler(index)"
      >
        <slot name="leftItem" v-bind="{ item, index }"> </slot>
      </view>
    </scroll-view>
    <scroll-view
      class="u-vtabs__content"
      :style="[getContentStyle, $u.addStyle(contentStyle)]"
      :scroll-y="true"
      :scroll-x="scrollX"
      :show-scrollbar="false"
      :scroll-top="contentScrollTop"
      :scroll-into-view="contentScrollTo"
      :scroll-with-animation="true"
      @scroll="scrollHandler"
      @scrolltolower="scrolltolower"
      v-if="chain"
    >
      <w-vtabs-item
        v-for="(item, index) in dataSource"
        :key="index"
        :index="index"
        :resize="childrenResize"
      >
        <view class="class-item">
          <slot name="rightItem" v-bind="{ item, index }"> </slot>
        </view>
      </w-vtabs-item>
    </scroll-view>
    <scroll-view
      v-else
      class="u-vtabs__content"
      :style="[getContentStyle, $u.addStyle(contentStyle)]"
      :scroll-y="true"
      :scroll-x="scrollX"
      :show-scrollbar="false"
      :scroll-top="contentScrollTop2"
      @scrolltolower="scrolltolower"
    >
      <w-vtabs-item
        v-for="(item, index) in dataSource"
        :key="index"
        :index="index"
        :resize="childrenResize"
      >
        <view class="class-item">
          <slot name="rightItem" v-bind="{ item, index }"> </slot>
        </view>
      </w-vtabs-item>
    </scroll-view>
  </view>
</template>
<script>
import mpMixin from "uview-plus/libs/mixin/mpMixin.js";
import mixin from "uview-plus/libs/mixin/mixin.js";
import debounce from "uview-plus/libs/function/debounce.js";
import throttle from "uview-plus/libs/function/throttle.js";
import uBadgeProps from "uview-plus/components/u-badge/props.js";
import props from "./props.ts";

/**
 * 垂直选项卡
 * @description 该组件兼容所有端，提供了分类展示和联动等功能
 * @tutorial https://www.uvui.cn/components/vtabs.html
 * @property {Array}	dataSource  选项数组，元素为对象，如[{name:'u-ui'}]（默认 [] ）
 * @property {String}  keyName  从list元素对象中读取的键名（默认 name ）
 * @property {Number}  current  当前选中项，从0开始（默认 0 ）
 * @property {Number | String}  hdHeight  头部内容的高度，头部有内容必传，否则会有联动误差（默认 0 ）
 * @property {Boolean}  chain  是否开启联动，开启后右边区域可以滑动查看内容（默认 true ）
 * @property {Number|String}  height  整个列表的高度，默认auto或空则为屏幕高度（默认 auto屏幕高度 ）
 * @property {Number|String}  barWidth  左边选项区域的宽度（默认 180rpx ）
 * @property {Boolean}  barScrollable  左边选项区域是否允许滚动 （默认 true ）
 * @property {String}  barBgColor  左边选项区域的背景颜色（默认$u-bg-color）
 * @property {Object}  barStyle  左边选项区域的自定义样式 （默认{}）
 * @property {Object}  barItemStyle  左边选项区域每个选项的自定义样式 （默认{}）
 * @property {Object}  barItemActiveStyle  左边选项区域选中选项的自定义样式 （默认{}）
 * @property {Object}  barItemActiveLineStyle  左边选项区域选中选项竖线条的自定义样式 （默认{}）
 * @property {Object}  barItemBadgeStyle  左边选项区域选中选项徽标的自定义样式，主要用于设置位置 （默认{}）
 * @property {Object}  contentStyle  右边区域自定义样式 （默认{}）
 * @example <u-vtabs :dataSource="dataSource"><u-vtabs-item>...</u-vtabs-item></u-vtabs>
 */
export default {
  name: "w-vtabs",
  mixins: [mpMixin, mixin, props],
  created() {
    this.children = [];
  },
  mounted() {
    this.$nextTick(() => {
      this.init(this.current);
    });
  },
  data() {
    return {
      activeIndex: 0,
      // 微信小程序下，scroll-view的scroll-into-view属性无法对slot中的内容的id生效，只能通过设置scrollTop的形式去移动滚动条
      contentScrollTop: 0,
      contentScrollTop2: 0, //针对非联动
      contentScrollTo: "",
      scrolling: false,
      barScrolling: false,
      touching: false,
      hasHeight: 0,
      scrollViewHeight: 0,
      barScrollTop: 0,
      barScrollToView: "",
      timer2: 0,
      childrenResize: false, // 子项重新计算高度
    };
  },
  computed: {
    scrollX() {
      return false;
    },
    vtabsStyle() {
      const style = {};
      style.height = this.getHeight();
      return uni.$u.deepMerge(style, uni.$u.addStyle(this.customStyle));
    },
    getBarStyle() {
      const style = {};
      style.width = uni.$u.getPx(this.barWidth, true);
      style.background = this.barBgColor;
      style.height = this.getHeight();
      if (!this.barStyle) return style;
      return uni.$u.deepMerge(style, uni.$u.addStyle(this.barStyle));
    },
    itemStyle() {
      return (index) => {
        const style = {};
        let barItemInitStyle = this.barItemStyle;
        // 避免在nvue模式下，切换时候上一个选中颜色不变
        if (this.barItemStyle && !this.barItemStyle?.background) {
          barItemInitStyle.background = "transparent";
        }
        // 是否激活的样式
        const customeStyle =
          index === this.activeIndex
            ? uni.$u.addStyle(this.barItemActiveStyle)
            : uni.$u.addStyle(barItemInitStyle);
        if (this.dataSource[index].disabled) {
          style.color = "#c8c9cc";
        }
        return uni.$u.deepMerge(style, customeStyle);
      };
    },
    // nvue设置字体样式必须要text标签上进行
    textStyle() {
      return (index) => {
        const style = {};
        style.width = uni.$u.getPx(this.barWidth, true);
        return style;
      };
    },
    getContentStyle() {
      const style = {};
      style.height = this.getHeight();
      return style;
    },
  },
  watch: {
    current(newVal) {
      if (!this.touching)
        this.$nextTick(() => {
          this.init(newVal ? newVal : 0);
        });
    },
    dataSource(newVal) {
      this.childrenResize = !this.childrenResize;
      if (newVal.length) {
        uni.$u.sleep(30).then((res) => {
          this.resize();
        });
      }
    },
    activeIndex(newVal) {
      if (!this.chain) {
        // 解决：非联动，内容过多的情况，滚动一段距离，再切换未滚动到顶部的BUG
        this.contentScrollTop2 = 0 - Math.random() * 4 - 4;
      }
      this.$emit("change", newVal);
    },
  },
  methods: {
    init(index) {
      let num = 0;
      clearInterval(this.timer2);
      this.timer2 = setInterval(async () => {
        num++;
        if (num > 50) clearInterval(this.timer2);
        if (this.children.length) {
          clearInterval(this.timer2);
          await uni.$u.sleep(300);
          this.clickHandler(index);
        }
      }, 100);
    },
    // 内容滚动到底部触发
    scrolltolower() {
      this.$emit("scrolltolower", this.activeIndex);
    },
    async resize() {
      // 如果list数组长度为0就不处理 || 选中目标未变则不处理
      if (this.dataSource.length == 0 || !this.barScrollable) return;
      // 避免滑太快，修复位置
      Promise.all([this.getTabsRect(), this.getAllItemRect()]).then(
        ([tabsRect, itemRect = []]) => {
          this.tabsRect = tabsRect;
          this.scrollViewHeight = 0;
          itemRect.map((item, index) => {
            this.scrollViewHeight += item.height;
            this.dataSource[index].rect = item;
          });
          this.setBarScrollTop();
        }
      );
    },
    // 设置左边菜单滚动条的位置，目标：将当前的选项移到中间位置
    setBarScrollTop() {
      const tabRect = this.dataSource[this.activeIndex];
      const offsetTop = this.dataSource
        .slice(0, this.activeIndex)
        .reduce((total, item) => {
          return total + item.rect.height;
        }, 0);
      const scrollViewHeight = uni.$u.getPx(this.getHeight());
      let barScrollTop =
        tabRect.rect.height / 2 + offsetTop - scrollViewHeight / 2;
      // 先给一点随机值，避免出现不能滚动的BUG
      barScrollTop = Math.min(
        barScrollTop,
        this.scrollViewHeight - this.tabsRect.height
      );
      this.barScrollTop = Math.max(0, barScrollTop);
      // 已经不能滚动的时候，就使用scroll-into-view的方式进行定位，避免失效
      if (barScrollTop >= this.scrollViewHeight - this.tabsRect.height) {
        this.timer && clearTimeout(this.timer);
        this.timer = setTimeout(() => {
          this.barScrollToView = `bar_${this.activeIndex}`;
        }, 400);
      }
    },
    // 左边菜单点击
    async clickHandler(currentIndex) {
      if (currentIndex == this.activeIndex) return;
      this.touching = true;
      this.activeIndex = currentIndex;
      if (this.chain) {
        // 给一点随机值，避免出现不能滚动的BUG。微信端必须用此方法
        this.contentScrollTop =
          this.children[currentIndex].top -
          uni.$u.getPx(this.hdHeight) -
          Math.random() * 4 -
          4;
        // #ifndef MP-WEIXIN
        this.contentScrollTo = `content_${currentIndex}`;
        // #endif
      }
      this.timer && clearTimeout(this.timer);
      throttle(
        () => {
          this.resize();
        },
        300,
        false
      );
      debounce(() => {
        this.touching = false;
      }, 900);
    },
    // 内容滚动
    scrollHandler(e) {
      if (this.touching || this.scrolling) return;
      // 每过一定时间取样一次，减少资源损耗以及可能带来的卡顿
      this.scrolling = true;
      uni.$u.sleep(80).then(() => {
        this.scrolling = false;
      });
      const scrollTop = e.detail.scrollTop;
      let children = this.children;
      const len = children.length;
      let top = 0;
      let activeIndex = 0;
      children = this.children.map((item, index) => {
        if (item.height > 0) this.hasHeight = item.height;
        item.height = item.height > 0 ? item.height : this.hasHeight;
        const child = {
          height: item.height,
          top,
        };
        // 进行累加，给下一个item提供计算依据
        top += item.height;
        return child;
      });
      for (let i = 0; i < len; i++) {
        const item = children[i];
        const nextItem = children[i + 1];
        // 如果滚动条高度小于第一个item的top值，此时无需设置任意字母为高亮
        if (scrollTop <= children[0].top) {
          activeIndex = 0;
          break;
        } else if (!nextItem) {
          // 当不存在下一个item时，意味着历遍到了最后一个
          activeIndex = len - 1;
          break;
        } else if (scrollTop > item.top && scrollTop < nextItem.top) {
          activeIndex = i;
          break;
        }
      }
      this.activeIndex = activeIndex;
      // 当前选中项索引必然来源于前后两个索引，满足才执行，避免闪烁的bug
      this.timer4 && clearTimeout(this.timer4);
      this.timer4 = setTimeout(() => {
        this.resize();
      }, 100);
    },
    // 设置高度
    getHeight() {
      let height = 0;
      const isEmpty = uni.$u.test.empty(this.height);
      if (isEmpty || this.height == "auto")
        height = uni.$u.addUnit(uni.$u.sys().windowHeight);
      else height = uni.$u.getPx(this.height, true);
      return height;
    },
    // 获取导航菜单的尺寸
    getTabsRect() {
      return new Promise((resolve) => {
        this.queryRect("u-vtabs__bar").then((size) => resolve(size));
      });
    },
    // 获取所有标签的尺寸
    getAllItemRect() {
      return new Promise((resolve) => {
        const promiseAllArr = this.dataSource.map((item, index) =>
          this.queryRect(`u-vtabs__bar-item--${index}`, true)
        );
        Promise.all(promiseAllArr).then((sizes) => resolve(sizes));
      });
    },
    // 获取各个标签的尺寸
    queryRect(el, item) {
      return new Promise((resolve) => {
        this.$uGetRect(`.${el}`).then((size) => {
          resolve(size);
        });
      });
    },
  },
};
</script>
<style scoped lang="scss">
@import "uview-plus/libs/css/components.scss";
@import "uview-plus/libs/css/color.scss";
.u-vtabs {
  @include flex;
  &__bar {
    background: $u-bg-color;
    // background: #f4f4f4;
    &-item {
      position: relative;
      @include flex;
      align-items: center;
      justify-content: center;
      padding: 35rpx 12rpx 35rpx 20rpx;
      &--value {
        font-size: 26rpx;
        color: $u-content-color;
      }
      &-active {
        background: #fff;
        font-size: 30rpx;
        font-weight: 600;
        &--value {
          color: $u-primary;
        }
      }
      &--line {
        position: absolute;
        width: 2px;
        left: 0;
        top: 0;
        bottom: 0;
        z-index: 1;
        background-color: $u-primary;
      }
      &--badge {
        position: absolute;
        top: 4px;
        right: 10px;
        z-index: 1;
      }
    }
  }
  &__content {
    flex: 1;
    background: #fff;
  }
  .u-vtabs__content {
    background-color: $u-bg-color;
    padding: 16rpx;
    box-sizing: border-box;
    .class-item {
      margin-bottom: 30rpx;
      background-color: #fff;
      padding: 16rpx;
      border-radius: 8rpx;
    }

    .class-item:last-child {
      min-height: 20vh;
    }
  }
}
</style>
./props.js