<!-- 编程课列表内容 -->
<template>
  <div class="programming-content">
    <!-- 标题部分 -->
    <div class="top-box">
      <!-- 返回按钮 -->
      <div class="top-left-box">
        <div class="top-left-inner-box">
          <!-- 左侧返回图标 -->
          <div class="left-content-wrapper" @click="goBackIndex">
            <el-icon class="left-icon"><ArrowLeftBold /></el-icon>
            <span class="left-text">返回</span>
          </div>
        </div>
      </div>
      <!-- 标题 -->
    <div class="top-center-box" v-if="!showVideo">
      <div class="top-center-inner-box">
        <span>{{ pageTitle }}</span>
      </div>
    </div>
      <!-- 课程提示 -->
      <div class="top-right-box">
        <div class="top-right-inner-box">
          <div class="course-info-box">{{ originalCourseTitle }}</div>
        </div>
      </div>
    </div>

    <!-- 课程部分 -->
    <div class="lower-box" v-if="!showVideo">
        <!-- 左切换按钮 -->
        <div v-if="!showVideo && courseItems.length > 3" class="carousel-btn prev-btn" @click="prevSlide" :class="{ 'disabled-btn': currentIndex === 0 }" :disabled="currentIndex === 0">
          <el-icon class="btn-icon" :class="{ 'disabled-icon': currentIndex === 0 }"><ArrowLeftBold /></el-icon>
        </div>
        <div 
            class="content-box"
            ref="contentBox"
            @mousedown="handleMouseDown"
            @mousemove="handleMouseMove"
            @mouseup="handleMouseUp"
            @mouseleave="handleMouseLeave"
            @scroll="handleScroll"
          >
          <!-- 动态渲染课程内容 -->
          <div 
            v-for="(item) in courseItems" 
            :key="item.id"
            class="slide-item"
            :style="courseItems.length <= 3 ? { float: 'left' } : {}"
            @click="handleCourseItemClick(item)"
          >
            <div class="box-content">
              <img :src="item.image" :alt="item.title" class="box-image" />
              <div class="box-text">{{ item.title }}</div>
            </div>
            <!-- 星星图标组 -->
            <div class="star-group">
              <div
                v-for="i in getStarCount(item.contentType)"
                :key="i"
                class="star-icon"
                :style="{
                  backgroundImage: `url(${i <= item.progress ? star01Image : star02Image})`,
                }"
              ></div>
            </div>
          </div>
        </div>
        <!-- 右切换按钮 -->
        <div v-if="!showVideo && courseItems.length > 3" class="carousel-btn next-btn" @click="nextSlide" :class="{ 'disabled-btn': currentIndex >= courseItems.length - 3 }" :disabled="currentIndex >= courseItems.length - 3">
          <el-icon class="btn-icon" :class="{ 'disabled-icon': currentIndex >= courseItems.length - 3 }"><ArrowRightBold /></el-icon>
        </div>
    </div>
    
    <!-- 视频和编程界面 -->
    <Interface v-if="showVideo" :courseData="selectedCourseData" :courseList="resData" @closeVideo="showVideo = false" />

  </div>
</template>

<script setup>
// 返回图标
import { ArrowLeftBold, ArrowRightBold } from '@element-plus/icons-vue';
import { ref, onMounted, computed } from 'vue';
// 导入路由
import { useRouter, useRoute } from 'vue-router';
// 根据ID获取课程列表
import { getBlocklyByTypeId } from '@/api/programming/index.js'
// 导入图片
import  explanation  from '@/assets/programming/explanation.png'
import  practice  from '@/assets/programming/practice.png'
import  summary  from '@/assets/programming/summary.png'

import Interface from './Interface.vue'

// 星星图片
import star02Image from '@/assets/programming/star02.png'
import star01Image from '@/assets/programming/star01.png'


// 获取路由实例
const router = useRouter()
const route = useRoute()
// 页面标题
const pageTitle = ref('')
// 保存原始的课程ID和标题
const originalCourseId = ref('')
const originalCourseTitle = ref('')
// 类型ID（从ProgrammingList页面传递过来）
const typeId = ref('')
// 控制视频界面显示
const showVideo = ref(false) 
// 动态课程项数据
const courseItems = ref([])
// 当前选中的课程数据
const selectedCourseData = ref(null)
// 保存原始API返回的数据
const resData = ref([])
// 轮播图当前索引
const currentIndex = ref(0)

// 拖动相关变量
const isDragging = ref(false)
const startX = ref(0)
const scrollLeft = ref(0)
const hasMoved = ref(false) // 标记是否发生了移动

// 获取contentBox元素的引用
const contentBox = ref(null)

// 根据内容类型获取星星数量
const getStarCount = (contentType) => {
  if (contentType === 'video') {
    return 1; // video类型渲染1个星星
  } else if (contentType === 'blockly') {
    return 3; // blockly类型渲染3个星星
  }
}

// 上一页
const prevSlide = () => {
  if (currentIndex.value > 0) {
    currentIndex.value = Math.max(0, currentIndex.value - 3)
    // 滚动到对应位置
    if (contentBox.value) {
      const itemWidth = rpxValue(140) + rpxValue(70); // 宽度+间距
      const scrollPosition = currentIndex.value * itemWidth;
      contentBox.value.scrollTo({
        left: scrollPosition,
        behavior: 'smooth'
      });
    }
  }
}

// 下一页
const nextSlide = () => {
  if (currentIndex.value < courseItems.value.length - 3) {
    currentIndex.value = Math.min(courseItems.value.length - 3, currentIndex.value + 3)
    // 滚动到对应位置
    if (contentBox.value) {
      const itemWidth = rpxValue(140) + rpxValue(70); // 宽度+间距
      const scrollPosition = currentIndex.value * itemWidth;
      contentBox.value.scrollTo({
        left: scrollPosition,
        behavior: 'smooth'
      });
    }
  }
}

// 鼠标按下事件处理函数
const handleMouseDown = (e) => {
  // 拖拽状态为true
  isDragging.value = true
  // 初始化移动状态为false
  hasMoved.value = false
  // 计算鼠标在容器内的相对X坐标的位置  e.pageX鼠标相对于整个页面的X坐标
  startX.value = e.pageX - contentBox.value.offsetLeft
  // 记录当前容器的滚动位置
  scrollLeft.value = contentBox.value.scrollLeft
  e.stopPropagation() // 阻止事件冒泡 防止事件继续向上传播到父元素
}

// 鼠标移动事件处理函数
const handleMouseMove = (e) => {
  if (!isDragging.value) return
  // 标记已发生移动
  hasMoved.value = true
  // 阻止默认行为和冒泡
  e.preventDefault()
  e.stopPropagation()
  const x = e.pageX - contentBox.value.offsetLeft
  const walk = (x - startX.value) * 2 // 滚动速度
  contentBox.value.scrollLeft = scrollLeft.value - walk
}

// 鼠标松开事件处理函数
const handleMouseUp = () => {
  isDragging.value = false
  // 延迟重置hasMoved，确保点击事件可以正常判断
  setTimeout(() => {
    hasMoved.value = false
  }, 100)
}

// 鼠标离开事件处理函数
const handleMouseLeave = () => {
  isDragging.value = false
  hasMoved.value = false
}

// rpx转换为像素值的辅助函数
const rpxValue = (px) => {
  return (px / 750) * window.innerWidth;
}

// 滚动事件处理函数
const handleScroll = () => {
  if (contentBox.value && !isDragging.value) {
    // 检查是否滚动到最右侧
    const { scrollLeft, scrollWidth, clientWidth } = contentBox.value;
    // 当滚动到最右侧时，禁用右侧箭头
    if (scrollLeft + clientWidth >= scrollWidth - 10) { 
      currentIndex.value = Math.max(0, courseItems.value.length - 3);
    } else {
      // 向右滑动，左侧按钮正常显示
      if (scrollLeft > 10) {
        // 根据滚动位置计算当前索引，但不限制为0
        const itemWidth = rpxValue(140) + rpxValue(70); // 宽度+间距
        const calculatedIndex = Math.round(scrollLeft / itemWidth);
        currentIndex.value = Math.max(0, Math.min(courseItems.value.length - 3, calculatedIndex));
      } else { // 滚动到最左侧
        currentIndex.value = 0;
      }
    }
  }
}

// 组件挂载时获取路由参数设置标题
onMounted(() => {
  // 检查路由参数中是否有courseTitle
  const courseTitle = route.query.courseTitle
  if (courseTitle) {
    // 设置页面标题
    pageTitle.value = courseTitle
  }
  // 获取当前类型ID
  typeId.value = route.query.typeId
  // 保存原始的课程ID和标题，返回时使用
  originalCourseId.value = route.query.originalCourseId
  originalCourseTitle.value = route.query.originalCourseTitle
  // 获取到topicId后，再获取课程列表getBlocklyByTypeId接口
  if (typeId.value) {
    getBlocklyByTypeId(typeId.value).then(res => {
      if (res && res.data && Array.isArray(res.data)) {
        console.log(res);
        
        // 保存原始API返回的数据
        resData.value = res.data;
        // 创建图片映射，根据bcLabel显示对应图片
        const imageMap = {
          '1': explanation,
          '2': practice,
          '3': summary
        }
        // 遍历接口返回的数据，设置课程项
        res.data.forEach((item, index) => {
          // 每个课程项都对应位置样式和图片
          const positionIndex = (index % 3) + 1
          const image = imageMap[item.bcLabel]; // 根据bcLabel获取图片
          courseItems.value.push({
            id: item.id,
            title: item.bcName,
            image: image,
            contentType: item.bcContentType,
            progress: item.progress 
          })
        })
      }
    })
  }
})

// 处理课程项点击事件
const handleCourseItemClick = (item) => {
  // 如果在拖动过程中，则不触发点击事件
  if (hasMoved.value) return
  if (item.contentType === 'video' || item.contentType === 'blockly') {
    showVideo.value = true
    // 查找并保存完整的课程数据
    const fullCourseData = resData.value.find(course => course.id === item.id)
    if (fullCourseData) {
      selectedCourseData.value = fullCourseData
      selectedCourseData.value.ztId = originalCourseId.value
    }
  }
}

// 返回编程课列表
const goBackIndex = () => {
  // 隐藏视频和游戏界面
  showVideo.value = false
  // 返回时携带原始的课程参数，使用categoryId保持与ProgrammingList.vue中参数名一致
  router.push({
    path: '/programminglist',
    query: {
      categoryId: originalCourseId.value,
      courseTitle: originalCourseTitle.value
    }
  })
}
</script>

<style scoped lang="scss">
@use 'sass:math';
// 定义rpx转换函数
@function rpx($px) {
  @return math.div($px, 750) * 100vw;
}
.programming-content{
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-image: url('@/assets/programming/list_bg03.png');
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
  display: flex;
  flex-direction: column;
  user-select: none; /* 禁止文本选择 */
}

.top-box {
  height: 20%;
  display: flex;
}

.top-left-box,
.top-right-box {
  flex: 1;
  height: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.top-center-box {
  flex: 2;
  display: flex;
  align-items: center;
  justify-content: center;
}

.top-center-inner-box{
  width: 100%;
  height: 100%;
  background-image: url('@/assets/programming/list_title.png');
  background-size: 70%; 
    background-repeat: no-repeat;
    background-position: center center; /* 背景图垂直水平居中 */
    display: flex; 
    align-items: center; /* 垂直居中 */
    justify-content: center; /* 水平居中 */
    cursor: pointer;
    position: relative; /* 相对定位 */
   span{
        font-size: rpx(16);
        color: white;
        position: relative;
        z-index: 1; /* 确保文字在背景图上方 */
        display: flex;
        align-items: center;
        justify-content: center;
        padding-bottom: rpx(5);
    }
  }

.top-left-inner-box{
  display: flex;
  align-items: center; /* 垂直居中对齐 */
  width: 100%;
  height: 100%;
  .left-content-wrapper{
    display: flex;
    align-items: center; /* 保持内部元素垂直居中 */
  }
  .left-icon{
    font-size: rpx(14);
    color: white;
    padding-left: rpx(20);
    cursor: pointer;
  }
  .left-text{
    font-size: rpx(14);
    color: white;
    padding-left: rpx(10);
    cursor: pointer;
  }
}

.top-right-inner-box {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: flex-end;
  align-items: center;
  padding-right: rpx(20);
  .course-info-box {
    width: rpx(60);
    height: rpx(20);
    background-color: rgb(255, 255, 255);
    border-radius: rpx(15);
    display: flex;
    align-items: center;
    justify-content: center;
    color: #45300b;
    font-size: rpx(10);
    cursor: pointer;
  }
}

.lower-box {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
}

.content-box {
  width: 100%;
  min-width: rpx(660); /* 最小宽度 */
  height: 100%;
  overflow-x: auto; /* 水平滚动条 */
  overflow-y: hidden; /* 取消上下滚动 */
  white-space: nowrap; /* 防止元素换行 */
  scroll-behavior: smooth; /* 平滑滚动效果 */
  -webkit-overflow-scrolling: touch; /* 触摸设备支持 */
  position: relative;
  flex: 1;
  cursor: grab; /* 显示可抓取图标 */
  z-index: 2;
  padding: 0 rpx(30);
  /* 设置背景图  */
  background-image: url('@/assets/programming/track01.png');
  background-size: rpx(1360) rpx(350); /* 使用固定宽度,背景图大小一致 */
  background-position: left calc(-1 * rpx(50));
  background-repeat: no-repeat;
  background-attachment: local; /* 背景图跟内容一起滚动 */
}

/* 鼠标按下时的光标样式 */
.content-box:active {
  cursor: grabbing;
}

/* 隐藏滚动条但保持滚动功能 */
.content-box::-webkit-scrollbar {
  display: none;
}

.content-box {
  -ms-overflow-style: none;
  scrollbar-width: none;
}

.slide-item {
  width: rpx(140); /* 设置固定宽度 */
  height: rpx(120); /* 高度设置 */
  margin: rpx(80) rpx(35);
  border-radius: rpx(40);
  background-color: rgba(255, 255, 255);
  display: inline-flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 rpx(5) rpx(10) rgba(0, 0, 0, 0.2);
  transition: transform 0.3s ease;
  cursor: pointer;
  z-index: 2; /* 内容在背景图上方 */
  vertical-align: middle;
  position: relative;
}
/* 奇数项在上层 */
.slide-item:nth-child(odd) {
  transform: translateY(-50%);
}
/* 偶数项在下层 */
.slide-item:nth-child(even) {
  transform: translateY(50%);
}
/* 鼠标悬停放大效果 - 在保持原有垂直位置的基础上放大 */
.slide-item:nth-child(odd):hover {
  transform: translateY(-50%) scale(1.1);
  z-index: 10;
}

.slide-item:nth-child(even):hover {
  transform: translateY(50%) scale(1.1);
  z-index: 10;
}

/* 内容样式 */
.box-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  width: 100%;
}



/* 鼠标按下时的光标样式 */
.slide-item:active {
  cursor: grabbing;
}
.box-image {
  width: 100%;
  height: 90%;
  object-fit: contain;
}

.box-text {
  width: 100%;
  height: 20%;
  line-height: 20%;
  font-size: rpx(13);
  color: #333;
  text-align: center;
}

/* 星星图标样式 */
.star-group {
  position: absolute;
  top: 100%;
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 3;
}

.star-icon {
  position: relative;
  width: rpx(23);
  height: rpx(23);
  background-size: contain;
  background-repeat: no-repeat;
  background-position: center;
  margin: 0 rpx(0);
}

/* 轮播图按钮样式 */
.carousel-btn {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  width: rpx(30);
  height: rpx(30);
  background-color: rgba(255, 255, 255, 0.8);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  z-index: 100; /* 提高按钮层级确保始终在最上层 */
  box-shadow: 0 rpx(5) rpx(10) rgba(0, 0, 0, 0.2);
  transition: all 0.3s ease;
  pointer-events: all;
}

.carousel-btn:hover:not(.disabled-btn) {
  background-color: rgba(255, 255, 255, 1);
  transform: translateY(-50%) scale(1.1);
}

.carousel-btn:disabled,
.disabled-btn {
  opacity: 0.5;
  cursor: not-allowed;
  background-color: rgba(200, 200, 200, 0.7);
  box-shadow: none;
}

.disabled-icon {
  color: #ccc !important;
  filter: grayscale(100%);
  opacity: 0.6;
}

.prev-btn {
  left: 1%;
}

.next-btn {
  right: 1%;
}

.btn-icon {
  font-size: rpx(15);
  color: #333;
}
</style>