<template>
  <view class="novel-list-page">
    <!-- 加载状态 -->
    <view v-if="loading" class="loading-container">
      <uni-icons type="spinner-cycle" size="36" color="var(--primary-color)" class="loading-icon" />
      <text>加载中...</text>
    </view>
    
    <!-- 内容区域 -->
    <template v-else>
      <!-- 顶部广告 -->
      <ad-banner v-if="topAds.length" :ads="topAds" />
      
      <!-- 顶部分类导航 -->
      <scroll-view scroll-x class="category-nav">
        <view 
          v-for="category in categories" 
          :key="category.id"
          class="category-item"
          :class="{ active: activeCategory === category.id }"
          @click="changeCategory(category.id)"
        >
          {{ category.name }}
        </view>
      </scroll-view>
      
      <!-- 空状态 -->
      <view v-if="novels.length === 0 && !error" class="empty-container">
        <image src="/static/empty-book.png" class="empty-img" />
        <text class="empty-text">暂无小说数据</text>
		<button class="btn-refresh" @click="reloadData">重新加载</button>
      </view>
      
      <!-- 错误状态 -->
      <view v-if="error" class="error-container">
        <uni-icons type="info" size="48" color="var(--error-color)" />
        <text class="error-text">{{ error }}</text>
        <button class="btn-refresh" @click="loadNovels">重新加载</button>
      </view>
      
      <!-- 热门推荐 -->
      <view v-if="hotNovels.length > 0" class="section">
    <!-- ... -->
  </view>
  <view v-else class="section">
        <view class="section-header">
      <text class="section-title">热门推荐（演示数据）</text>
          <text class="section-more" @click="goMore">更多 ></text>
        </view>
        <scroll-view scroll-x class="hot-list">
          <view 
        v-for="novel in demoHotNovels" 
            :key="novel.id" 
            class="hot-item"
            @click="openNovel(novel)"
          >
        <image :src="novel.cover" class="hot-cover" />
            <text class="hot-title">{{ novel.title }}</text>
          </view>
        </scroll-view>
      </view>
      
      <!-- 分类小说列表 -->
      <view v-if="novels.length > 0" class="section">
    <!-- ... -->
  </view>
  <view v-else class="section">
        <view class="section-header">
      <text class="section-title">小说列表（演示数据）</text>
        </view>
        <view class="novel-grid">
          <view 
        v-for="novel in demoNovels" 
        :key="novel.id" 
            class="novel-item"
            @click="openNovel(novel)"
          >
        <image :src="novel.cover" class="novel-cover" />
        <text class="novel-title">{{ novel.title }}</text>
        <text class="novel-author">{{ novel.author }}</text>
          </view>
        </view>
      </view>
      
      <!-- 成为签约作家按钮 -->
      <view class="become-author" @click="applyAuthor">
        <text>成为签约作家，发布你的作品</text>
      </view>
      
      <!-- 底部广告 -->
      <ad-banner v-if="bottomAds.length" :ads="bottomAds" />
    </template>
  </view>
</template>

<script>
// 确保路径正确
import AdBanner from '@/components/AdBanner';
import urls from '@/api/urls';

export default {
  components: { AdBanner },
  data() {
    return {
      topAds: [],
      bottomAds: [],
      categories: [],
      activeCategory: 0,
      hotNovels: [],
      novels: [],
      loading: true,
      error: null,
      currentCategoryName: '全部',
      
      // 临时解决方案 - 模拟数据
      mockHotNovels: [
        { id: 1, title: '总裁的替身前妻', cover: '/static/demo-cover1.jpg' },
        { id: 2, title: '神医毒妃', cover: '/static/demo-cover2.jpg' },
        { id: 3, title: '穿越之王妃逆袭', cover: '/static/demo-cover3.jpg' }
      ],
      mockNovels: [
        { id: 4, title: '都市最强赘婿', author: '网络作家', cover: '/static/demo-cover4.jpg' },
        { id: 5, title: '修仙归来', author: '仙侠迷', cover: '/static/demo-cover5.jpg' },
        { id: 6, title: '校园纯爱物语', author: '青春校园', cover: '/static/demo-cover6.jpg' }
      ]
    }
  },
  mounted() {
    console.log('$http available in component:', typeof this.$http.get === 'function');
    
    // 确保所有方法都已绑定
    console.log('loadCategories:', typeof this.loadCategories);
    console.log('loadHotNovels:', typeof this.loadHotNovels);
    console.log('loadNovels:', typeof this.loadNovels);
    console.log('loadAds:', typeof this.loadAds);
    
    this.initData();
  },
  methods: {
    async initData() {
      // 确保所有方法都已绑定
      if (
        typeof this.loadCategories !== 'function' ||
        typeof this.loadHotNovels !== 'function' ||
        typeof this.loadNovels !== 'function' ||
        typeof this.loadAds !== 'function'
      ) {
        console.error('一个或多个方法未绑定!');
        this.error = '系统初始化失败，请刷新页面';
        this.loading = false;
        return;
      }
      
      try {
        // 顺序加载数据
        await this.loadCategories();
        await this.loadHotNovels();
        await this.loadNovels();
        await this.loadAds();
      } catch (e) {
        console.error('初始化失败', e);
        this.error = '初始化失败，请检查网络连接';
      } finally {
        this.loading = false;
      }
    },
        // 加载分类
    async loadCategories() {
      try {
    // 使用正确的参数格式
    const res = await this.$http.get('/category/tree', {
      header: { isToken: false }
              });
        this.categories = res && res.data ? [{ id: 0, name: '全部' }, ...res.data] : [];
      } catch (e) {
        console.error('加载分类失败', e);
        this.categories = [{ id: 0, name: '全部' }];
      }
    },
    // 加载热门小说
    async loadHotNovels() {
      try {
      // 公开API，不需要认证
    const res = await this.$http.get('/novel/hot', {
      header: { isToken: false }
      });
        // 处理响应
        if (res && res.data && res.data.rows) {
          this.hotNovels = res.data.rows;
        } else if (res && res.data && Array.isArray(res.data)) {
          this.hotNovels = res.data;
        } else {
          console.warn('热门小说API返回格式未知', res);
          this.hotNovels = this.mockHotNovels;
        }
      } catch (e) {
        console.error('加载热门小说失败', e);
        this.hotNovels = this.mockHotNovels;
      }
    },
    // 加载小说列表
    async loadNovels() {
      this.loading = true;
      this.error = null;
      try {
        // 使用正确的请求方式
        //const res = await this.$http.get('/novel/list');
    const res = await this.$http.get('/novel/list', {
      header: { isToken: false }
        });
        
        // 修复可选链操作符问题
        if (res && res.data && res.data.rows) {
          this.novels = res.data.rows;
        } else if (res && res.data && Array.isArray(res.data)) {
          this.novels = res.data;
        } else {
          console.warn('小说列表API返回格式未知', res);
          this.novels = this.mockNovels;
        }
      } catch (e) {
        console.error('加载小说失败', e);
        this.error = '加载失败，请重试';
        this.novels = this.mockNovels;
      } finally {
        this.loading = false;
      }
    },
    
    // 加载广告
    async loadAds() {
      try {
        const [topRes, bottomRes] = await Promise.all([
      this.$http.get('/ad/position?code=TOP_BANNER', {
        header: { isToken: false }
      }),
      this.$http.get('/ad/position?code=BOTTOM_BANNER', {
        header: { isToken: false }
      })
        ]);
        
        this.topAds = topRes && topRes.data ? topRes.data : [];
        this.bottomAds = bottomRes && bottomRes.data ? bottomRes.data : [];
      } catch (e) {
        console.error('加载广告失败', e);
      }
    },
    // 封面URL处理
    getCoverUrl(cover) {
      if (!cover) return '/static/default-cover.jpg';
      if (cover.startsWith('http')) return cover;
      if (cover.startsWith('/')) return cover;
      return `${process.env.VUE_APP_BASE_URL || ''}/uploads/${cover}`;
    },
    
    // 其他方法...
    changeCategory(categoryId) {
      this.activeCategory = categoryId;
      this.currentCategoryName = this.categories.find(c => c.id === categoryId)?.name || '全部';
      this.loadNovels();
    },
    
    openNovel(novel) {
      if (novel.id) {
        uni.navigateTo({
          url: `/pages/novel/detail?id=${novel.id}`
        });
      } else {
        uni.showToast({
          title: '小说ID不存在',
          icon: 'none'
        });
      }
    },
    
    applyAuthor() {
      if (!this.$store.getters.token) {
        uni.showToast({ title: '请先登录', icon: 'none' });
        uni.navigateTo({ url: '/pages/login' });
        return;
      }
      uni.navigateTo({ url: '/pages/author/apply' });
    },

    goMore() {
      uni.navigateTo({
        url: '/pages/novel/more'
      });
    },
        // 确保重新加载按钮绑定到正确的方法
    reloadData() {
      this.initData();
    }
  }
}
</script>

<style scoped>
/* 添加加载状态样式 */
.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 100rpx 0;
}

.loading-icon {
  animation: rotate 1s linear infinite;
  margin-bottom: 20rpx;
}

@keyframes rotate {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

/* 添加空状态样式 */
.empty-container, .error-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 100rpx 0;
  text-align: center;
}

.empty-img {
  width: 200rpx;
  height: 200rpx;
  opacity: 0.6;
  margin-bottom: 40rpx;
}

.empty-text, .error-text {
  font-size: 32rpx;
  color: var(--text-color);
  margin-bottom: 40rpx;
}

.error-text {
  color: var(--error-color);
}

.btn-refresh {
  background-color: var(--primary-color);
  color: white;
  width: 60%;
  border-radius: 50rpx;
}

/* 确保网格布局正确 */
.novel-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 20rpx;
  padding: 20rpx;
}

.novel-item {
  background-color: var(--card-bg);
  border-radius: 12rpx;
  overflow: hidden;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
}

.novel-cover {
  width: 100%;
  height: 300rpx;
  background-color: #f5f5f5; /* 添加默认背景 */
}

.novel-title {
  display: block;
  font-size: 28rpx;
  padding: 10rpx 15rpx;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.novel-author {
  display: block;
  font-size: 24rpx;
  color: #888;
  padding: 0 15rpx 15rpx;
}
</style>
