<template>
    <view class="tabbar_container">
        <view class="tabbar_item" v-for="(item, index) in tabbarList" :key="index" @click="changeItem(item)">
            <view
                class="item-top"
                :class="[
                    item.centerItem ? 'center-item-img ' : '',
                    item.centerItem && currentItem === item.id ? 'rubberBand animated' : '',
                ]"
            >
                <image :src="currentItem == item.id ? item.selectedIconPath : item.iconPath"></image>
            </view>
            <view class="badge" v-if="item.badge && item.badge > 0">{{ item.badge }}</view>
            <view class="item-bottom" :class="[currentItem == item.id ? 'item-active' : '']">
                <text>{{ item.text }}</text>
            </view>
        </view>
    </view>
</template>

<script setup>
import { ref, onMounted, computed, watch, nextTick } from 'vue';
import { useReadMsg } from '@/stores/useReadMsg';
import { storeToRefs } from 'pinia';
import useUserStore from '@/stores/useUserStore';

const props = defineProps({
    currentpage: {
        type: Number,
        required: true,
        default: 0,
    },
});

const readMsg = useReadMsg();
const { userInfo } = storeToRefs(useUserStore());
const currentItem = ref(0);

// 监听用户类型变化，重新生成tabbar配置
watch(() => userInfo.value?.isCompanyUser, (newIsCompanyUser, oldIsCompanyUser) => {
    console.log('midell-box用户类型变化监听:', { newIsCompanyUser, oldIsCompanyUser, userInfo: userInfo.value });
    if (newIsCompanyUser !== oldIsCompanyUser) {
        console.log('用户类型发生变化，重新生成tabbar:', newIsCompanyUser);
        // tabbarList是computed，会自动重新计算
        // 强制触发响应式更新
        nextTick(() => {
            console.log('tabbar配置已更新:', tabbarList.value);
        });
    }
}, { immediate: true });

// 监听用户信息变化（包括登录状态）
watch(() => userInfo.value, (newUserInfo, oldUserInfo) => {
    console.log('midell-box用户信息变化监听:', { newUserInfo, oldUserInfo });
    if (newUserInfo !== oldUserInfo) {
        console.log('用户信息发生变化，重新生成tabbar');
        // 强制触发响应式更新
        nextTick(() => {
            console.log('tabbar配置已更新:', tabbarList.value);
        });
    }
}, { immediate: true, deep: true });

// 生成tabbar配置的函数
const generateTabbarList = () => {
    const baseItems = [
        {
            id: 0,
            text: '职位2',
            path: '/pages/index/index',
            iconPath: '../../static/tabbar/calendar.png',
            selectedIconPath: '../../static/tabbar/calendared.png',
            centerItem: false,
            badge: readMsg.badges[0]?.count || 0,
        },
        {
            id: 2,
            text: 'AI+',
            path: '/packageA/pages/chat/chat',
            iconPath: '../../static/tabbar/logo3.png',
            selectedIconPath: '../../static/tabbar/logo3.png',
            centerItem: true,
            badge: readMsg.badges[2]?.count || 0,
        },
        {
            id: 3,
            text: '消息2',
            path: '/pages/msglog/msglog',
            iconPath: '../../static/tabbar/chat4.png',
            selectedIconPath: '../../static/tabbar/chat4ed.png',
            centerItem: false,
            badge: readMsg.badges[3]?.count || 0,
        },
        {
            id: 4,
            text: '我的',
            path: '/pages/mine/mine',
            iconPath: '../../static/tabbar/mine.png',
            selectedIconPath: '../../static/tabbar/mined.png',
            centerItem: false,
            badge: readMsg.badges[4]?.count || 0,
        },
    ];

    // 根据用户类型添加不同的导航项，未登录时默认为求职者
    const userType = userInfo.value?.isCompanyUser !== undefined ? userInfo.value.isCompanyUser : 1;
    
    if (userType === 0) {
        // 企业用户：显示发布岗位，隐藏招聘会
        baseItems.splice(1, 0, {
            id: 1,
            text: '发布岗位',
            path: '/packageA/pages/job/publishJob',
            iconPath: '../../static/tabbar/post.png',
            selectedIconPath: '../../static/tabbar/posted.png',
            centerItem: false,
            badge: 0,
        });
    } else {
        // 求职者用户（包括未登录状态）：显示招聘会
        baseItems.splice(1, 0, {
            id: 1,
            text: '招聘会',
            path: '/packageA/pages/careerfair/careerfair',
            iconPath: '../../static/tabbar/post.png',
            selectedIconPath: '../../static/tabbar/posted.png',
            centerItem: false,
            badge: readMsg.badges[1]?.count || 0,
        });
    }

    return baseItems;
};

// 根据用户类型生成不同的导航栏配置
const tabbarList = computed(() => {
    return generateTabbarList();
});

onMounted(() => {
    // 自定义TabBar不需要调用hideTabBar，因为已经在pages.json中设置了custom: true
    // uni.hideTabBar(); // 移除这行，避免在自定义TabBar模式下调用
    currentItem.value = props.currentpage;
});

const changeItem = (item) => {
    // 判断是否为 TabBar 页面
    const tabBarPages = [
        '/pages/index/index',
        '/packageA/pages/careerfair/careerfair', 
        '/packageA/pages/chat/chat',
        '/pages/msglog/msglog',
        '/pages/mine/mine'
    ];
    
    if (tabBarPages.includes(item.path)) {
        // TabBar 页面使用 redirectTo 避免页面栈溢出
        uni.redirectTo({
            url: item.path,
        });
    } else {
        // 非 TabBar 页面使用 navigateTo
        uni.navigateTo({
            url: item.path,
        });
    }
};
</script>

<style lang="scss" scoped>
.badge {
    position: absolute;
    top: 4rpx;
    right: 20rpx;
    min-width: 30rpx;
    height: 30rpx;
    background-color: red;
    color: #fff;
    font-size: 18rpx;
    border-radius: 15rpx;
    text-align: center;
    line-height: 30rpx;
    padding: 0 10rpx;
}
.tabbar_container {
    background-color: #ffffff;
    width: 100%;
    height: 88rpx;
    display: flex;
    align-items: center;
    padding: 5rpx 0;
    overflow: hidden;
    // position: fixed;
    // bottom: 0rpx;
    // left: 0rpx;
    // box-shadow: 0 0 5px #999;
    // padding-bottom: env(safe-area-inset-bottom);
    // z-index: 998;
    .tabbar_item {
        width: 33.33%;
        height: 100rpx;
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        text-align: center;
        position: relative;
        color: #5e5f60;
        .item-top {
            width: 44.44rpx;
            height: 44.44rpx;
            image {
                width: 100%;
                height: 100%;
            }
        }
        .item-bottom {
            font-weight: 500;
            font-size: 22rpx;
        }
    }
}
.center-item-img {
    // position: absolute;
    // top: 0rpx;
    // left: 50%;
    // transform: translate(-50%, 0);
    width: 108rpx !important;
    height: 98rpx !important;
}
.item-active {
    color: #256bfa;
}
</style>
