<template>
    <view>
        <UTabbar v-if="showTabbar" v-model="current" v-bind="tabbarStyle" :list="tabbarList" :mid-button="hasMidButton"
            @change="handleChange" :hide-tab-bar="hideNativeTabbar"></UTabbar>
        <AppLoading />
        <GlobalPopup />
    </view>
</template>

<script lang="ts" setup>
import { useAppStore } from '@/stores/app'
import { computed, ref, watch, onMounted } from 'vue'
import { onShow } from '@dcloudio/uni-app'
import AppLoading from '@/components/app-loading/app-loading.vue'
import GlobalPopup from '@/components/global-popup/global-popup.vue'
import UTabbar from '@/uni_modules/vk-uview-ui/components/u-tabbar/u-tabbar.vue'

const props = withDefaults(defineProps<{
    forceShow?: boolean
    activePagePath?: string
}>(), {
    forceShow: false,
    activePagePath: ''
})

const current = ref(0)
const appStore = useAppStore()
const showTabbar = ref(false)
const hideNativeTabbar = ref(false)
const nativeTabbar = [
    '/pages/index/index',
    '/pages/match/match',
    '/pages/crypto/crypto',
    '/pages/lottery_analysis/lottery_analysis',
    '/pages/empty/empty',
    '/pages/user/user'
]
const tabbarRouteAliasMap: Record<string, string> = {
    '/pages/match/match': '/packages_match/pages/worldcup',
    '/pages/lottery_analysis/lottery_analysis': '/packages_lottery/pages/index',
    '/pages/empty/empty': '/packages_community/pages/index'
}
const tabbarList = computed(() => {
    return appStore.getTabbarConfig
        ?.filter((item: any) => item.is_show == 1)
        .map((item: any) => {
            const link = typeof item.link === 'string' ? JSON.parse(item.link) : item.link
            return {
                iconPath: item.unselected,
                selectedIconPath: item.selected,
                text: item.name,
                link: link,
                pagePath: link.path,
                midButton: !!link.midButton
            }
        })
})

const hasMidButton = computed(() => {
    return tabbarList.value?.some((item: any) => item.midButton) || false
})

const getPageRoute = (page: any) => {
    let route = page.route || ''
    // H5下route可能带base前缀，需要去除
    // #ifdef H5
    route = route.replace(/^\//, '')
    if (route.startsWith('mobile/')) {
        route = route.replace('mobile/', '')
    }
    // #endif
    return '/' + route
}

const normalizeTabbarRoute = (route?: string) => {
    if (!route) {
        return ''
    }
    return tabbarRouteAliasMap[route] || route
}

const isSameTabbarRoute = (left?: string, right?: string) => {
    return normalizeTabbarRoute(left) === normalizeTabbarRoute(right)
}

const updateTabbarState = () => {
    hideNativeTabbar.value = false
    if (props.forceShow && props.activePagePath) {
        const forceRoute = props.activePagePath
        const idx = tabbarList.value?.findIndex((item: any) => isSameTabbarRoute(item.pagePath, forceRoute)) ?? -1
        showTabbar.value = idx >= 0
        if (idx >= 0) {
            current.value = idx
        }
        return
    }
    const currentPages = getCurrentPages()
    if (!currentPages.length) {
        return
    }
    const currentPage = currentPages[currentPages.length - 1]
    const rawCurrentRoute = getPageRoute(currentPage)
    const currentRoute = normalizeTabbarRoute(rawCurrentRoute)
    hideNativeTabbar.value = nativeTabbar.includes(rawCurrentRoute)
    const idx = tabbarList.value?.findIndex((item: any) => {
        return isSameTabbarRoute(item.pagePath, currentRoute)
    })
    showTabbar.value = idx >= 0
    if (idx >= 0) {
        current.value = idx
    }
}

const syncCurrent = () => {
    updateTabbarState()
    setTimeout(updateTabbarState, 50)
    setTimeout(updateTabbarState, 180)
    setTimeout(updateTabbarState, 360)
}

onMounted(syncCurrent)
onShow(syncCurrent)

watch(() => appStore.tabbarTick, syncCurrent)

// tabbarList 变化（API 加载完成）时主动 bump tick 触发重算
watch(() => tabbarList.value, () => {
    appStore.tabbarTick++
    syncCurrent()
}, { deep: true })

const tabbarStyle = computed(() => ({
    activeColor: appStore.getStyleConfig?.selected_color || '#0b55eb',
    inactiveColor: appStore.getStyleConfig?.default_color || '#999999'
}))
const handleChange = (index: number) => {
    const selectTab = tabbarList.value[index]
    const targetRoute = normalizeTabbarRoute(selectTab?.pagePath)
    console.log('[Tabbar] 切换tab:', index, selectTab?.text, selectTab?.pagePath, '=>', targetRoute)
    if (!targetRoute) {
        return
    }
    // 防止重复跳转当前页面
    const currentPages = getCurrentPages()
    if (currentPages.length) {
        const curRoute = getPageRoute(currentPages[currentPages.length - 1])
        if (isSameTabbarRoute(curRoute, targetRoute)) return
    }
    if (selectTab.midButton) {
        uni.navigateTo({ url: targetRoute })
        return
    }
    if (nativeTabbar.includes(targetRoute)) {
        uni.switchTab({ url: targetRoute })
    } else {
        uni.reLaunch({ url: targetRoute })
    }
}
</script>
