<template>
  <view class="discover-container">
    <!-- 自定义状态栏 -->
    <view class="status-bar"></view>
    
    <!-- 搜索框 -->
    <view class="search-section">
      <view class="search-box">
        <text class="search-icon">🔍</text>
        <input class="search-input" placeholder="python · html · java..." />
      </view>
    </view>

    <!-- 轮播图 -->
    <view class="banner-section" v-if="swipeGroup.length > 0">
      <swiper class="banner-swiper" :indicator-dots="true" :autoplay="true" :interval="3000" :duration="1000">
        <swiper-item v-for="(item, index) in swipeGroup" :key="index">
          <image 
            class="swipe-image" 
            :src="item.cover" 
            mode="aspectFill"
            @click="navigateToSwipeLink(index)"
          />
        </swiper-item>
      </swiper>
    </view>

    <!-- 功能模块 -->
    <view class="function-section">
      <view class="function-row">
        <view class="function-item" v-for="(item, index) in functionList.slice(0, 5)" :key="index" @click="handleFunctionClick(item)">
          <view class="function-icon">
            <image :src="item.icon" mode="aspectFit"></image>
          </view>
          <text class="function-text">{{ item.name }}</text>
          <view v-if="item.badge" class="function-badge">{{ item.badge }}</view>
        </view>
      </view>
      <view class="function-row">
        <view class="function-item" v-for="(item, index) in functionList.slice(5, 10)" :key="index" @click="handleFunctionClick(item)">
          <view class="function-icon" :style="{ backgroundColor: item.bgColor }">
            <image :src="item.icon" mode="aspectFit"></image>
          </view>
          <text class="function-text">{{ item.name }}</text>
        </view>
      </view>
    </view>

    <!-- 课程推荐卡片 -->
    <view class="course-cards">
      <view class="course-card" v-for="(card, index) in courseCards" :key="index" :style="{ backgroundColor: card.bgColor }">
        <view class="card-content">
          <text class="card-title">{{ card.title }}</text>
          <text class="card-subtitle">{{ card.subtitle }}</text>
        </view>
        <image class="card-image" :src="card.image" mode="aspectFit"></image>
      </view>
    </view>

    <!-- 课程列表 -->
    <view class="course-section">
      <view class="section-header">
        <text class="section-title">大家都在学</text>
        <view class="more-btn">
          <text>更多课程</text>
          <text class="arrow-icon">›</text>
        </view>
      </view>

      <view class="course-list">
        <view class="course-item" v-for="(course, index) in courseList" :key="index" @click="handleCourseClick(course)">
          <image class="course-cover" :src="course.cover" mode="aspectFill"></image>
          <view class="course-info">
            <text class="course-title">{{ course.title }}</text>
            <view class="course-stats">
              <text class="course-students">{{ course.students }}人学习</text>
              <text class="course-type">{{ course.type }}</text>
            </view>
            <text class="course-desc">{{ course.description }}</text>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import requestModule from '@/utils/request'
import config from '@/config/index.js'

// 轮播图数据
const swipeGroup = ref([])

// 功能模块数据
const functionList = ref([
  { name: '学练课', icon: '/static/icons/study.png', bgColor: '#FF6B6B', badge: '好课' },
  { name: '视频课', icon: '/static/icons/video.png', bgColor: '#9B59B6' },
  { name: '题库', icon: '/static/icons/question.png', bgColor: '#F39C12' },
  { name: '教程', icon: '/static/icons/tutorial.png', bgColor: '#2ECC71' },
  { name: 'VIP会员', icon: '/static/icons/vip.png', bgColor: '#E74C3C', badge: '16周年' },
  { name: '基础入门', icon: '/static/icons/basic.png', bgColor: '#3498DB' },
  { name: '数据分析', icon: '/static/icons/data.png', bgColor: '#1ABC9C' },
  { name: '人工智能', icon: '/static/icons/ai.png', bgColor: '#95A5A6' },
  { name: '爬虫', icon: '/static/icons/spider.png', bgColor: '#34495E' },
  { name: '办公自动化', icon: '/static/icons/office.png', bgColor: '#16A085' }
])

// 课程推荐卡片
const courseCards = ref([
  {
    title: 'Python高薪就业课',
    subtitle: '面向大学、职场就业提效',
    bgColor: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
    image: '/static/cards/job-card.png'
  },
  {
    title: 'Python少儿编程',
    subtitle: '面向小学、初高中学习',
    bgColor: 'linear-gradient(135deg, #f093fb 0%, #f5576c 100%)',
    image: '/static/cards/kids-card.png'
  }
])

// 课程列表数据
const courseList = ref([
  {
    cover: '/static/courses/python-basic.png',
    title: 'Python3 入门课程',
    students: '5037',
    type: '学练课',
    description: '爬虫+机器学习? Python无所不能...'
  },
  {
    cover: '/static/courses/python-zero.png',
    title: '零基础入门学Python',
    students: '619',
    type: '视频课',
    description: '通过Python入门到实战全套教程...'
  },
  {
    cover: '/static/courses/python-guide.png',
    title: 'Python3零基础入门先导课',
    students: '5847',
    type: '学练课',
    description: '0基础的python入门先导课程...'
  }
])

// 获取轮播图
const getSwipe = () => {
  try {
    // 先尝试从本地存储获取缓存数据
    const cachedSwipe = uni.getStorageSync('swipeGroup')
    if (cachedSwipe) {
      swipeGroup.value = JSON.parse(cachedSwipe)
    }
  } catch (e) {
    console.error('获取缓存轮播图失败:', e)
  }

  // 检查必要的依赖
  if (!requestModule || !config) {
    console.error('request或config模块未正确导入')
    return
  }

  try {
    // 安全获取系统信息
    const systemInfo = uni.getSystemInfoSync()
    
    // 从服务器获取最新数据 - 使用正确的API调用方式
    requestModule.request('/api/appapi/getSlide', {}, {
      apptype: config.APP_TYPE || 'production',
      systemType: systemInfo.platform || 'unknown'
    }, (ret, err) => {
      try {
        if (ret && ret.statusCode < 300 && ret.data) {
          swipeGroup.value = []
          // console.log('轮播图原始数据:', JSON.stringify(ret.data))
          // console.log('ret.data类型:', typeof ret.data, 'isArray:', Array.isArray(ret.data))
          
          // 确保ret.data是数组
          let dataArray = ret.data
          if (typeof ret.data === 'string') {
            try {
              dataArray = JSON.parse(ret.data)
            } catch (e) {
              console.error('解析轮播图数据失败:', e)
              dataArray = []
            }
          }
          
          // 如果不是数组，尝试从其他可能的字段获取
          if (!Array.isArray(dataArray)) {
            if (dataArray && dataArray.list && Array.isArray(dataArray.list)) {
              dataArray = dataArray.list
            } else if (dataArray && dataArray.data && Array.isArray(dataArray.data)) {
              dataArray = dataArray.data
            } else {
              console.error('轮播图数据格式不正确:', dataArray)
              dataArray = []
            }
          }
          
          // 处理数组数据
          if (Array.isArray(dataArray) && dataArray.length > 0) {
            dataArray.forEach((item) => {
              if (item && item.cover) {
                const swipeItem = {
                  cover: config.BASE_URL + '/' + item.cover,
                  link: item.link || '',
                  title: item.title || ''
                }
                swipeGroup.value.push(swipeItem)
              }
            })
          }
          
          // 缓存到本地存储
          try {
            uni.setStorageSync('swipeGroup', JSON.stringify(swipeGroup.value))
          } catch (e) {
            console.error('缓存轮播图失败:', e)
          }
          
          // console.log('处理后的轮播图数据:', JSON.stringify(swipeGroup.value))
        } else if (swipeGroup.value.length === 0) {
          // 如果没有数据且缓存也为空，使用默认图片
          swipeGroup.value = [{
            cover: '/static/banner/default-slide.png',
            link: '',
            title: '默认轮播图'
          }]
        }
        
        if (err) {
          console.error('获取轮播图失败:', err)
        }
      } catch (error) {
        console.error('处理轮播图数据时出错:', error)
      }
    })
  } catch (error) {
    console.error('获取系统信息或发起请求时出错:', error)
  }
}

// 轮播图点击跳转
const navigateToSwipeLink = (index) => {
  const item = swipeGroup.value[index]
  if (!item || !item.link) return
  
  console.log('点击轮播图:', item.title, item.link)
  
  // 处理不同类型的链接
  if (item.link.startsWith('http')) {
    // 外部链接，使用webview打开
    uni.navigateTo({
      url: `/pages/webview/webview?url=${encodeURIComponent(item.link)}&title=${encodeURIComponent(item.title || '详情')}`
    })
  } else if (item.link.includes('||')) {
    // 内部页面跳转格式: winname||path||params
    const linkParts = item.link.split('||')
    if (linkParts.length >= 2) {
      const pagePath = linkParts[1]
      const params = linkParts[2] || ''
      
      // 构建跳转路径
      let navigateUrl = `/pages/${pagePath}`
      if (params) {
        navigateUrl += `?params=${encodeURIComponent(params)}`
      }
      
      uni.navigateTo({
        url: navigateUrl
      })
    }
  }
}

// 方法
const handleFunctionClick = (item) => {
  console.log('点击功能:', item.name)
  // 这里可以添加跳转逻辑
}

const handleCourseClick = (course) => {
  console.log('点击课程:', course.title)
  // 这里可以添加跳转到课程详情的逻辑
}

onMounted(() => {
  try {
    console.log('发现页面加载完成')
    // 获取轮播图数据
    getSwipe()
  } catch (error) {
    console.error('页面初始化时出错:', error)
  }
})
</script>

<style lang="scss" scoped>
.discover-container {
  background-color: #f5f5f5;
  min-height: 100vh;
}

// 自定义状态栏
.status-bar {
  background-color: #fff;
  /* 使用CSS环境变量适配安全区域 */
  height: env(safe-area-inset-top);
  height: constant(safe-area-inset-top); /* 兼容iOS < 11.2 */
  /* 设置最小高度，确保在没有刘海屏的设备上也有合适的高度 */
  min-height: 20px;
}

// 搜索框样式
.search-section {
  background-color: #fff;
  padding: 20rpx 30rpx;
  
  .search-box {
    display: flex;
    align-items: center;
    background-color: #f8f8f8;
    border-radius: 50rpx;
    padding: 20rpx 30rpx;
    
    .search-icon {
      font-size: 32rpx;
      color: #999;
    }
    
    .search-input {
      flex: 1;
      margin-left: 20rpx;
      font-size: 28rpx;
      color: #333;
    }
  }
}

// 轮播图样式
.banner-section {
  margin: 20rpx 30rpx;
  
  .banner-swiper {
    height: 300rpx;
    border-radius: 20rpx;
    overflow: hidden;
  }
  
  .swipe-image {
    width: 100%;
    height: 100%;
    border-radius: 20rpx;
  }
}

// 功能模块样式
.function-section {
  background-color: #fff;
  margin: 20rpx 30rpx;
  border-radius: 20rpx;
  padding: 40rpx 20rpx;
  
  .function-row {
    display: flex;
    justify-content: space-around;
    margin-bottom: 40rpx;
    
    &:last-child {
      margin-bottom: 0;
    }
  }
  
  .function-item {
    display: flex;
    flex-direction: column;
    align-items: center;
    position: relative;
    
    .function-icon {
      width: 80rpx;
      height: 80rpx;
      border-radius: 20rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-bottom: 15rpx;
    }
    
    .function-text {
      font-size: 24rpx;
      color: #333;
    }
    
    .function-badge {
      position: absolute;
      top: -10rpx;
      right: -10rpx;
      background-color: #FF4757;
      color: #fff;
      font-size: 18rpx;
      padding: 4rpx 8rpx;
      border-radius: 20rpx;
      transform: scale(0.8);
    }
  }
}

// 课程推荐卡片样式
.course-cards {
  margin: 20rpx 30rpx;
  display: flex;
  gap: 20rpx;
  
  .course-card {
    flex: 1;
    height: 200rpx;
    border-radius: 20rpx;
    padding: 30rpx;
    display: flex;
    align-items: center;
    justify-content: space-between;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    
    .card-content {
      flex: 1;
      
      .card-title {
        display: block;
        color: #fff;
        font-size: 28rpx;
        font-weight: bold;
        margin-bottom: 10rpx;
      }
      
      .card-subtitle {
        display: block;
        color: #fff;
        font-size: 22rpx;
        opacity: 0.9;
      }
    }
    
    .card-image {
      width: 80rpx;
      height: 80rpx;
    }
  }
}

// 课程列表样式
.course-section {
  background-color: #fff;
  margin: 20rpx 30rpx;
  border-radius: 20rpx;
  padding: 30rpx;
  
  .section-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 30rpx;
    
    .section-title {
      font-size: 32rpx;
      font-weight: bold;
      color: #333;
    }
    
    .more-btn {
      display: flex;
      align-items: center;
      color: #999;
      font-size: 24rpx;
      
      .arrow-icon {
        font-size: 28rpx;
        margin-left: 8rpx;
        color: #999;
      }
    }
  }
  
  .course-list {
    .course-item {
      display: flex;
      margin-bottom: 30rpx;
      
      &:last-child {
        margin-bottom: 0;
      }
      
      .course-cover {
        width: 160rpx;
        height: 120rpx;
        border-radius: 12rpx;
        margin-right: 20rpx;
      }
      
      .course-info {
        flex: 1;
        
        .course-title {
          display: block;
          font-size: 28rpx;
          font-weight: bold;
          color: #333;
          margin-bottom: 10rpx;
        }
        
        .course-stats {
          display: flex;
          align-items: center;
          margin-bottom: 10rpx;
          
          .course-students {
            font-size: 22rpx;
            color: #999;
            margin-right: 20rpx;
          }
          
          .course-type {
            font-size: 22rpx;
            color: #999;
          }
        }
        
        .course-desc {
          font-size: 24rpx;
          color: #666;
          line-height: 1.4;
        }
      }
    }
  }
}
</style>