import AdminTabBar from '../../wxcomponents/admin-tabr/admin-tabar'
import UserTabBar from '../../wxcomponents/user-tabar/user-tabar'

export default {
  components: {
    AdminTabBar,
    UserTabBar
  },
  data() {
    return {
      userRole: '',
      isTabBarVisible: true,
      currentPath: '',
      tabBarIndex: 0
    }
  },
  computed: {
    isAdmin() {
      return this.userRole === 'admin'
    },
    shouldShowTabBar() {
      const tabBarPages = [
        '/pages/component/admin_home',
        '/pages/component/role_management',
        '/pages/component/admin_my'
      ]
      return tabBarPages.includes(this.currentPath)
    }
  },
  methods: {
    async checkUserRole() {
      try {
        const userInfo = uni.getStorageSync('userInfo')
        if (userInfo && userInfo.role) {
          this.userRole = userInfo.role
        } else {
          this.userRole = 'user'
        }
      } catch (e) {
        console.error('获取用户角色失败:', e)
        this.userRole = 'user'
      }
    },
    updateCurrentPath() {
      const pages = getCurrentPages()
      if (pages.length > 0) {
        const currentPage = pages[pages.length - 1]
		console.log(currentPage,'text');
        this.currentPath = '/' + currentPage.route
        this.isTabBarVisible = this.shouldShowTabBar
        console.log('当前页面路径:', this.currentPath)
      }
    },
    hideTabBar() {
      this.isTabBarVisible = false
    },
    showTabBar() {
      this.isTabBarVisible = this.shouldShowTabBar
    },
    switchTab(index) {
      const routes = ['pages/index/index', 'pages/role-management/role-management', 'pages/my/my']
      if (!this.isAdmin && index === 1) {
        uni.showToast({
          title: '无权限访问',
          icon: 'none'
        })
        return
      }
      
      this.tabBarIndex = index
      uni.switchTab({
        url: '/' + routes[index]
      })
    }
  },
  onShow() {
    this.checkUserRole()
    this.updateCurrentPath()
    // 获取当前页面路径，设置正确的tabBarIndex
    const pages = getCurrentPages()
    const currentPage = pages[pages.length - 1]
    const route = currentPage.route
    const routes = ['pages/index/index', 'pages/role-management/role-management', 'pages/my/my']
    this.tabBarIndex = routes.findIndex(r => r === route)
  },
  onLoad() {
    this.checkUserRole()
    this.updateCurrentPath()
  },
  mounted() {
    this.checkUserRole()
    this.updateCurrentPath()
  }
} 