<template>
  <view class="find-tabs-wrapper">
    <scroll-view
      class="tabs-scroll"
      scroll-x="true"
      :scroll-left="scrollLeft"
      scroll-with-animation="true"
      @scroll="handleScroll"
    >
      <view class="tabs-list">
        <view
          v-for="(tab, idx) in tabs"
          :key="idx"
          :id="getTabId(idx)"
          class="tab-item"
          :class="{ active: modelValue === idx }"
          @tap="handleSwitch(tab, idx)"
        >
          <view class="tab-content">
            <view class="tab-label">
              <text class="tab-text">{{ tab.tagName }}</text>
              <image v-if="modelValue === idx && (isZhiNian ? indicatorSrcB : indicatorSrc)" :src="isZhiNian ? indicatorSrcB : indicatorSrc" class="tab-indicator" mode="widthFix" />
            </view>
          </view>
        </view>
      </view>
    </scroll-view>
  </view>
</template>

<script setup>
import { getCurrentInstance, nextTick, onMounted, ref, watch } from "vue";
import { isZhiNian } from "@/constant/base";
import indicatorSrc from "./images/selected_tabs_icon.png";
import indicatorSrcB from "./images/selected_tabs_icon_b.png";

const instance = getCurrentInstance();

const props = defineProps({
  modelValue: { type: Number, default: 0 },
  tabs: {
    type: Array,
    default: () => [],
  },
});

const emit = defineEmits(['update:modelValue', 'change']);

const scrollLeft = ref(0);
let currentScrollLeft = 0;

const getTabId = (idx) => `find-tab-${idx}`;

const handleScroll = (e) => {
  currentScrollLeft = e.detail?.scrollLeft || 0;
};

const centerActiveTab = async () => {
  await nextTick();

  const activeIndex = props.modelValue;
  if (activeIndex < 0 || activeIndex >= props.tabs.length) return;
  if (!instance || typeof uni === "undefined" || !uni.createSelectorQuery) return;

  const query = uni.createSelectorQuery().in(instance);
  query.select(".tabs-scroll").boundingClientRect();
  query.select(".tabs-scroll").scrollOffset();
  query.select(`#${getTabId(activeIndex)}`).boundingClientRect();
  query.exec((res) => {
    const [scrollRect, scrollOffset, activeRect] = res || [];
    if (!scrollRect || !activeRect) return;

    const currentLeft = scrollOffset?.scrollLeft ?? currentScrollLeft;
    const targetScrollLeft =
      currentLeft +
      activeRect.left - scrollRect.left -
      (scrollRect.width - activeRect.width) / 2;

    scrollLeft.value = Math.max(0, targetScrollLeft);
  });
};

const handleSwitch = (tab, idx) => {
  emit('update:modelValue', idx);
  emit('change', { tab, idx });
};

watch(
  () => [props.modelValue, props.tabs.length],
  () => {
    centerActiveTab();
  }
);

onMounted(() => {
  centerActiveTab();
});

</script>

<style lang="scss" scoped>
@import "./styles/index.scss";
</style>
