<template>
    <view class="custom-tabbar">
        <view v-for="(item, index) in visibleTabList" :key="index" class="tab-item" @click="handleTabClick(index)">
            <view class="tab-icon-container">
                <image class="tab-icon" :src="currentVisibleIndex == index ? item.selectedIconPath : item.iconPath" mode="aspectFit"></image>
                <view v-if="item.badge != null && item.badge > 0" class="badge">
                    <text class="badge-text">{{ item.badge }}</text>
                </view>
            </view>
            <text :class="['tab-text', currentVisibleIndex == index ? 'tab-text-active' : '']">
                {{ item.text }}
            </text>
        </view>
    </view>
</template>

<script setup lang="uts">
    import { ref, computed, onMounted, onBeforeUnmount } from 'vue'
    import { getMessageList } from '../../api/message/index'

    // Props
    type Props = {
        current?: number
		hide0:number
		hide1:number
		hide2:number
		hide3:number
    }

    const props = withDefaults(defineProps<Props>(), {
        current: 0,
		hide0:1,
		hide1:1,
		hide2:1,
		hide3:1
    })

    // Tab 列表配置
    type TabItem = {
        pagePath: string
        text: string
        iconPath: string
        selectedIconPath: string
        badge?: number
    }

    const tabList = ref<TabItem[]>([
        {
            pagePath: '/pages/index/index',
            text: '首页',
            iconPath: '/static/images/custom-tabbar/11.png',
            selectedIconPath: '/static/images/custom-tabbar/22.png'
        },
        {
            pagePath: '/pages/workspace/index',
            text: '工作台',
            iconPath: '/static/images/custom-tabbar/33.png',
            selectedIconPath: '/static/images/custom-tabbar/44.png'
        },
		{
		    pagePath: '/pages/message/index',
		    text: '消息',
		    iconPath: '/static/images/custom-tabbar/77.png',
		    selectedIconPath: '/static/images/custom-tabbar/88.png',
		    badge: 0
		},
		{
		    pagePath: '/pages/profile/index',
		    text: '我的',
		    iconPath: '/static/images/custom-tabbar/55.png',
		    selectedIconPath: '/static/images/custom-tabbar/66.png'
		}
    ])
	
	// 计算可见的 tab 列表
    const visibleTabList = computed<TabItem[]>(() => {
        const hideValues = [props.hide0, props.hide1, props.hide2, props.hide3]
        return tabList.value.filter((item: TabItem, index: number) => {
            return index < hideValues.length && hideValues[index] === 1
        })
    })

    // 计算当前选中项在可见列表中的索引
    const currentVisibleIndex = computed<number>(() => {
        const hideValues = [props.hide0, props.hide1, props.hide2, props.hide3]
        let visibleIndex = 0
        
        for (let i = 0; i < props.current; i++) {
            // 如果前面的 tab 是可见的，则可见索引增加
            if (i < hideValues.length && hideValues[i] === 1) {
                visibleIndex++
            }
        }
        
        // 检查当前 tab 是否可见
        if (props.current >= hideValues.length || hideValues[props.current] !== 1) {
            // 如果当前 tab 不可见，返回第一个可见的 tab 索引
            return 0
        }
        
        return visibleIndex
    })

    // 定时器
    let refreshTimer: number | null = null

    // 获取未读消息数量
    const getUnreadMessageCount = async (): Promise<void> => {
        try {
            const result = await getMessageList(1, 1, '', 'UNREAD')
            const resultObj = result as UTSJSONObject
            const total = resultObj['total'] as number
            
            // 更新消息标签的徽章
            const messageTabIndex = tabList.value.findIndex(item => item.pagePath === '/pages/message/index')
            if (messageTabIndex !== -1) {
                tabList.value[messageTabIndex].badge = total
            }
        } catch (e) {
            console.error('获取未读消息数量失败:', e)
        }
    }

    // 启动定时器
    const startRefreshTimer = (): void => {
        // 每30秒更新一次未读消息数量
        refreshTimer = setInterval(() => {
            getUnreadMessageCount()
        }, 30000)
    }

    // 停止定时器
    const stopRefreshTimer = (): void => {
        if (refreshTimer != null) {
            clearInterval(refreshTimer as number)
            refreshTimer = null
        }
    }

    // Tab 点击事件
    const handleTabClick = (index: number): void => {
        // 将可见索引转换回原始索引
        const hideValues = [props.hide0, props.hide1, props.hide2, props.hide3]
        let originalIndex = 0
        let visibleCount = 0
        
        for (let i = 0; i < tabList.value.length; i++) {
            if (i < hideValues.length && hideValues[i] === 1) {
                if (visibleCount === index) {
                    originalIndex = i
                    break
                }
                visibleCount++
            }
        }
        
        if (originalIndex == props.current) {
            return
        }
        
        const item = tabList.value[originalIndex]
        uni.redirectTo({
            url: item.pagePath
        })
    }
	// 监听登录状态变化
	const onAuthStateChange = (res: UTSJSONObject): void => {
	    if (res != null && res['isLoggedIn'] === false) {
	        stopRefreshTimer()
	    } else if (res != null && res['isLoggedIn'] === true) {
	        // 重新登录后重新启动timer
	        startRefreshTimer()
	        getUnreadMessageCount()
	    }
	}

    // 组件挂载时
    onMounted(() => {
        // 初始获取未读消息数量
        getUnreadMessageCount()
        // 启动定时更新
        startRefreshTimer()
        // 监听未读消息数量更新事件
        uni.$on('updateUnreadCount', getUnreadMessageCount)
        // 监听登录状态变化，清除timer
        uni.$on('onAuthStateChange', onAuthStateChange)
    })

    // 组件卸载时
    onBeforeUnmount(() => {
        // 停止定时器
        stopRefreshTimer()
        // 移除事件监听
        uni.$off('updateUnreadCount', getUnreadMessageCount)
        uni.$off('onAuthStateChange', onAuthStateChange)
    })
</script>

<style lang="scss">
    .custom-tabbar {
        position: fixed;
        bottom: 0;
        left: 0;
        right: 0;
        z-index: 1000;
        height: 150rpx;
        background-color: #ffffff;
        border-top: 1rpx solid #e5e5e5;
        flex-direction: row;
        justify-content: space-around;
        align-items: center;
        padding-bottom: env(safe-area-inset-bottom);
    }

    .tab {
        &-item {
            flex: 1;
            justify-content: center;
            align-items: center;
        }

        &-icon-container {
            position: relative;
            display: flex;
            align-items: center;
            justify-content: flex-start;
            margin-bottom: 8rpx;
            width: 80rpx;
            height: 70rpx;
            padding-left: 10rpx;
        }

        &-icon {
            width: 48rpx;
            height: 48rpx;
        }

        &-text {
            font-size: 24rpx;
            color: #666666;

            &-active {
                color: #0081ff;
            }
        }
    }

    .badge {
        position: absolute;
        top: 0rpx;
        right: 0rpx;
        min-width: 36rpx;
        height: 36rpx;
        background-color: #ff3b30;
        border-radius: 18rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        padding: 0 10rpx;
        z-index: 1;

        .badge-text {
            font-size: 20rpx;
            color: #ffffff;
            font-weight: bold;
        }
    }
</style>