<!-- 实验课程 -->
<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>{{ coursesTitle }}</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="middleBox"
            :class="{ 'short-bg': courseList.length <= 3 }" 
            @mousedown="handleMouseDown"
            @mousemove="handleMouseMove"
            @mouseup="handleMouseUp"
            @mouseleave="handleMouseLeave"
            @scroll="handleScroll"
          >
          <!-- 动态渲染课程内容 -->
          <div 
            v-for="(item, index) in courseList" 
            :key="item.id"
            :class="['slide-item', { 'three-items': courseList.length <= 3 }, { active: activeButton === index }]"
            :style="courseList.length <= 3 ? { float: 'left' } : {}"
            @click="!isDragging && !hasMoved && handleCourseItemClick(item, index)"
            v-memo="[activeButton === index, item.isDisabled]"
          >
            <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 && courseList.length > 3" class="bottom-box">
      <!-- 左切换按钮 -->
      <div class="carousel-btn prev-btn" @click="prevExperimentalCourses" :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="courseList.length > 0">
        <el-slider v-model="activeButton" :max="courseList.length - 1" :step="1" :show-tooltip="false" />
      </div>
      <!-- 右切换按钮 -->
      <div class="carousel-btn next-btn" @click="nextExperimentalCourses" :class="{ 'disabled-btn': activeButton >= courseList.length - 1 }" :disabled="activeButton >= courseList.length - 1">
        <img :src="rightbtn" alt="右按钮" class="btn-image" :class="{ 'disabled-icon': activeButton >= courseList.length - 1 }" />
      </div>
    </div>
    
    <!-- 视频和编程界面 -->
    <ExperimentalInterface v-if="showVideo" :courseData="selectedCourseData" :courseList="resData" @closeVideo="showVideo = false" />

  </div>
</template>

<script setup>
// 返回图标
import { ArrowLeftBold } from '@element-plus/icons-vue';
import {ref, onMounted,computed , onUnmounted, watch, nextTick} from 'vue';
// 导入路由
import { useRouter } from 'vue-router';
// 导入按钮图片
import leftbtn from '@/assets/programming/leftbtn.png'
import rightbtn from '@/assets/programming/rightbtn.png'
import ExperimentalInterface from './ExperimentalInterface.vue'
// 星星图片
import star02Image from '@/assets/programming/star02.png'
import star01Image from '@/assets/programming/star01.png'
import trackLongImage from '@/assets/programming/track-long.png'
import trackShortImage from '@/assets/programming/track.png'
import {Message} from "@/utils/message/Message.js";
// 根据ID获取实验室课程列表接口
import { getCourseByTypeId } from '@/api/laboratory/index.js'

import {DICT_TYPE} from "@/utils/dictUtils.js";
import {scrollToCenter} from "@/utils/pageCss/scrollToCenter.js";

// 常量配置
const CONSTANTS = {
  SCROLL_SPEED: 2,
  ANIMATION_DURATION: '0.3s',
  // 根据acLabel获取图片
  IMAGE_MAP: { 
    '1': "",
    '2': "",
    '3': ""
  }
}

// 获取路由实例
const router = useRouter()
// 页面标题
const coursesTitle = ref('')
// 保存原始的课程ID和标题
const originalCourseId = ref('')
const originalCourseTitle = ref('')
const isDisabled = ref(false) // 课程是否只读
// 类型ID（从ExperimentType页面传递过来）
const typeId = ref('')
// 控制视频界面显示
const showVideo = ref(false) 
// 动态课程项数据
const courseList = ref([])
// 当前选中的课程数据
const selectedCourseData = ref(null)
// 保存原始API返回的数据
const resData = ref([])
// 选中的按钮索引存储键名
const blocklyActiveButton = ref("aiCourseSectionActiveButton")
// 当前激活的按钮索引
const activeButton = ref(Number(localStorage.getItem(blocklyActiveButton.value)) || 0)

// 根据课程项数量动态计算背景图
const backgroundImage = computed(() => {
  return courseList.value.length <= 3 
    ? `url(${trackShortImage})`
    : `url(${trackLongImage})`;
})

// 拖动相关变量
const isDragging = ref(false)
const startX = ref(0)
const scrollLeft = ref(0)
const hasMoved = ref(false) // 标记是否发生了移动
// 获取contentBox元素的引用
const middleBox = ref(null)

// 获取星星数量，默认返回1个星星
const getStarCount = () => 1

// 上一节课程
const prevExperimentalCourses = () => {
  if (activeButton.value > 0) {
    activeButton.value -= 1;
  }
}

// 下一节课程
const nextExperimentalCourses = () => {
  if (activeButton.value < courseList.value.length - 1) {
    activeButton.value += 1;
  }
}

// 鼠标按下事件处理函数
const handleMouseDown = (e) => {
  // 拖拽状态为true
  isDragging.value = true
  // 初始化移动状态为false
  hasMoved.value = false
  // 计算鼠标在容器内的相对X坐标的位置  e.pageX鼠标相对于整个页面的X坐标
  if (middleBox.value) {
    startX.value = e.pageX - middleBox.value.offsetLeft
    scrollLeft.value = middleBox.value.scrollLeft
  }
}

// 鼠标移动事件处理函数
const handleMouseMove = (e) => {
  if (!isDragging.value || !middleBox.value) return
  // 阻止默认行为，防止文本选择等与拖拽冲突
  e.preventDefault()
  // 标记已发生移动
  hasMoved.value = true
  // 优化滚动
  requestAnimationFrame(() => {
    // 计算新的滚动位置
    const x = e.pageX - middleBox.value.offsetLeft
    const walk = (x - startX.value) * CONSTANTS.SCROLL_SPEED // 滚动速度
    middleBox.value.scrollLeft = scrollLeft.value - walk
  })
}

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

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

// 滚动事件处理函数
const handleScroll = () => {}

// 监听activeButton变化，自动滚动到中间位置
watch(activeButton, () => {
  middleBoxWidth()
});

// 中间卡片居中显示和放大效果
const middleBoxWidth = ()=> {
  scrollToCenter(middleBox.value, activeButton.value, {
    selector: '.slide-item'
  });
}

// 获取课程数据函数优化
const fetchCourseData = async () => {
  if (typeId.value) {
    try {
      const res = await getCourseByTypeId(typeId.value)
      if (res && res.data && Array.isArray(res.data)) {
        // 使用局部变量处理数据，减少响应式对象的频繁修改
        const newResData = [...res.data];
        newResData.forEach(item => {
          item.isDisabled = isDisabled.value
        });

        // 批量创建课程项
        const newCourseItems = newResData.map((item, index) => {
          const image = CONSTANTS.IMAGE_MAP[item.acLabel]; // 根据acLabel获取图片
          return {
            id: item.id,
            title: item.acName,
            image: image,
            contentType: item.acContentType,
            progress: item.progress, // 进度
            isDisabled: isDisabled.value // 保存acLabel用于图片映射
          };
        });
        
        // 一次性更新响应式数据，减少DOM更新次数
        resData.value = newResData;
        courseList.value = newCourseItems;

        // 数据加载完成后，等待下一个DOM更新周期，然后调用middleBoxWidth
        await nextTick(() => {
          middleBoxWidth();
        });

      }
    } catch (error) {
      console.error('Failed to fetch course data:', error)
      Message().notifyError('获取课程数据失败，请重试', true)
    }
  }
}

// 组件挂载时获取路由参数设置标题
onMounted(() => {
  // 从history.state中获取参数
  const courseTitle = history.state?.typeTitle;
  if (courseTitle) {
    coursesTitle.value = courseTitle;
  }
  
  // 一次性设置多个响应式数据
  typeId.value = history.state?.typeId;
  originalCourseId.value = history.state?.originalThemeId;
  originalCourseTitle.value = history.state?.originalThemeTitle;
  isDisabled.value = Boolean(history.state?.isDisabled);

  // 调用函数获取课程列表
  fetchCourseData();


  //课程小节字典
  let menuDictStr = localStorage.getItem(DICT_TYPE.BLOCKLY_COURSE_LABEL);
  let menuDictJson = menuDictStr ? JSON.parse(menuDictStr) : [];
  CONSTANTS.IMAGE_MAP = menuDictJson.reduce((acc, item) => {
    acc[item.value] = item.remark;
    return acc;
  }, {});
});

// 组件卸载时清理
onUnmounted(() => {
  // 清理拖拽状态
  isDragging.value = false;
  hasMoved.value = false;
});

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

  activeButton.value = index
  localStorage.setItem(blocklyActiveButton.value, activeButton.value)

  // 如果是只读模式，不允许点击
  if (isDisabled.value) {
    Message().notifyWarning('您的账号并未开放此课程！', true)
    return;
  }

  // 直接使用item中的信息，避免再次查找
  showVideo.value = true
  selectedCourseData.value = {
    ...resData.value.find(course => course.id === item.id),
    ztId: originalCourseId.value,
    isDisabled: isDisabled.value
  }
}

// 返回编程课列表
const goBackIndex = () => {
  localStorage.removeItem(blocklyActiveButton.value)

  // 隐藏视频和游戏界面
  showVideo.value = false
  // 返回时携带原始的课程参数
  router.push({
    path: '/experiment-type',
    state: {
      themeId: originalCourseId.value,
      themeTitle: originalCourseTitle.value
    }
  })
}

// 监听showVideo状态变化，当从true变为false时重新获取课程数据
watch(showVideo, (newValue, oldValue) => {
  // 使用nextTick确保DOM更新完成后再执行
  if (oldValue === true && newValue === false) {
    setTimeout(() => {
      fetchCourseData();
    }, 0)
  }
})

</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/laboratory/laboratory-bg.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(700); /* 最小宽度 */
  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(0);
  /* 硬件加速 */
  transform: translateZ(0);
  backface-visibility: hidden;
  perspective: 1000px;
  /* 设置背景图  */
  background-image: v-bind(backgroundImage);
  background-size: rpx(1360) rpx(400); /* 固定宽度,背景图大小一致 */
  background-position: left calc(-1 * rpx(80));
  background-repeat: repeat-x;
  background-attachment: local; /* 背景图跟内容一起滚动 */
}

.short-bg {
  background-size: rpx(790) rpx(300);
  background-position: center calc(-1 * rpx(10));
}

/* 鼠标按下时的光标样式 */
.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-top: rpx(80);
  margin-right: rpx(85);
  margin-left: rpx(10);
  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;
  /* 硬件加速 */
  transform: translateZ(0);
  backface-visibility: hidden;
  perspective: 1000px;
}
/* 当只有3个课程项时调整间距 */
.slide-item.three-items {
  margin-right: rpx(70);
  margin-left: rpx(50);
}
/* 奇数项在上层 */
.slide-item:nth-child(odd) {
  transform: translateY(-50%) translateZ(0);
}
/* 偶数项在下层 */
.slide-item:nth-child(even) {
  transform: translateY(50%) translateZ(0);
}
/* 鼠标悬停放大效果 */
  .slide-item:nth-child(odd):hover {
    transform: translateY(-50%) scale(1.05); /* 减小放大比例 */
    z-index: 10;
    transition: transform 0.2s ease-out; /* 更短更平滑的过渡 */
  }

  .slide-item:nth-child(even):hover {
    transform: translateY(50%) scale(1.05); /* 减小放大比例 */
    z-index: 10;
    transition: transform 0.2s ease-out; /* 更短更平滑的过渡 */
  }
  /* 默认选中第一个元素的样式 */
  /* 奇数项选中样式 */
  .slide-item:nth-child(odd).active {
    transform: translateY(-50%) scale(1.05); /* 减小放大比例 */
    z-index: 10;
    box-shadow: 0 rpx(5) rpx(10) rgba(0, 0, 0, 0.2);
  }

  /* 偶数项选中样式 */
  .slide-item:nth-child(even).active {
    transform: translateY(50%) scale(1.05); /* 减小放大比例 */
    z-index: 10;
    box-shadow: 0 rpx(5) rpx(10) rgba(0, 0, 0, 0.2);
  }

/* 内容样式 */
.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>