<template>
  <view class="novel-list-page">
    <!-- 顶部广告（来自Java后台） -->
    <ad-banner :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 class="section">
      <view class="section-header">
        <text class="section-title">热门推荐</text>
        <text class="section-more">更多 ></text>
      </view>
      <scroll-view scroll-x class="hot-list">
        <view 
          v-for="novel in hotNovels" 
          :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 class="section">
      <view class="section-header">
        <text class="section-title">{{ currentCategoryName }}作品</text>
      </view>
      <view class="novel-grid">
        <view 
          v-for="novel in novels" 
          :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 :ads="bottomAds" />
  </view>

</template>
<script>
import AdBanner from '@/components/AdBanner';

export default {
	components: { AdBanner },
  data() {
    return {
          // 确保所有数组初始化为空数组
      novelList: [], // 存储小说目录数据
	        topAds: [],
	        bottomAds: [],
			      categories: [],
			      activeCategory: 0,
			      hotNovels: [],
			      novels: [],
			      currentCategoryName: '全部'
			
    }
  },
  async onLoad() {
    await this.loadAds();
    await this.loadNovels();
	    this.loadCategories();
	    this.loadHotNovels();
	    // this.loadNovels();
  },
  // onLoad() {
  //   this.loadNovelList();
  // },
  methods: {
    // 从Java后台加载广告
    async loadAds() {
      const [topRes, bottomRes] = await Promise.all([
        this.$http.get('/java-api/ad/position?code=TOP_BANNER'),
        this.$http.get('/java-api/ad/position?code=BOTTOM_BANNER')
      ]);
      
      this.topAds = topRes.data;
      this.bottomAds = bottomRes.data;
    },
	    applyAuthor() {
	      if (!this.$store.getters.token) {
	        uni.showToast({ title: '请先登录', icon: 'none' });
	        uni.navigateTo({ url: '/pages/login' });
	        return;
	      }
	      
	      uni.navigateTo({ url: '/pages/author/apply' });
	    },
        async loadCategories() {
          try {
            // 从Java后台获取分类
        const res = await this.$http.get('/category/tree');
        // 确保数据结构正确
        if (res.data && Array.isArray(res.data)) {
          // 添加"全部"选项
          this.categories = [{ id: 0, name: '全部' }];
          
          // 递归处理分类树
          const processCategories = (cats) => {
            cats.forEach(cat => {
              this.categories.push({
                id: cat.id,
                name: cat.title,
                children: cat.children
              });
              if (cat.children && cat.children.length) {
                processCategories(cat.children);
              }
            });
          };
          
          processCategories(res.data);
        } else {
          console.warn('分类数据格式不正确');
        }
          } catch (e) {
            console.error('加载分类失败', e);
          }
        },
    // 从PHP系统加载小说目录
    // async loadNovels() {
    //   const res = await this.$http.get('/php-api/novel/list');
    //   this.novelList = res.data;
    // },
        async loadHotNovels() {
          try {
            // 获取热门小说
            const res = await this.$http.get('/novel/hot');
            this.hotNovels = res.data;
          } catch (e) {
            console.error('加载热门小说失败', e);
          }
        },
    async loadNovels(categoryId = 0) {
      try {
        const url = categoryId 
          ? `/novel/list?categoryId=${categoryId}`
          : '/novel/list';
          
        const res = await this.$http.get(url);
        // 确保数据结构正确
        if (res.rows && Array.isArray(res.rows)) {
          this.novels = res.rows;
        } else {
          console.warn('小说列表数据格式不正确');
          this.novels = [];
        }

      } catch (e) {
        uni.showToast({ title: '加载小说失败', icon: 'none' });
      }
    },
    changeCategory(categoryId) {
      this.activeCategory = categoryId;
      this.loadNovels(categoryId);
    },
    openNovel(novel) {
      uni.navigateTo({
        url: `/pages/novel/detail?id=${novel.id}`
      });
    },
    applyAuthor() {
      uni.navigateTo({
        url: '/pages/author/apply'
      });
    },
    // 打开小说详情页
    openNovel(novel) {
      uni.navigateTo({
        url: `/pages/novel/detail?id=${novel.id}&title=${encodeURIComponent(novel.title)}`
      });
    }
  }
}
</script>
<style scoped>
.become-author {
  position: fixed;
  bottom: 120rpx; /* 在TabBar上方 */
  left: 50%;
  transform: translateX(-50%);
  background-color: #3cc51f;
  color: white;
  padding: 16rpx 40rpx;
  border-radius: 50rpx;
  font-size: 28rpx;
  box-shadow: 0 4rpx 12rpx rgba(60, 197, 31, 0.3);
  z-index: 999;
}
.novel-list-page {
  padding: 20rpx;
  padding-bottom: 40rpx;
}

.category-nav {
  white-space: nowrap;
  margin-bottom: 30rpx;
}

.category-item {
  display: inline-block;
  padding: 10rpx 30rpx;
  margin-right: 20rpx;
  border-radius: 50rpx;
  background-color: #f5f5f5;
  font-size: 28rpx;
}

.category-item.active {
  background-color: #3cc51f;
  color: white;
}

.section {
  margin-bottom: 40rpx;
}

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

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

.section-more {
  font-size: 24rpx;
  color: #888;
}

.hot-list {
  white-space: nowrap;
}

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

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

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

.novel-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 20rpx;
}

.novel-item {
  text-align: center;
}

.novel-cover {
  width: 100%;
  height: 300rpx;
  border-radius: 8rpx;
}

.novel-title {
  display: block;
  font-size: 26rpx;
  margin-top: 10rpx;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 1;
  -webkit-box-orient: vertical;
}

.novel-author {
  display: block;
  font-size: 22rpx;
  color: #888;
}

.become-author {
  position: fixed;
  bottom: 120rpx; /* 在TabBar上方 */
  left: 50%;
  transform: translateX(-50%);
  background-color: #3cc51f;
  color: white;
  padding: 16rpx 40rpx;
  border-radius: 50rpx;
  font-size: 28rpx;
  box-shadow: 0 4rpx 12rpx rgba(60, 197, 31, 0.3);
  z-index: 999;
}
</style>