<template>
    <u-tabbar v-if="showTabbar" v-model="current" v-bind="tabbarStyle" :list="tabbarList" @change="handleChange"
        :hide-tab-bar="true"></u-tabbar>
</template>

<script lang="ts" setup>
import { useAppStore } from '@/stores/app'
import { useNavigationBarTitleStore } from '@/stores/navigationBarTitle'
import { navigateTo } from '@/utils/util'
import { computed, ref, watch } from 'vue'
const current = ref()
const appStore = useAppStore()
const navigationBarTitleStore = useNavigationBarTitleStore()
const tabbarList = computed(() => {
    return (
        appStore.getTabbarConfig.list
            ?.filter((item: any) => item.is_show == '1')
            .map((item: any) => {
                const link = item.link
                return {
                    iconPath: appStore.getImageUrl(item.unselected),
                    selectedIconPath: appStore.getImageUrl(item.selected),
                    text: item.name,
                    link,
                    pagePath: link.path
                }
            }) || []
    )
})

// 原生菜单列表
const nativeTabList = [
    '/pages/index/index',
    '/pages/ai_creation/ai_creation',
    '/pages/skills/skills',
    '/pages/app/app',
    '/pages/user/user'
]

const getCurrentIndex = () => {
    const currentPages = getCurrentPages()
    const currentPage = currentPages[currentPages.length - 1]
    const current = tabbarList.value.findIndex((item: any) => {
        return item.pagePath === '/' + currentPage.route
    })
    return current
}
const showTabbar = computed(() => {
    const currentPages = getCurrentPages()
    const currentPage = currentPages[currentPages.length - 1]
    const current = tabbarList.value.findIndex((item: any) => {
        return item.pagePath === '/' + currentPage.route
    })
    return current >= 0
})
const tabbarStyle = computed(() => ({
    activeColor: appStore.getTabbarConfig?.style?.selected_color,
    inactiveColor: appStore.getTabbarConfig?.style?.default_color
}))
const handleChange = (index: number) => {
    const selectTab = tabbarList.value[index]
    selectTab.link.name = selectTab.text
    const navigateType = nativeTabList.includes(selectTab.pagePath)
        ? 'switchTab'
        : 'reLaunch'
    navigateTo(selectTab.link, false, navigateType)
}

watch(
    tabbarList,
    () => {
        const current = getCurrentIndex()
        if (current >= 0) {
            const currentTab = tabbarList.value[current]
            navigationBarTitleStore.add({
                path: currentTab.pagePath,
                title: currentTab.text
            })
            navigationBarTitleStore.setTitle()
        }
    },
    {
        immediate: true
    }
)
</script>
