<!-- 编程课列表内容 -->
<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 
            class="content-box"
            ref="contentBox"
            @mousedown="handleMouseDown"
            @mousemove="handleMouseMove"
            @mouseup="handleMouseUp"
            @mouseleave="handleMouseLeave"
            @scroll="handleScroll"
          >
          <!-- 动态渲染课程内容 -->
          <div 
            v-for="(item, index) in courseItems" 
            :key="item.id"
            :class="['slide-item', { active: activeButton === index }]"
            :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>

    <!-- 底部切换按钮 -->
    <div v-if="!showVideo && courseItems.length > 3" class="bottom-box">
      <!-- 左切换按钮 -->
      <div class="carousel-btn prev-btn" @click="prevSlide" :class="{ 'disabled-btn': activeButton === 0 }" :disabled="activeButton === 0">
        <img :src="leftbtn" alt="左按钮" class="btn-image" :class="{ 'disabled-icon': activeButton === 0 }" />
      </div>
      <!-- 进度条滑块 -->
      <div class="line-container" v-if="courseItems.length > 0">
        <el-slider v-model="activeButton" :max="courseItems.length - 1" :step="1" :show-tooltip="false" />
      </div>
      <!-- 右切换按钮 -->
      <div class="carousel-btn next-btn" @click="nextSlide" :class="{ 'disabled-btn': activeButton >= courseItems.length - 1 }" :disabled="activeButton >= courseItems.length - 1">
        <img :src="rightbtn" alt="右按钮" class="btn-image" :class="{ 'disabled-icon': activeButton >= courseItems.length - 1 }" />
      </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, watch } 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 leftbtn from '@/assets/programming/leftbtn.png'
import rightbtn from '@/assets/programming/rightbtn.png'

import Interface from './Interface.vue'

// 星星图片
import star02Image from '@/assets/programming/star02.png'
import star01Image from '@/assets/programming/star01.png'
import {Message} from "@/utils/message/Message.js";


// 获取路由实例
const router = useRouter()
const route = useRoute()
// 页面标题
const pageTitle = ref('')
// 保存原始的课程ID和标题
const originalCourseId = ref('')
const originalCourseTitle = ref('')
const isDisabled = ref(false) // 课程是否只读
// 类型ID（从ProgrammingList页面传递过来）
const typeId = ref('')
// 控制视频界面显示
const showVideo = ref(false) 
// 动态课程项数据
const courseItems = ref([])
// 当前选中的课程数据
const selectedCourseData = ref(null)
// 保存原始API返回的数据
const resData = ref([])
// 当前激活的按钮索引
const activeButton = 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 (activeButton.value > 0) {
    activeButton.value -= 1;
  }
}

// 下一页
const nextSlide = () => {
  if (activeButton.value < courseItems.value.length - 1) {
    activeButton.value += 1;
  }
}

// 鼠标按下事件处理函数
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 = () => {}

// 监听activeButton变化，自动滚动到中间位置
watch(activeButton, (newIndex) => {
  if (contentBox.value && newIndex !== -1) {
    // 找到对应的课程卡片元素
    const courseElement = contentBox.value.querySelector(`.slide-item:nth-child(${newIndex + 1})`);
    if (courseElement) {
      // 计算滚动位置，选中的卡片居中
      const containerWidth = contentBox.value.clientWidth;
      const elementLeft = courseElement.offsetLeft;
      const elementWidth = courseElement.offsetWidth;
      // 计算居中位置
      const scrollPosition = elementLeft - (containerWidth / 2) + (elementWidth / 2);
      // 平滑滚动到计算的位置
      contentBox.value.scrollTo({
        left: scrollPosition,
        behavior: 'smooth'
      });
    }
  }
});

// 提取课程数据获取和处理逻辑为单独函数
const fetchCourseData = () => {
  if (typeId.value) {
    getBlocklyByTypeId(typeId.value).then(res => {
      if (res && res.data && Array.isArray(res.data)) {

        // 保存原始API返回的数据
        resData.value = res.data;
        resData.value.forEach(item => {
          item.isDisabled = isDisabled.value
        })
        // 创建图片映射，根据bcLabel显示对应图片
        const imageMap = {
          '1': explanation,
          '2': practice,
          '3': summary
        }
        // 清空旧的课程项
        courseItems.value = [];
        // 遍历接口返回的数据，设置课程项
        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, // 进度
            isDisabled: isDisabled.value // 保存bcLabel用于图片映射
          })
        })
      }
    })
  }
}

// 组件挂载时获取路由参数设置标题
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
  isDisabled.value = Boolean(isDisabled.value)

  // 获取到topicId后，调用函数获取课程列表
  fetchCourseData();
})

// 处理课程项点击事件
const handleCourseItemClick = (item) => {
  // 如果在拖动过程中，则不触发点击事件
  if (hasMoved.value) return

  // 如果是只读模式，不允许点击
  if (isDisabled.value) {
    Message().notifyWarning('您的账号并未开放此课程！', true)
    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
      selectedCourseData.value.isDisabled = isDisabled.value
    }
  }
}

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

// 监听showVideo状态变化，当从true变为false时重新获取课程数据
watch(showVideo, (newValue, oldValue) => {
  if (oldValue === true && newValue === false) {
    // 当视频界面关闭时，调用函数重新获取最新的课程数据
    fetchCourseData();
  }
})
</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 {
  height: 75%;
  overflow: hidden; /* 溢出隐藏 */
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-top: rpx(-25);
}

.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(130); /* 设置固定宽度 */
  height: rpx(110); /* 高度设置 */
  margin: rpx(85) rpx(40);
  border-radius: rpx(35);
  background-color: rgba(255, 255, 255);
  display: inline-flex;
  align-items: center;
  justify-content: center;
  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;
}
/* 默认选中第一个元素的样式 */
/* 奇数项选中样式 */
.slide-item:nth-child(odd).active {
  transform: translateY(-50%) scale(1.1);
  z-index: 10;
  box-shadow: 0 rpx(8) rpx(15) rgba(0, 0, 0, 0.3);
}

/* 偶数项选中样式 */
.slide-item:nth-child(even).active {
  transform: translateY(50%) scale(1.1);
  z-index: 10;
  box-shadow: 0 rpx(8) rpx(15) rgba(0, 0, 0, 0.3);
}

/* 内容样式 */
.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 {
  width: rpx(40);
  height: rpx(40);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  z-index: 10;
  transition: all 0.3s ease;
}

.carousel-btn:hover:not(.disabled-btn) {
 transform: scale(1.1);
}

.carousel-btn:disabled,
.disabled-btn {
  cursor: not-allowed;
  box-shadow: none;
}

.disabled-icon {
  opacity: 0.5;
}

.prev-btn {
  margin-right: rpx(5);
}

.next-btn {
  margin-left: rpx(5);
}

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

/* 底部切换按钮样式 */
.bottom-box {
  height: 15%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.bottom-box .carousel-btn {
  position: relative;
  top: 0;
  transform: none;
  width: rpx(40);
  height: rpx(40);
  background-color: transparent;
  box-shadow: none;
}

.bottom-box .carousel-btn:hover:not(.disabled-btn) {
  transform: none;
}

.line-container {
  width: 70%; /* 滑块宽度 */
  position: relative;
  display: flex;
  align-items: center;
  justify-content: space-between;
  /* el-slider滑块样式 */
  :deep(.el-slider__runway) {
    height: rpx(10); /* 滑块轨道高度 */
    background-color: rgba(228, 227, 254,0.3); /* 轨道背景色 */
    border-radius: rpx(10);
  }
  
  :deep(.el-slider__bar) {
    height: rpx(10); /* 滑块激活部分高度 */
    background-color: #2598c2; /* 激活部分颜色为蓝色 */
    border-radius: rpx(10);
  }
  
  :deep(.el-slider__button) {
    width: rpx(35); 
    height: rpx(35); 
    margin-top: rpx(-5);
    margin-left: rpx(-10);
    border: none; /* 移除边框 */
    background-image: url('@/assets/programming/xiaozhi.png'); 
    background-size: 100%; /* 背景图片完全覆盖按钮 */
    background-position: center; /* 背景图片居中 */
    background-repeat: no-repeat; /* 背景图片不重复 */
    background-color: transparent; /* 透明背景 */
    &:hover {
      transform: scale(1.1); /* 悬停时放大效果 */
    }
    &.hover,
    &:active {
      transform: scale(1.1); /* 激活时放大效果 */
      box-shadow: none; /* 移除阴影效果 */
    }
  }
  
  :deep(.el-slider__stop) {
    width: rpx(10); /* 停止点大小 */
    height: rpx(10); /* 停止点大小 */
    background-color: white; /* 停止点颜色 */
    opacity: 0.2;
  }
}

.btn-image {
  width: rpx(40);
  height: rpx(40);
  object-fit: contain;
}
</style>