<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="showEmptyState" 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 && !showNovels" 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="showHotNovels" 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 displayedHotNovels" 
            :key="novel.id" 
            class="hot-item"
            @click="openNovel(novel)"
          >
            <image 
              :src="getCoverUrl(novel.coverImg)" 
              class="hot-cover"
              @error="handleImageError"
            />
            <text class="hot-title">{{ novel.title }}</text>
          </view>
        </scroll-view>
      </view>
      
      <!-- 小说列表 -->
      <view v-if="showNovels" class="section">
        <view class="section-header">
          <text class="section-title">小说列表</text>
        </view>
        <view class="novel-grid">
          <view 
            v-for="novel in displayedNovels" 
            :key="novel.id" 
            class="novel-item"
            @click="openNovel(novel)"
          >
            <image 
              :src="getCoverUrl(novel.coverImg)" 
              class="novel-cover"
              @error="handleImageError"
            />
            <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';

export default {
  components: { AdBanner },
  data() {
    return {
      topAds: [],
      bottomAds: [],
      categories: [],
      activeCategory: 0,
      hotNovels: [],
      novels: [],
      loading: true,
      error: null,
      currentCategoryName: '全部',
      
      // 临时解决方案 - 模拟数据
      mockHotNovels: [
        { id: 1, title: '总裁的替身前妻', coverImg: '/static/demo-cover1.jpg', author: '言情作家' },
        { id: 2, title: '神医毒妃', coverImg: '/static/demo-cover2.jpg', author: '古风大神' },
        { id: 3, title: '穿越之王妃逆袭', coverImg: '/static/demo-cover3.jpg', author: '穿越达人' }
      ],
      mockNovels: [
        { id: 4, title: '都市最强赘婿', author: '网络作家', coverImg: '/static/demo-cover4.jpg' },
        { id: 5, title: '修仙归来', author: '仙侠迷', coverImg: '/static/demo-cover5.jpg' },
        { id: 6, title: '校园纯爱物语', author: '青春校园', coverImg: '/static/demo-cover6.jpg' }
      ],
      // 添加分页参数
      page: 1,
      pageSize: 10,
      total: 0,
      hasMore: true
    }
  },
  computed: {
    // 添加计算属性控制显示逻辑
    showEmptyState() {
      return this.novels.length === 0 && !this.error && !this.loading;
    },
    showHotNovels() {
      return this.hotNovels.length > 0 && !this.error;
    },
    showNovels() {
      return this.novels.length > 0 && !this.error;
    },
    displayedHotNovels() {
      return this.hotNovels.length > 0 ? this.hotNovels : this.mockHotNovels;
    },
    displayedNovels() {
      return this.novels.length > 0 ? this.novels : this.mockNovels;
    }
  },
  mounted() {
    this.initData();
  },
  methods: {
    async initData() {
      try {
        // 确保所有方法都已绑定
        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;
        }
        
        // 并行加载数据以提高性能
        await Promise.all([
          this.loadCategories(),
          this.loadHotNovels(),
          this.loadNovels(),
          this.loadAds()
        ]);
      } catch (e) {
        console.error('初始化失败', e);
        this.error = '初始化失败，请检查网络连接';
      } finally {
        this.loading = false;
      }
    },

    // 修复API请求逻辑
    async loadCategories() {
      try {
        const res = await this.$http.get('/category/tree', {
          header: { isToken: false }
        });
        
        console.log('分类API响应:', res);
        
        // 确保正确解析API响应
        if (res && res.data && res.data.code === 200 && Array.isArray(res.data.data)) {
          // 提取所有子分类（第二级分类）
          let subCategories = [];
          res.data.data.forEach(parent => {
            if (parent.children && Array.isArray(parent.children)) {
              subCategories = subCategories.concat(parent.children);
            }
          });
          
          // 添加"全部"分类
          this.categories = [
            { id: 0, name: '全部' }, 
            ...subCategories
          ];
        } else {
          console.warn('分类数据结构异常，使用默认分类');
          this.categories = [{ id: 0, name: '全部' }];
        }
      } catch (e) {
        console.error('加载分类失败', e);
        this.categories = [{ id: 0, name: '全部' }];
      }
    },

    async loadHotNovels() {
      try {
        const res = await this.$http.get('/novel/hot', {
          header: { isToken: false }
        });
        
        console.log('热门小说API响应:', res);
        
        // 处理不同API响应格式
        if (res && res.data) {
          if (res.data.code === 200 && Array.isArray(res.data.rows)) {
            this.hotNovels = res.data.rows;
          } else if (Array.isArray(res.data)) {
            this.hotNovels = res.data;
          } else {
            console.error('热门小说数据结构异常');
          }
        }
        
        // 只在真实数据不可用时使用模拟数据
        if (!this.hotNovels || this.hotNovels.length === 0) {
          console.warn('使用模拟热门小说数据');
          this.hotNovels = this.mockHotNovels;
        }
      } catch (e) {
        console.error('加载热门小说失败', e);
        this.hotNovels = this.mockHotNovels;
      }
    },

    async loadNovels(reset = false) {
      if (reset) {
        this.page = 1;
        this.hasMore = true;
        this.novels = [];
      }
      
      if (!this.hasMore) return;
      
      this.loading = true;
      this.error = null;
      
      try {
        const res = await this.$http.get('/novel/list', {
          params: {
            page: this.page,
            pageSize: this.pageSize,
            categoryId: this.activeCategory
          },
          header: { isToken: false }
        });
        
        console.log('小说列表API响应:', res);
        
        let newNovels = [];
        let total = 0;
        
        // 处理不同API响应格式
        if (res && res.data) {
          if (res.data.code === 200 && Array.isArray(res.data.rows)) {
            newNovels = res.data.rows;
            total = res.data.total;
          } 
          else if (Array.isArray(res.data)) {
            newNovels = res.data;
            total = res.data.length;
          }
        }
        
        if (newNovels.length > 0) {
          this.novels = [...this.novels, ...newNovels];
          this.hasMore = this.novels.length < total;
          this.page++;
        } else if (this.page === 1) {
          console.warn('小说列表为空');
          this.novels = [];
        }
      } catch (e) {
        console.error('加载小说失败', e);
        this.error = '加载失败，请重试';
        if (this.novels.length === 0) {
          this.novels = this.mockNovels;
        }
      } finally {
        this.loading = false;
      }
    },

    async loadAds() {
      try {
        // 使用Promise.all并行请求
        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 = this.parseAdResponse(topRes);
        this.bottomAds = this.parseAdResponse(bottomRes);
      } catch (e) {
        console.error('加载广告失败', e);
      }
    },
    
    // 新增：广告响应解析方法
    parseAdResponse(response) {
      if (!response || !response.data) return [];
      
      if (response.data.code === 200 && Array.isArray(response.data.data)) {
        return response.data.data;
      } else if (Array.isArray(response.data)) {
        return response.data;
      } else if (Array.isArray(response.data.rows)) {
        return response.data.rows;
      }
      
      return [];
    },

    // 修复封面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 || ''}${cover}`;
    },
    
    // 添加图片错误处理
    handleImageError(event) {
      event.target.src = '/static/default-cover.jpg';
    },
    
    // 其他方法...
    changeCategory(categoryId) {
      this.activeCategory = categoryId;
      const category = this.categories.find(c => c.id === categoryId);
      this.currentCategoryName = category ? category.name : '全部';
      this.loadNovels(true); // 重置并加载新分类
    },
    
    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();
    },
    
    // 添加上拉加载事件
    onReachBottom() {
      this.loadNovels();
    }
  }
}
</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: white;
  border-radius: 12rpx;
  overflow: hidden;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
}

/* 确保封面有默认背景和固定比例 */
.novel-cover, .hot-cover {
  width: 100%;
  height: 300rpx;
  background-color: #f5f5f5;
  object-fit: cover;
}

.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;
}

/* 热门列表样式 */
.hot-list {
  display: flex;
  padding: 20rpx;
  overflow-x: auto;
  white-space: nowrap;
}

.hot-item {
  display: inline-block;
  width: 200rpx;
  margin-right: 30rpx;
}

.hot-cover {
  width: 200rpx;
  height: 280rpx;
  border-radius: 8rpx;
}

.hot-title {
  display: block;
  margin-top: 10rpx;
  font-size: 26rpx;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

/* 分类导航样式 */
.category-nav {
  white-space: nowrap;
  padding: 20rpx 0;
  background-color: #fff;
  border-bottom: 1rpx solid #eee;
}

.category-item {
  display: inline-block;
  padding: 10rpx 30rpx;
  margin: 0 10rpx;
  border-radius: 30rpx;
  font-size: 28rpx;
}

.category-item.active {
  background-color: var(--primary-color);
  color: white;
}

/* 章节标题样式 */
.section {
  margin-top: 30rpx;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20rpx 20rpx;
}

.section-title {
  font-size: 32rpx;
  font-weight: bold;
}

.section-more {
  font-size: 26rpx;
  color: var(--text-secondary-color);
}

/* 成为作家按钮样式 */
.become-author {
  margin: 40rpx 20rpx;
  padding: 20rpx;
  text-align: center;
  background-color: var(--primary-color);
  color: white;
  border-radius: 10rpx;
  font-size: 30rpx;
}
</style>
