<template>
  <view class="app-container">
    <router-view />
    <!-- 若依风格自定义菜单 -->
    <view v-if="showMenu" class="ruoyi-tabbar">
      <view 
        v-for="(item, index) in menuItems" 
        :key="index"
        class="tab-item"
        :class="{ active: activeIndex === index }"
        @click="switchTab(item, index)"
      >
        <image class="icon" :src="activeIndex === index ? item.activeIcon : item.icon" />
        <text class="text">{{ item.text }}</text>
      </view>
    </view>
  </view>
</template>

<script>
import CustomTabbar from '@/components/custom-tabbar/index.vue'
import config from './config'
import { getToken } from '@/utils/auth'

export default {
  components: { CustomTabbar },
  data() {
    return {
      activeIndex: 0,
      showMenu: true,
      menuItems: [
        {
          path: '/pages/index/index',
          icon: '/static/tabbar/home.png',
          activeIcon: '/static/tabbar/home_selected.png',
          text: '首页'
        },
        {
          path: '/pages/novel/list',
          icon: '/static/tabbar/novel.png',
          activeIcon: '/static/tabbar/novel_selected.png',
          text: '小说'
        },
        {
          path: '/pages/bookshelf/index',
          icon: '/static/tabbar/bookshelf.png',
          activeIcon: '/static/tabbar/bookshelf_selected.png',
          text: '书架'
        },
        {
          path: '/pages/me/index',
          icon: '/static/tabbar/mine.png',
          activeIcon: '/static/tabbar/mine_selected.png',
          text: '我的'
        }
      ]
    }
  },
  watch: {
    '$route.path': {
      immediate: true,
      handler(path) {
        // 确定当前激活的菜单项
        this.activeIndex = this.menuItems.findIndex(item => 
          path.startsWith(item.path)
        );
        
        // 决定是否显示菜单
        this.showMenu = this.activeIndex !== -1;
      }
    }
  },
  methods: {
    switchTab(item, index) {
      if (this.activeIndex === index) return;
      
      this.activeIndex = index;
      uni.switchTab({
        url: item.path
      });
    }
  },
  onLaunch() {
    // 初始化主题
    this.initTheme()
    
    // 检查阅读进度
    this.checkReadingProgress()
    
    // 初始化 store 状态
    this.initStoreState()
    // 检查登录状态
    //this.checkLogin()
      console.log('App launched, store:', this.$store)


  },
  onShow() {
    // 检查云端阅读进度
    if (this.$store.getters.token) {
      this.syncReadingProgress()
    }
  },
  methods: {
    // 初始化 store 状态
    initStoreState() {
      // 从本地存储恢复状态
      const token = uni.getStorageSync('token')
      const readingProgress = uni.getStorageSync('readingProgress') || 1
      
      // 提交到 store
      this.$store.commit('SET_TOKEN', token)
      this.$store.commit('SET_READING_PROGRESS', readingProgress)
    },
    // 检查阅读进度
    checkReadingProgress() {
      // 直接从本地存储读取
      const chapter = uni.getStorageSync('readingProgress') || 1
      
      if (chapter > 5 && !uni.getStorageSync('token')) {
        uni.showModal({
          title: '登录提示',
          content: `您已阅读到第${chapter}章，登录后继续阅读`,
          confirmText: '立即登录',
          success: (res) => {
            if (res.confirm) {
              uni.navigateTo({ url: '/pages/login' })
            }
          }
        })
      }
    },
    // 同步阅读进度 (修改后)
    async syncReadingProgress() {
      try {
        // 安全访问 store
        if (!this.$store) {
          console.warn('Store 未初始化，无法同步阅读进度')
          return
        }
        
        const token = this.$store.getters.token
        if (!token) {
          console.log('用户未登录，跳过同步')
          return
        }
        
        // 从本地存储获取进度
        const localChapter = uni.getStorageSync('readingProgress') || 1
        
        // 调用 API 同步
        const res = await this.$api.saveReadingProgress(localChapter)
        console.log('进度同步成功:', res.data)
      } catch (err) {
        console.error('同步阅读进度失败', err)
      }
    },
    // 添加 checkLogin 方法
    // checkLogin() {
    //   // 这里写登录检查逻辑
    //   // 示例：检查本地存储的登录状态
    //   const isLoggedIn = uni.getStorageSync('isLogin');
    //   if (!isLoggedIn) {
    //     uni.navigateTo({ url: '/pages/login' });
    //   }
    // },
    
    // 临时主题初始化
    initTheme() {
      const themeName = uni.getStorageSync('selectedTheme') || 'aydzBlue'
      
      // 应用主题变量
      const themes = {
        aydzBlue: {
          '--primary-color': '#2a5caa',
          '--bg-color': '#e6f7ff',
          '--text-color': '#1a3353',
          '--card-bg': '#d0e8ff',
          '--header-bg': '#2a5caa'
        },
        darkMode: {
          '--primary-color': '#52c41a',
          '--bg-color': '#1a1a1a',
          '--text-color': '#e6e6e6',
          '--card-bg': '#2a2a2a'
        },
        default: {
          '--primary-color': '#1890ff',
          '--bg-color': '#f8f9fa',
          '--text-color': '#333',
          '--card-bg': '#ffffff'
        }
      }
      
      const root = document.documentElement
      const themeVars = themes[themeName] || themes.aydzBlue
      
      Object.keys(themeVars).forEach(key => {
        root.style.setProperty(key, themeVars[key])
      })
      
      // 动态设置导航栏颜色
      if (themeName === 'darkMode') {
        uni.setNavigationBarColor({
          frontColor: '#ffffff',
          backgroundColor: '#1a1a1a'
        })
      } else if (themeName === 'aydzBlue') {
        uni.setNavigationBarColor({
          frontColor: '#ffffff',
          backgroundColor: '#2a5caa'
        })
      }
    }
  }
}
</script>

<style lang="scss">
/* 确保自定义TabBar有足够的空间 */
.app-container {
  padding-bottom: 100rpx;
}
.ruoyi-tabbar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  display: flex;
  height: 100rpx;
  background-color: #fff;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.1);
  z-index: 9999;
  border-top: 1rpx solid #eee;
  
  .tab-item {
    flex: 1;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    
    .icon {
      width: 44rpx;
      height: 44rpx;
      margin-bottom: 6rpx;
    }
    
    .text {
      font-size: 22rpx;
      color: #666;
    }
        .active .text {
          color: #3a8ee6; /* 若依主题蓝色 */
          font-weight: 500;
        }  
	}
}
/* 确保tabbar显示 */
uni-tabbar {
  display: flex !important;
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  z-index: 9999;
  background-color: #fff;
  box-shadow: 0 -2px 10px rgba(0,0,0,0.1);
}

/* 修复高度问题 */
uni-tabbar .uni-tabbar {
  height: 50px !important;
}

/* 页面内容区域 */
.page-content {
  padding-bottom: 60px !important;
}
/* 保留原有样式 */
uni-tabbar {
  z-index: 999;
}
</style>