<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"
          @click="goToCourseDetail(course)"
        >
          <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: 0,
      categories: [], 
      allCourses: [], // 存储所有课程数据
      courses: [], // 存储当前显示的课程数据
      searchQuery: '',
      showAll: false, // 控制是否显示全部分类
      // 定义分类与课程的映射
      categoryCourseMap: {
        0: [
          {
            imgUrl: 'https://picx.zhimg.com/v2-d6f44389971daab7e688e5b37046e4e4_720w.jpg?source=172ae18b',
            courseName: '课程1',
            coursePrice: 99
          },
          {
            imgUrl: 'https://img.ixintu.com/download/jpg/201911/e25b904bc42a74d7d77aed81e66d772c.jpg!con',
            courseName: '课程2',
            coursePrice: 199
          }
        ],
        1: [
          {
            imgUrl: 'https://ts1.tc.mm.bing.net/th/id/OIP-C.Nj6o69waOC3JTbebyCu-hgHaEc?rs=1&pid=ImgDetMain',
            courseName: '课程3',
            coursePrice: 20
          },
          {
            imgUrl: 'https://pic1.zhimg.com/v2-02760a1bf058904006740d3f66b2c9ac_r.jpg?source=1940ef5c',
            courseName: '课程4',
            coursePrice: 150
          }
        ],
        2: [
          {
            imgUrl: 'https://ts1.tc.mm.bing.net/th/id/R-C.987f582c510be58755c4933cda68d525?rik=C0D21hJDYvXosw&riu=http%3a%2f%2fimg.pconline.com.cn%2fimages%2fupload%2fupc%2ftx%2fwallpaper%2f1305%2f16%2fc4%2f20990657_1368686545122.jpg&ehk=netN2qzcCVS4ALUQfDOwxAwFcy41oxC%2b0xTFvOYy5ds%3d&risl=&pid=ImgRaw&r=0',
            courseName: '课程5',
            coursePrice: 50
          },
          {
            imgUrl: 'https://ts1.tc.mm.bing.net/th/id/OIP-C.MQoT8Pi43oSD6cQGpvs-lAHaEK?rs=1&pid=ImgDetMain',
            courseName: '课程6',
            coursePrice: 80
          }
        ],
        3: [
          {
            imgUrl: 'https://ts1.tc.mm.bing.net/th/id/R-C.cf381aa2a44f28ade81cb72e0e8decae?rik=xctKMrYyWQKvDg&riu=http%3a%2f%2fwww.1mpi.com%2fpic%2f9af8385ddd409baf50e081d6%2f2-810-jpg_6-1080-0-0-1080.jpg&ehk=Fw4Rzzq%2bSED%2bgMqemTtEk7fUdSL%2fkwW0KcsnygzTqp4%3d&risl=&pid=ImgRaw&r=0',
            courseName: '课程7',
            coursePrice: 120
          },
          {
            imgUrl: 'https://img.shetu66.com/2023/04/25/1682391088567884.png',
            courseName: '课程8',
            coursePrice: 180
          }
        ],
        4: [
          {
            imgUrl: 'https://ts1.tc.mm.bing.net/th/id/R-C.82ece114307f62dc0b8aa2c366b9ef37?rik=GwmaljjvGJ75zg&riu=http%3a%2f%2fimg.pconline.com.cn%2fimages%2fupload%2fupc%2ftx%2fwallpaper%2f1308%2f15%2fc2%2f24494094_1376530595238.jpg&ehk=L%2fNVdWJDsmRvIsmKuuUcvCGnK4DJwpxad4JswscWIN0%3d&risl=&pid=ImgRaw&r=0',
            courseName: '课程9',
            coursePrice: 30
          },
          {
            imgUrl: 'https://bpic.588ku.com/back_origin_min_pic/21/07/09/8c9d5f41848ca6a292d52b3457ed418a.jpg',
            courseName: '课程10',
            coursePrice: 60
          }
        ],
        5: [
          {
            imgUrl: 'https://pic.616pic.com/ys_bnew_img/00/13/11/J1kFGL8p6F.jpg',
            courseName: '课程11',
            coursePrice: 90
          },
          {
            imgUrl: 'https://pic.616pic.com/ys_bnew_img/00/47/45/WwJs1U7BJW.jpg',
            courseName: '课程12',
            coursePrice: 110
          }
        ],
        6: [
          {
            imgUrl: 'https://pic.616pic.com/ys_bnew_img/00/06/07/KT7I0AbOoI.jpg',
            courseName: '课程13',
            coursePrice: 40
          },
          {
            imgUrl: 'https://ts1.tc.mm.bing.net/th/id/R-C.72eb213371fd74859ad6c574cf223070?rik=AjZbpwPKouep7A&riu=http%3a%2f%2fattach.66rpg.com%2fbbs%2fattachment%2fforum%2f201501%2f09%2f211837s6hkh6g5mg35336s.jpg&ehk=gJTX%2bHzLsoWwDctstn13%2bJY3QmA86kqpzexWicVHgbw%3d&risl=&pid=ImgRaw&r=0',
            courseName: '课程14',
            coursePrice: 70
          }
        ],
        7: [
          {
            imgUrl: 'https://ts1.tc.mm.bing.net/th/id/R-C.478f595a4d79e0aacc812494d3f8ab9f?rik=%2bqgBvxUlXAuqqQ&riu=http%3a%2f%2ffile.51pptmoban.com%2fd%2ffile%2f2023%2f08%2f25%2f43b8e6ed4fa04f190edd0c8bd83d52b0.jpg&ehk=qiyuhH8mm%2bU9cHz1Px%2fLOZqDKA6PaSlPbn8yD5mnQGk%3d&risl=&pid=ImgRaw&r=0',
            courseName: '课程15',
            coursePrice: 130
          },
          {
            imgUrl: 'https://img.keaitupian.cn/newupload/07/1688632400492441.jpg',
            courseName: '课程16',
            coursePrice: 160
          }
        ],
        8: [
          {
            imgUrl: 'https://img.tukuppt.com/photo-big/18/10/08/07/27/181008072732.jpg',
            courseName: '课程17',
            coursePrice: 200
          },
          {
            imgUrl: 'https://file.51pptmoban.com/d/file/2022/09/13/b2d85362febcf895e78916e0696f1a59.jpg',
            courseName: '课程18',
            coursePrice: 220
          }
        ]
      }
    };
  },
  computed: {
    // 根据 showAll 状态计算需要显示的分类
    showCategories() {
      if (this.showAll || this.categories.length <= 4) {
        return this.categories;
      } else {
        return this.categories.slice(0, 4);
      }
    }
  },
  mounted() {
    this.fetchCategories(); 
    // 初始化所有课程数据
    this.allCourses = Object.values(this.categoryCourseMap).flat();
    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 方法，接收 index 参数
    fetchCourses(index) {
      const categoryIndex = index !== undefined ? index : this.currentTab;
      let categoryCourses = this.categoryCourseMap[categoryIndex] || [];

      if (this.searchQuery) {
        categoryCourses = categoryCourses.filter(course =>
          course.courseName.includes(this.searchQuery)
        );
      }

      this.courses = categoryCourses;
    },
    changeTab(index) {
      this.currentTab = index;
      // 调用 fetchCourses 时传递 index 参数
      this.fetchCourses(index); 
    },
    onSearch() {
      // 搜索时调用 fetchCourses 不传递 index 参数，使用默认逻辑
      this.fetchCourses(); 
    },
    // 切换显示全部分类状态
    toggleShowAll() {
      this.showAll = !this.showAll;
    },
    goToCourseDetail(course) {
      uni.navigateTo({
        url: `/pages/courseDetail/courseDetail?imgUrl=${encodeURIComponent(course.imgUrl)}&courseName=${encodeURIComponent(course.courseName)}&coursePrice=${course.coursePrice}`
      });
    }
  }
};
</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>
