<template>
    <view class="container">
      <!-- 搜索栏 -->
      <view class="search-bar">
        <input 
          type="text" 
          placeholder="搜索课程" 
          v-model="searchQuery" 
          @input="onSearch"
        />
      </view>
      <!-- 分类导航 -->
      <scroll-view class="category-scroll" scroll-x>
        <view class="category-nav">
          <view 
            v-for="(category, index) in showCategories" 
            :key="index"
            class="category-item" 
            :class="{active: currentTab === index}" 
            @click="changeTab(index)"
          >
            {{ category.categoryName }}
          </view>
          <!-- 全部分类按钮 -->
          <view 
            v-if="categories.length > 3" 
            class="category-item" 
            @click="toggleShowAll"
          >
            {{ showAll ? '收起分类' : '全部分类' }}
          </view>
        </view>
      </scroll-view>
      <!-- 课程列表 -->
      <view class="course-list">
        <view 
          v-for="(course, index) in courses" 
          :key="index"
          class="course-item"
        >
          <view class="course-img">
            <image :src="course.imgUrl" mode="aspectFill"></image>
          </view>
          <view class="course-info">
            <view class="course-title">{{course.courseName}}</view>
            <view class="course-price">¥{{course.coursePrice}}</view>
          </view>
        </view>
      </view>
    </view>
</template>

<script>
export default {
  data() {
    return {
      currentTab: 1,
      categories: [], 
      courses: [], 
      searchQuery: '',
      showAll: false // 控制是否显示全部分类
    };
  },
  computed: {
    // 根据 showAll 状态计算需要显示的分类
    showCategories() {
      if (this.showAll || this.categories.length <= 4) {
        return this.categories;
      } else {
        return this.categories.slice(0, 4);
      }
    }
  },
  mounted() {
    this.fetchCategories(); 
    this.fetchCourses(); 
  },
  methods: {
    // 获取分类导航数据
    fetchCategories() {
      uni.request({
        url: 'http://localhost:8080/system/category/findAll',
        method: 'GET',
        success: (res) => {
          console.log('分类导航响应数据:', res);
          if (res.statusCode === 200) {
            // 假设数据被嵌套在 data 字段里
            if (res.data && Array.isArray(res.data.data)) { 
              this.categories = res.data.data;
            } else {
              console.error('分类导航数据格式不正确:', res.data);
            }
          } else {
            console.error('获取分类导航数据失败:', `HTTP error! status: ${res.statusCode}`);
          }
        },
        fail: (error) => {
          console.error('获取分类导航数据失败:', error.errMsg);
        }
      });
    },
    // 获取课程列表数据
    fetchCourses() {
      let url = `http://localhost:8080/system/course/findById?courseCategory=${this.currentTab}`;
      if (this.searchQuery) {
        url += `&search=${this.searchQuery}`;
      }
      uni.request({
        url: url,
        method: 'GET',
        success: (res) => {
          if (res.statusCode === 200) {
            this.courses = res.data;
          } else {
            console.error('获取课程列表数据失败:', `HTTP error! status: ${res.statusCode}`);
            uni.showToast({
              title: `获取课程列表失败，状态码: ${res.statusCode}`,
              icon: 'none'
            });
          }
        },
        fail: (error) => {
          console.error('获取课程列表数据失败:', error.errMsg);
          uni.showToast({
            title: `获取课程列表失败: ${error.errMsg}`,
            icon: 'none'
          });
        },
        complete: () => {
          // 请求完成后的操作，可根据需要添加
        }
      });
    },
    changeTab(index) {
      this.currentTab = index;
      this.fetchCourses(); 
    },
    onSearch() {
      this.fetchCourses(); 
    },
    // 切换显示全部分类状态
    toggleShowAll() {
      this.showAll = !this.showAll;
    }
  }
};
</script>

<style lang="scss" scoped>
.container {
  padding: 10px;
}
.search-bar {
  background-color: #f5f5f5;
  padding: 8px;
  border-radius: 5px;
  margin-bottom: 10px;
}
.search-bar input {
  width: 100%;
  border: none;
}
.category-scroll {
  white-space: nowrap;
}
.category-nav {
  display: inline-flex;
  justify-content: space-around;
  margin-bottom: 10px;
}
.category-item {
  padding: 5px 10px;
  border-radius: 3px;
  cursor: pointer;
  display: inline-block;
}
.category-item.active {
  background-color: #ff9900;
  color: white;
}
// 全部分类展开时的样式，修改为一行展示四个分类
.category-nav.show-all {
  display: flex;
  flex-wrap: wrap;
  white-space: normal;
}
.category-nav.show-all .category-item {
  width: calc(25% - 10px); // 修改宽度为 25%，减去边距
  margin: 5px;
  box-sizing: border-box;
  text-align: center;
}
.course-list {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
}
.course-item {
  width: 48%;
  background-color: #fff;
  border-radius: 5px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  margin-bottom: 15px;
  overflow: hidden;
}
.course-img {
  width: 100%;
  height: 180px;
  position: relative;
}
.course-img image {
  width: 100%;
  height: 100%;
}
.course-info {
  padding: 10px;
}
.course-title {
  font-size: 16px;
  line-height: 1.4;
  margin-bottom: 5px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}
.course-price {
  color: #ff4500;
  font-size: 14px;
}
</style>
