<template>
  <div id="app">
    <!-- 顶部菜单栏 -->
    <div v-if="showHeader" class="app-header">
      <router-link to="/">首页</router-link>
      <router-link to="/pages/novel/list">小说列表</router-link>
      <router-link to="/pages/author/apply">作者申请</router-link>
      <router-link to="/pages/search/index">搜索</router-link>
    </div>
    
    <!-- 主内容区 -->
    <router-view v-if="isRouterAlive" />
    
    <!-- 使用自定义TabBar组件 -->
    <CustomTabbar v-if="showTabBar" />
  </div>
</template>

<script>
import CustomTabbar from '@/components/custom-tabbar/index.vue';

export default {
  name: 'App',
  provide() {
    return {
      reload: this.reload
    }
  },
  components: { CustomTabbar },
  data() {
    return {
      // 确保所有属性都在这里定义
      isRouterAlive: true,
      showTabBar: false,
      showHeader: false,
      isMounted: false, // 添加组件挂载状态标志
      tabBarPages: [
        '/pages/index/index',
        '/pages/novel/list',
        '/pages/bookshelf/index',
        '/pages/me/index'
      ],
      hideMenuRoutes: [
        '/login',
        '/register',
        '/forgot-password',
        '/novel/reader'
      ]
    }
  },
  mounted() {
    this.isMounted = true;
    
    // 详细的环境检查
    this.checkEnvironment();
    
    this.checkRouteAuth();
    this.initTheme();
    this.initStoreState();
    this.safeUpdateMenuVisibility();
    
    // 添加全局错误处理
    window.addEventListener('error', (event) => {
      console.error('全局错误捕获:', event.error);
      this.logError(event.error);
    });
    
    window.addEventListener('unhandledrejection', (event) => {
      console.error('未处理的Promise拒绝:', event.reason);
      this.logError(event.reason);
    });
  },
  beforeDestroy() {
    this.isMounted = false;
  },
  watch: {
    // 安全监听路由变化
    '$route': {
      immediate: true,
      handler(newRoute) {
        if (this.isMounted && newRoute && newRoute.path) {
          this.safeUpdateMenuVisibility();
        }
      }
    },
    '$store.state.token': {
      handler(newToken) {
        if (newToken) {
          console.log('检测到新token，重新加载数据');
          this.reloadData();
        }
      },
      immediate: true
    }
  },
  methods: {
    // 环境检查方法
    checkEnvironment() {
      console.log('开始环境检查...');
      
      // 检查uni对象
      if (typeof uni === 'undefined') {
        console.error('uni对象未定义，uni-app环境可能未正确初始化');
        this.injectFallbackUni();
        return;
      }
      
      // 检查uni.navigateTo方法
      if (typeof uni.navigateTo !== 'function') {
        console.error('uni.navigateTo方法不存在');
        this.injectFallbackUni();
        return;
      }
      
      // 检查其他必要的uni API
      const requiredMethods = ['showToast', 'navigateBack', 'redirectTo'];
      requiredMethods.forEach(method => {
        if (typeof uni[method] !== 'function') {
          console.warn(`uni.${method}方法不存在`);
        }
      });
      
      console.log('环境检查完成');
    },
    
    // 注入备用uni对象
    injectFallbackUni() {
      console.log('注入备用uni对象');
      
      // 确保window.uni存在
      if (typeof window !== 'undefined' && typeof window.uni === 'undefined') {
        window.uni = {
          navigateTo: (options) => {
            console.log('备用navigateTo被调用:', options);
            if (options && options.url) {
              // 使用Vue Router进行跳转
              if (this.$router && typeof this.$router.push === 'function') {
                const path = options.url.split('?')[0];
                const query = {};
                
                if (options.url.includes('?')) {
                  const queryString = options.url.split('?')[1];
                  queryString.split('&').forEach(param => {
                    const [key, value] = param.split('=');
                    query[key] = decodeURIComponent(value);
                  });
                }
                
                this.$router.push({
                  path: path,
                  query: query
                });
              } else {
                // 降级到window.location
                window.location.href = options.url;
              }
            }
          },
          showToast: (options) => {
            console.log('备用showToast被调用:', options);
            alert(options.title || '提示信息');
          },
          // 添加其他必要的方法
          navigateBack: () => {
            if (this.$router && typeof this.$router.back === 'function') {
              this.$router.back();
            } else {
              window.history.back();
            }
          },
          redirectTo: (options) => {
            if (options && options.url) {
              if (this.$router && typeof this.$router.replace === 'function') {
                const path = options.url.split('?')[0];
                const query = {};
                
                if (options.url.includes('?')) {
                  const queryString = options.url.split('?')[1];
                  queryString.split('&').forEach(param => {
                    const [key, value] = param.split('=');
                    query[key] = decodeURIComponent(value);
                  });
                }
                
                this.$router.replace({
                  path: path,
                  query: query
                });
              } else {
                window.location.replace(options.url);
              }
            }
          },
          getStorageSync: (key) => {
            return localStorage.getItem(key);
          },
          setStorageSync: (key, value) => {
            localStorage.setItem(key, value);
          }
        };
      }
    },
    
    // 错误日志记录
    logError(error) {
      // 这里可以添加错误上报逻辑
      console.error('记录错误:', error);
      
      // 如果是导航相关错误，尝试修复
      if (error.message && error.message.includes('navigate')) {
        this.injectFallbackUni();
      }
    },
    
    // 平台检测
    checkPlatform() {
      // 检测运行平台
      const platform = this.getPlatform();
      console.log('当前运行平台:', platform);
      
      // 根据不同平台采取不同策略
      if (platform === 'h5') {
        this.initH5Environment();
      } else if (platform === 'weapp') {
        this.initWeappEnvironment();
      } else {
        this.initDefaultEnvironment();
      }
    },
    
    getPlatform() {
      // 判断当前运行环境
      if (typeof wx !== 'undefined' && wx && wx.request) {
        return 'weapp'; // 微信小程序
      } else if (typeof window !== 'undefined' && window.document) {
        return 'h5'; // H5环境
      } else if (typeof plus !== 'undefined') {
        return 'app'; // 5+App环境
      }
      return 'unknown';
    },
    
    initH5Environment() {
      console.log('初始化H5环境');
      // H5环境特定初始化
    },
    
    initWeappEnvironment() {
      console.log('初始化微信小程序环境');
      // 微信小程序环境特定初始化
    },
    
    initDefaultEnvironment() {
      console.log('初始化默认环境');
      // 默认环境初始化
    },
    
    // 确保 initTheme 方法正确定义
    initTheme() {
      console.log('主题初始化开始');
      
      // 设置默认主题
      const themeName = localStorage.getItem('selectedTheme') || 'aydzBlue';
      // 应用主题变量
      const themes = {
        aydzBlue: {
          '--primary-color': '#2a5caa',
          '--bg-color': '#e6f7ff',
          '--text-color': '#1a3353',
          '--card-bg': '#d0e8ff',
          '--header-bg': '#2a5caa'
        },
        default: {
          '--primary-color': '#1890ff',
          '--bg-color': '#f8f9fa',
          '--text-color': '#333',
          '--card-bg': '#ffffff'
        }
      };
      const theme = themes[themeName] || themes.default;
      
      // 应用主题变量
      Object.keys(theme).forEach(key => {
        document.documentElement.style.setProperty(key, theme[key]);
      });
      
      console.log('主题初始化完成');
    },
    
    reload() {
      this.isRouterAlive = false;
      this.$nextTick(() => {
        this.isRouterAlive = true;
        this.safeUpdateMenuVisibility();
      });
    },
    
    safeUpdateMenuVisibility() {
      // 确保组件已挂载且路由对象存在
      if (!this.isMounted || !this.$route || !this.$route.path) return;
      
      const currentPath = this.$route.path;
      
      // 检查是否显示底部TabBar
      this.showTabBar = this.tabBarPages.some(path => 
        currentPath.includes(path) || currentPath === path
      );
      
      // 检查是否显示顶部菜单
      this.showHeader = !this.hideMenuRoutes.some(route => 
        currentPath.includes(route) || currentPath === route
      );
    },
    
    initStoreState() {
      // 使用备用存储方法
      const token = (uni && uni.getStorageSync) ? uni.getStorageSync('token') : localStorage.getItem('token') || '';
      const readingProgress = (uni && uni.getStorageSync) ? uni.getStorageSync('readingProgress') : localStorage.getItem('readingProgress') || 1;
      
      // 确保 store 存在并正确提交
      if (this.$store) {
        this.$store.commit('SET_TOKEN', token);
        this.$store.commit('SET_READING_PROGRESS', readingProgress);
        console.log('Store initialized:', this.$store.state);
      } else {
        console.error('Store is not available!');
      }
    },
    
    checkRouteAuth() {
      // 简单的路由权限检查
      if (!this.$route || !this.$route.path) return;
      
      const authRequiredRoutes = [
        '/pages/author/apply',
        '/pages/bookshelf/index',
        '/pages/me/index'
      ];
      
      if (authRequiredRoutes.some(route => this.$route.path.includes(route))) {
        if (!this.$store.getters.token) {
          // 使用统一的提示方法
          if (uni && uni.showToast) {
            uni.showToast({ title: '请先登录', icon: 'none' });
          } else {
            alert('请先登录');
          }
          
          if (this.$router) {
            this.$router.push('/pages/login');
          } else if (uni && uni.navigateTo) {
            uni.navigateTo({ url: '/pages/login' });
          }
        }
      }
    },
    
    reloadData() {
      // 在需要的地方调用此方法重新加载数据
      if (this.$route.path === '/pages/novel/list') {
        this.$refs.novelList?.initData?.();
      }
    }
  }
}
</script>

<style lang="scss">
@import '@/styles/index.scss';

/* 全局样式修复 */
#app {
  min-height: 100vh;
  background-color: var(--bg-color);
  color: var(--text-color);
}

/* 确保菜单不被其他元素覆盖 */
.custom-tabbar {
  z-index: 99999 !important;
  position: fixed !important;
  bottom: 0 !important;
  left: 0 !important;
  right: 0 !important;
}

/* 修复页面内容被遮挡的问题 */
.page-content {
  padding-bottom: 140rpx !important;
}

/* 确保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;
}

.app-header {
  background: var(--header-bg, #2a5caa);
  padding: 10px;
  display: flex;
  justify-content: space-around;
  position: sticky;
  top: 0;
  z-index: 1000;
  
  a {
    color: white;
    text-decoration: none;
    font-weight: bold;
    
    &.router-link-exact-active {
      color: #ffcc00;
      border-bottom: 2px solid #ffcc00;
    }
  }
}
</style>