<script setup>
import LTitle from "@/components/LTitle.vue";

import throttle from "lodash/throttle";

// 接收 props
const props = defineProps({
    type: {
        type: String,
        default: "purple-pink", // 默认颜色渐变
    },
    tabs: {
        type: Array,
        required: true, // tabs 的选项数组
    },
});

// 当前选中的 tab
const selected = ref(props.tabs[0].value);
const showPopup = ref(false); // 控制弹出层的显示状态
const onSelect = ref(false);
// 根据 type 动态生成分割线的类名
const lineClass = computed(() => {
    switch (props.type) {
        case "blue-green":
            return "bg-gradient-to-r from-blue-400 via-green-500 to-teal-500";
        case "orange-yellow":
            return "bg-gradient-to-r from-orange-400 via-yellow-500 to-yellow-600";
        case "red-purple":
            return "bg-gradient-to-r from-red-500 via-purple-500 to-purple-600";
        default:
            return "bg-gradient-to-r from-purple-400 via-pink-500 to-red-500";
    }
});
const tabWidths = ref([]);
// 计算滑动线的位置和宽度
const slideLineStyle = computed(() => {
    const index = props.tabs.findIndex((tab) => tab.value === selected.value);
    const width = tabWidths.value[index] || 0;
    const offsetLeft = tabWidths.value
        .slice(0, index)
        .reduce((acc, w) => acc + w, 0);
    return {
        width: `${width}px`,
        transform: `translateX(${offsetLeft}px)`,
    };
});

// 获取每个 tab 的宽度
function updateTabWidths() {
    const query = uni.createSelectorQuery();

    props.tabs.forEach((tab) => {
        query.select(`#tab-${tab.value}`).boundingClientRect();
    });

    query.exec((res) => {
        tabWidths.value = res.map((rect) => (rect ? rect.width : 0));
    });
}

function onSelectChange() {
    onSelect.value = true;
    setTimeout(() => {
        onSelect.value = false;
    }, 300);
}

// 获取视口滚动位置的异步函数
function getViewportScrollOffset() {
    return new Promise((resolve) => {
        const query = uni.createSelectorQuery();
        query
            .selectViewport()
            .scrollOffset((viewport) => {
                resolve(viewport);
            })
            .exec();
    });
}

// 获取元素相对视口的位置信息的异步函数
function getElementRect(selector) {
    return new Promise((resolve) => {
        const query = uni.createSelectorQuery();
        query
            .select(selector)
            .boundingClientRect((rect) => {
                resolve(rect);
            })
            .exec();
    });
}

// 主函数：按顺序执行两个查询
async function selectTab(tab) {
    console.log("one selectTab");
    selected.value = tab.value;
    updateTabWidths();
    onSelectChange();

    const offset = 100; // 自定义偏移量

    try {
        // 第一步：获取视口的滚动位置
        const viewport = await getViewportScrollOffset();
        console.log("viewport", viewport);

        // 第二步：获取目标元素的布局信息
        const rect = await getElementRect(`#${tab.value}`);
        console.log("rect", rect);

        const systemInfo = uni.getSystemInfoSync();
        let scrollTop = viewport.scrollTop + rect.top - offset;

        if (process.env.UNI_PLATFORM === "mp-weixin") {
            scrollTop += systemInfo.statusBarHeight || 20; // 微信小程序增加状态栏高度
        } else if (process.env.UNI_PLATFORM === "app-plus") {
            scrollTop += systemInfo.statusBarHeight || 20; // App 端增加状态栏高度
        }

        console.log("目标滚动位置 scrollTop:", scrollTop);

        // 执行滚动到目标位置
        uni.pageScrollTo({
            scrollTop,
            duration: 300,
        });
    } catch (error) {
        console.error("滚动过程中出现错误:", error);
    }
}
// 控制右侧图标按钮点击弹出所有选项的 Popup
function openPopup() {
    showPopup.value = true;
}

function selectFromPopup(tab) {
    selectTab(tab);
    showPopup.value = false;
}

const windowHeight = uni.getSystemInfoSync().windowHeight / 2; // 缓存窗口高度

function onScroll() {
    if (onSelect.value) return;

    const offset = 0;
    const query = uni.createSelectorQuery();

    // 为每个 tab 设置查询请求
    props.tabs.forEach((tab) => {
        query.select(`#${tab.value}`).boundingClientRect();
    });

    query.exec((res) => {
        for (let index = 0; index < res.length; index++) {
            const rect = res[index];
            if (rect && rect.top >= offset && rect.top < windowHeight) {
                if (selected.value !== props.tabs[index].value) {
                    selected.value = props.tabs[index].value;
                    updateTabWidths();
                }
                break; // 找到匹配的 tab 后立即退出循环
            }
        }
    });
}

// 使用节流来减少 onScroll 调用频率
const throttledOnScroll = throttle(onScroll, 100); // 每 100ms 触发一次

onMounted(() => {
    updateTabWidths();

    // #ifdef H5
    window.addEventListener("scroll", onScroll);
    // #endif
});

onUnmounted(() => {
    // #ifdef H5
    window.removeEventListener("scroll", onScroll);
    // #endif
});

// #ifdef MP-WEIXIN || APP-PLUS
onPageScroll(() => {
    throttledOnScroll();
});
// #endif

const scrollTab = computed(() => {
    let index = 0;
    let selectedTab = "";
    for (const i in props.tabs) {
        if (props.tabs[i].value === selected.value) {
            index = Number.parseInt(i);
            break;
        }
    }
    if (index === 1) {
        selectedTab = props.tabs[index - 1].value;
    } else if (index < 2 || index === props.tabs.length) {
        selectedTab = selected.value;
    } else {
        selectedTab = props.tabs[index - 1].value;
    }
    return `tab-${selectedTab}`;
});
</script>

<template>
    <div class="fixed z-1000 bg-white px-8">
        <scroll-view
            :scroll-into-view="scrollTab"
            scroll-x
            :show-scrollbar="false"
        >
            <div class="relative flex">
                <div
                    v-for="(tab, index) in tabs"
                    :id="`tab-${tab.value}`"
                    :key="index"
                    class="h-8 min-w-1/5 shrink-0 cursor-pointer py-1 text-center text-xs font-bold line-height-6 line-height-8 transition-transform duration-200 ease-in-out"
                    :class="{
                        'text-gray-900 ': selected === tab.value,
                        'text-gray-500': selected !== tab.value,
                    }"
                    @click="selectTab(tab)"
                >
                    {{ tab.label }}
                </div>
                <div
                    class="absolute bottom-0 h-1 rounded transition-all duration-300"
                    :style="slideLineStyle"
                    :class="lineClass"
                />
            </div>
        </scroll-view>
        <div
            class="absolute right-0 top-0 h-6 w-8 cursor-pointer bg-white py-2 text-center line-height-6"
            @click="openPopup"
        >
            <wd-icon name="view-list" size="22px" />
        </div>
        <WdPopup v-model="showPopup" position="right" class="w-3/4">
            <view class="pt-20">
                <view
                    v-for="tab in tabs"
                    :key="tab.value"
                    class="p-2 text-xs font-bold"
                    :class="{ 'bg-gray-200 ': selected === tab.value }"
                    @click="selectFromPopup(tab)"
                >
                    {{ tab.label }}
                </view>
            </view>
        </WdPopup>
    </div>
</template>

<style scoped>
.iconfont {
    font-size: 20px;
}
</style>
