<!--
 * @Author: jmy
 * @Date: 2025-12-13 12:02:41
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2025-12-19 15:02:01
 * @Description: 
-->
<template>
  <scroll-view class="scs-scroll-navbar" scroll-x :scroll-left="scrollLeft" scroll-with-animation="true">
    <view v-for="(item, index) in tabsData" :key="index" class="nav-item"
      :class="index === tabCurrentIndex ? 'act-current' : ''" @tap="tabChange(index)" :id="'item-' + index">
      <view class="item-title" :style="{ 'color': index === tabCurrentIndex ? activeColor : textColor }">
        {{ item[nameKey] }}
      </view>
    </view>
    <view class="nav-underline" :style="underlineStyle">
      <image v-if="isUseActImg" :src="activeImage"></image>
    </view>
  </scroll-view>
</template>

<script>
export default {
  name: 'scs-scroll-navbar',
  props: {
    // 导航项数据
    tabsData: {
      type: Array,
      default() {
        return [];
      },
    },
    // 当前选中的导航项索引
    tabCurrentIndex: {
      type: Number,
      default: 0,
    },
    // 导航项名称键名
    nameKey: {
      type: String,
      default: 'name',
    },
    // 导航项左侧间距px
    calcLeft: {
      type: Number,
      default: 12,
    },
    // 是否需要滚动
    isScroll: {
      type: Boolean,
      default: true,
    },
    // 选中导航项的字体颜色
    activeColor: {
      type: String,
      default: '#333333  ',
    },
    // 未选中导航项的字体颜色
    textColor: {
      type: String,
      default: '#4D4D4D',
    },
    // 选中导航项的图片
    activeImage: {
      type: String,
      default: 'https://fs-1319721001.cos.ap-chongqing.myqcloud.com/images/tj_tab_hover.png',
    },
    // 是否使用选中导航项的图片
    isUseActImg: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      scrollLeft: 0,
      widthList: [],
      screenWidth: 0,
      itemPositions: [], // 存储每个导航项的位置信息
    };
  },
  computed: {
    // 计算下划线的样式
    underlineStyle() {
      if (this.itemPositions.length === 0 || this.tabCurrentIndex >= this.itemPositions.length) {
        return {};
      }
      const position = this.itemPositions[this.tabCurrentIndex];
      if (this.tabCurrentIndex === 0) {
        position.left = 1
      }
      return `width:${position.width}px;left:${position.left}px;opacity:1`;
    },
  },
  watch: {
    tabCurrentIndex: function (val) {
      if (!this.isScroll) return
      this.tabScroll(val);
    },
    tabsData: function (val) {
      this.init();
    },
  },
  methods: {
    // 导航栏点击
    tabChange(index) {
      let self = this;
      self.$emit('tabChange', index);
    },
    // 导航栏滚动
    tabScroll(index) {
      var widthArr = this.widthList;
      var scrollWidth = 0;
      for (var i = 0; i < index + 1; i++) {
        scrollWidth += widthArr[i];
      }
      let currentWidth = widthArr[index];
      // scrollView 居中算法
      // 减去固定宽度位移
      // 减去选中的bar的宽度的一半
      scrollWidth -= this.screenWidth / 2;
      scrollWidth -= currentWidth / 2;
      this.scrollLeft = scrollWidth;
    },
    //滚动左侧
    tabScrollLeft() {
      this.scrollLeft = 0.5;
      setTimeout(() => {
        this.scrollLeft = 0;
      }, 500);
    },
    // 计算导航项宽度
    calculateItemWidth() {
      let widthArr = [];
      let positions = [];
      Promise.all(
        this.tabsData.map((_, index) =>
          new Promise((resolve) => {
            uni
              .createSelectorQuery()
              .in(this)
              .select(`#item-${index}`)
              .boundingClientRect((data) => {
                if (data) {
                  widthArr.push(data.width);
                  positions.push({ left: data.left - this.calcLeft, width: data.width });
                } else {
                  // 兜底默认宽度
                  widthArr.push(100);
                  positions.push({ left: index * 100, width: 100 });
                }
                resolve();
              })
              .exec();
          })
        )
      ).then(() => {
        // 所有节点查询完毕，一次性赋值
        this.widthList = widthArr;
        this.itemPositions = positions;
      });
    },
    // 计算窗口宽度
    calculateWindowWidth() {
      var info = uni.getSystemInfoSync();
      this.screenWidth = info.screenWidth;
    },
    init() {
      const that = this;
      this.calculateWindowWidth();
      setTimeout(function () {
        that.calculateItemWidth();
      }, 1000);
    },
  },
  created() {
    this.init();
  },
};
</script>
<style lang="scss" scoped>
::v-deep.uni-scroll-view::-webkit-scrollbar {
  display: none;
}

.scs-scroll-navbar {
  width: 100%;
  height: 90rpx;
  white-space: nowrap;

  .nav-item {
    height: 100%;
    text-align: center;
    display: inline-block;
    position: relative;
    font-size: 30rpx;
    margin-right: 32rpx;

    &:last-child {
      margin-right: 0;
    }


    .item-title {
      line-height: 90rpx;
      display: inline-block;
      position: relative;
      z-index: 10;
    }
  }

  .act-current {
    // font-size: 40rpx;
    font-weight: bold;
  }

  .nav-underline {
    position: relative;
    height: 12rpx;
    // background: linear-gradient( 90deg, rgba(56,217,125,0.5) 0%, rgba(56,217,125,0) 100%);
    border-radius: 8rpx;
    bottom: 15rpx;
    left: 10px;
    width: 0;
    visibility: visible;
    transition: all 0.3s ease;
    display: flex;
    justify-content: center;
    align-items: center;

    image {
      width: 20px;
      height: 6px;

    }

  }
}
</style>
