<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 {
        // 改为顺序加载，便于调试
        await this.loadCategories();
        await this.loadHotNovels();
        await this.loadNovels();
      } catch (e) {
        console.error('初始化失败', e);
        this.error = '初始化失败，请检查网络连接';
      } finally {
        this.loading = false;
      }
    },
openNovel(novel) {
  // 使用uni.navigateTo替代this.$tab.navigateTo
  uni.navigateTo({
    url: `/pages/novel/reader?novelId=${novel.id}`
  });
},
    // 修复响应解析方法
    parseResponse(res) {
      console.log('原始响应对象:', res);
      
      // 处理不同的响应格式
      let responseData = {};
      
      // 如果res有arg属性，使用arg作为响应数据
      if (res && res.arg) {
        responseData = res.arg;
        console.log('使用res.arg作为响应数据:', responseData);
      }
      // 如果res有data属性，使用data作为响应数据
      else if (res && res.data) {
        responseData = res.data;
        console.log('使用res.data作为响应数据:', responseData);
      }
      // 如果res本身就是响应数据
      else {
        responseData = res;
        console.log('使用res本身作为响应数据:', responseData);
      }
      
      return responseData;
    },

    // 修复分类加载逻辑
    async loadCategories() {
      try {
        const res = await this.$http.get('/category/tree', {
          header: { isToken: false },
          timeout: 10000
        });
        
        console.log('分类API完整响应:', res);
        
        // 使用统一的响应解析方法
        const responseData = this.parseResponse(res);
        console.log('处理后的分类响应数据:', responseData);
        
        // 修复: 检查不同的响应格式
        let categoriesData = [];
        
        if (responseData.code === 200 && Array.isArray(responseData.data)) {
          categoriesData = responseData.data;
        } else if (Array.isArray(responseData)) {
          categoriesData = responseData;
        } else if (responseData.code === 200 && Array.isArray(responseData.rows)) {
          categoriesData = responseData.rows;
        }
        
        if (categoriesData.length > 0) {
          let subCategories = [];
          categoriesData.forEach(parent => {
            if (parent && parent.children && Array.isArray(parent.children)) {
              // 确保每个子分类都有必要的字段
              const validChildren = parent.children.filter(child => 
                child && child.id && (child.title || child.name)
              ).map(child => ({
                id: child.id,
                name: child.title || child.name // 使用title或name作为分类名称
              }));
              
              subCategories = [...subCategories, ...validChildren];
            }
          });
          
          // 添加"全部"分类
          this.categories = [
            { id: 0, name: '全部' }, 
            ...subCategories
          ];
          
          console.log('处理后的分类:', this.categories);
        } else {
          console.warn('分类数据结构异常，使用默认分类', responseData);
          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 },
          timeout: 10000
        });
        
        console.log('热门小说API完整响应:', res);
        
        // 使用统一的响应解析方法
        const responseData = this.parseResponse(res);
        console.log('处理后的热门小说响应:', responseData);
        
        // 处理API返回的数据格式
        if (responseData.code === 200) {
          if (Array.isArray(responseData.rows)) {
            this.hotNovels = responseData.rows;
          } else if (Array.isArray(responseData.data)) {
            this.hotNovels = responseData.data;
          } else {
            console.warn('热门小说数据格式异常', responseData);
            this.hotNovels = this.mockHotNovels;
          }
        } else {
          console.warn('热门小说API返回异常状态码', responseData);
          this.hotNovels = this.mockHotNovels;
        }
        
        // 只在真实数据不可用时使用模拟数据
        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 },
          timeout: 15000
        });
        
        console.log('小说列表API完整响应:', res);
        
        // 使用统一的响应解析方法
        const responseData = this.parseResponse(res);
        console.log('处理后的小说列表响应:', responseData);
        
        let newNovels = [];
        let total = 0;
        
        // 处理API返回的数据格式
        if (responseData.code === 200) {
          if (Array.isArray(responseData.rows)) {
            newNovels = responseData.rows;
            total = responseData.total || 0;
          } else if (Array.isArray(responseData.data)) {
            newNovels = responseData.data;
            total = responseData.total || newNovels.length;
          }
        } else if (responseData.code === 500) {
          // 处理服务器错误
          console.error('服务器内部错误:', responseData.msg);
          throw new Error('服务器内部错误，请稍后重试');
        }
        
        if (newNovels.length > 0) {
          this.novels = [...this.novels, ...newNovels];
          this.hasMore = this.novels.length < total;
          this.page++;
          
          // 修复: 确保图片URL正确
          this.novels.forEach(novel => {
            if (novel.coverImg) {
              novel.coverImg = this.getCoverUrl(novel.coverImg);
            }
          });
        } else if (this.page === 1) {
          console.warn('小说列表为空，使用模拟数据');
          this.novels = this.mockNovels; // 使用模拟数据
        }
      } catch (e) {
        console.error('加载小说失败', e);
        if (e.errMsg && e.errMsg.includes('timeout')) {
          this.error = '网络请求超时，请检查网络连接';
        } else if (e.message && e.message.includes('服务器内部错误')) {
          this.error = '服务器暂时不可用，请稍后重试';
        } else {
          this.error = '加载失败，请重试';
        }
        this.novels = this.mockNovels; // 回退到模拟数据
      } finally {
        this.loading = false;
      }
    },

    // 暂时禁用广告加载，避免404错误
    async loadAds() {
      try {
        console.log('广告功能暂未开放');
        this.topAds = [];
        this.bottomAds = [];
        
        // 以下是原有的广告加载代码，暂时注释掉
        /*
        // 使用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);
        this.topAds = [];
        this.bottomAds = [];
      }
    },
    
    // 广告响应解析方法 - 简化逻辑
    parseAdResponse(response) {
      if (!response || !response.data) return [];
      
      const responseData = response.data;
      
      // 统一处理可能的响应格式
      if (responseData.code === 200 && Array.isArray(responseData.data)) {
        return responseData.data;
      } else if (Array.isArray(responseData)) {
        return responseData;
      } else if (responseData.code === 200 && Array.isArray(responseData.rows)) {
        return responseData.rows;
      }
      
      return [];
    },

    // 修复封面URL处理
    getCoverUrl(cover) {
      if (!cover) return '/static/default-cover.jpg';
      
      // 如果已经是完整URL，直接返回
      if (cover.startsWith('http')) return cover;
      
      // 如果是相对路径，添加基础URL
      if (cover.startsWith('/')) {
        return `${process.env.VUE_APP_BASE_URL || ''}${cover}`;
      }
      
      // 其他情况，直接返回
      return cover;
    },
    
    // 添加图片错误处理
    handleImageError(event) {
      console.log('图片加载失败:', 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); // 重置并加载新分类
    },

    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>
