<!-- 编程课列表 -->
<template>
    <div class="programming-content">
      <!-- 标题部分 -->
      <div class="top-box">
        <div class="top-left-box">
          <div class="top-left-inner-box">
            <!-- 左侧返回图标 -->
             <el-icon class="left-icon" @click="goBackIndex"><ArrowLeftBold /></el-icon>
             <span class="left-text">AI编程课</span>
          </div>
        </div>
        <div class="top-center-box">
          <div class="top-center-inner-box" style="background-image: url('./src/assets/programming/list_title.png');">
            <span>{{ pageTitle }}</span>
          </div>
        </div>
        <div class="top-right-box">
          <div class="top-right-inner-box"></div>
        </div>
      </div>

        <!-- 编程部分 -->
         <div class="middle-wrapper">
          <!-- 左切换按钮 -->
          <div 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="middle-box"
              ref="middleBox"
              @mousedown="handleMouseDown"
              @mousemove="handleMouseMove"
              @mouseup="handleMouseUp"
              @mouseleave="handleMouseLeave"
            >
              <div
                v-for="(courseType, index) in specificCourses"
                :key="index"
                class="middle-inner-box"
                @click="goToProgrammingList(courseType, index)"
              >
                <div class="new-white-box"
                     :class="{ 'active': activeButton === index, 'disabled': courseType.isDisabled }"
                     :style="{ '--lock-image': `url(${lockImage})` }"
                     @click="goToProgrammingList(courseType, index)">
                    <!-- 列表封面图 -->
                  <div class="bg-image-container" :style="{ backgroundImage: `url(${courseType.bgImage})` }">
                    <!-- 星星图标 -->
                    <div
                      v-if="!courseType.isDisabled"
                      v-for="starIndex in 5"
                      :key="starIndex"
                      class="star-icon"
                      :style="{
                        backgroundImage: `url(${starIndex <= courseType.progress ? star01Image : star02Image})`,
                        left: `${30 + (starIndex - 1) * 30}px`
                      }"
                    ></div>
                  </div>
                  <div class="text-container">
                    <div class="box-title">
                      <span>{{ courseType.title }}</span>
                    </div>
                  </div>
                  <!-- unlock背景图盒子 -->
                  <div class="unlock-box" :style="{ backgroundImage: courseType.isDisabled ? `url(${lockImage})` : courseType.progress > 0 ? `url(${trophyImage})` : `url(${unlockImage})` }"></div>
                </div>
              </div>
            </div>

        <!-- 右切换按钮 -->
        <div class="carousel-btn next-btn" @click="nextSlide" :class="{ 'disabled-btn': currentIndex >= specificCourses.length - 3 }" :disabled="currentIndex >= specificCourses.length - 3">
          <el-icon class="btn-icon" :class="{ 'disabled-icon': currentIndex >= specificCourses.length - 3 }"><ArrowRightBold /></el-icon>
        </div>

         </div>

        <!-- 底部切换按钮 -->
        <div class="bottom-box">
          <div class="line-container">
            <div class="bold-line"></div>
            <div
              v-for="(button, index) in circleButtons"
              :key="index"
              class="circle-button"
              :class="{ 'active': activeButton === index }"
              @click="activeButton = index"
            >
            </div>
          </div>
        </div>
    </div>
</template>

<script setup>
import { ref, reactive, watch, onMounted, onUnmounted } from 'vue'
// 返回图标
import { ArrowLeftBold, ArrowRightBold } from '@element-plus/icons-vue';
// 导入路由
import { useRouter, useRoute } from 'vue-router';
// 获取类型列表
import { getTypeByThemeId } from '@/api/programming/index.js'
// 导入图片
import lockImage from '@/assets/programming/lock.png'
import unlockImage from '@/assets/programming/unlock.png'
import trophyImage from '@/assets/programming/trophy.png'

// 星星图片
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 categoryId = ref('')

// 课程权限
const blocklyDataScope = ref([])
// 测试账号禁用视频
const isDisabled = ref(false)

// 返回上一页
const goBackIndex = () => {
  router.push('/programming')
}

// 定义课程数据
const specificCourses = reactive([])

// 当前激活的按钮索引
const activeButton = ref(0)
// 轮播图当前索引
const currentIndex = ref(0)

// 在获取到categoryId后再调用获取类型列表getTypeByThemeId接口
const fetchTopicList = () => {
  if (categoryId.value) {
    getTypeByThemeId(categoryId.value).then(res => {
      console.log(categoryId.value, res);
      // 更新课程数据，使用接口返回的数据
      if (res && res.data && Array.isArray(res.data)) {
        // 清空原有数据
        specificCourses.splice(0, specificCourses.length);
        res.data.forEach(item => {

          specificCourses.push({
            id: item.id,
            title: item.ctType,
            bgImage: item.ctTypeImage,
            progress: item.progress,
            isDisabled: disableBlockly(item.id)
          });
        });
        // 更新圆形按钮数据
        circleButtons.splice(0, circleButtons.length);
        specificCourses.forEach((_, index) => {
          circleButtons.push({ text: String(index + 1) });
        });
        // 重置激活按钮索引，默认选中第一项
        activeButton.value = 0;
      }
    })
  }
}


// 定义圆形按钮数据(根据课程数量动态生成)
const circleButtons = reactive(specificCourses.map((_, index) => ({ text: String(index + 1) })))

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

// 拖动相关变量
const isDragging = ref(false)
const startX = ref(0)
const scrollLeft = ref(0)

// 鼠标按下事件处理函数
const handleMouseDown = (e) => {
  isDragging.value = true
  startX.value = e.pageX - middleBox.value.offsetLeft
  scrollLeft.value = middleBox.value.scrollLeft
}

// 鼠标移动事件处理函数
const handleMouseMove = (e) => {
  if (!isDragging.value) return
  e.preventDefault()
  const x = e.pageX - middleBox.value.offsetLeft
  const walk = (x - startX.value) * 2 // 滚动速度
  middleBox.value.scrollLeft = scrollLeft.value - walk
}

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

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

// 上一页
const prevSlide = () => {
  if (currentIndex.value > 0) {
    currentIndex.value = Math.max(0, currentIndex.value - 3)
    // 滚动到对应位置
    if (middleBox.value) {
      const scrollAmount = middleBox.value.clientWidth * 0.75
      middleBox.value.scrollTo({
        left: Math.max(0, middleBox.value.scrollLeft - scrollAmount),
        behavior: 'smooth'
      })
    }
  }
}

// 下一页
const nextSlide = () => {
  if (currentIndex.value < specificCourses.length - 3) {
    currentIndex.value = Math.min(specificCourses.length - 3, currentIndex.value + 3)
    // 滚动到对应位置
    if (middleBox.value) {
      const scrollAmount = middleBox.value.clientWidth * 0.75
      middleBox.value.scrollTo({
        left: middleBox.value.scrollLeft + scrollAmount,
        behavior: 'smooth'
      })
    }
  }
}

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

// 组件挂载时获取路由参数设置标题和课程ID
onMounted(() => {

  if (localStorage.getItem("blocklyDataScope")) {
    blocklyDataScope.value = localStorage.getItem("blocklyDataScope").split(",");
  }

  const title = route.query.courseTitle
  if (title) {
    pageTitle.value = title
  }

  const id = route.query.categoryId
  if (id) {
    categoryId.value = id
    // 获取到categoryId后调用getTypeByThemeId接口
    fetchTopicList()
  }
})


// 跳转到课程详情页面
const goToProgrammingList = (courseType, index) => {
  // 检查是否禁用
  if (courseType.isDisabled) {
    Message().notifyWarning('您的账号并未开放此课程！', true)
    return
  }

  // 设置当前选中项
  activeButton.value = index;
  // 跳转ProgrammingCourset页面，并传递课程信息作为参数
  router.push({
    path: '/programmingCourset',
    query: {
      courseTitle: courseType.title,
      courseIndex: index,
      typeId: courseType.id, // 当前类型的id，避免与课程ID混淆
      originalCourseId: categoryId.value, // 原始的课程ID
      originalCourseTitle: pageTitle.value // 原始的课程标题
    }
  })
}

// 禁用视频
const disableBlockly = (blocklyId = categoryId.value) => {

  // 未配置课程权限，不禁用视频
  if (!blocklyDataScope.value || blocklyDataScope.value.length === 0) {
    return false
  }

  //配置了课程权限，且视频id不在权限列表中
  isDisabled.value = !blocklyDataScope.value.some(item => Number(item) === blocklyId)
  // if (isDisabled.value) {
  //   Message().notifyWarning('您的账号并未开放此课程！', true)
  //   return isDisabled.value;
  // }

  return isDisabled.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_bg02.png');
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
  display: flex;
  flex-direction: column;
}
.top-box {
  height: 20%;
  display: flex;
}
.top-left-box,
.top-right-box {
  flex: 1;
  height: 50%;
  border-radius: rpx(5);
  display: flex;
  align-items: center;
  justify-content: center;
}

.top-center-box {
  flex: 2;
  border-radius: rpx(5);
  display: flex;
  align-items: center;
  justify-content: center;
}
.top-left-inner-box,
.top-center-inner-box,
.top-right-inner-box {
  width: 100%;
  height: 100%;
}
.top-center-inner-box{
    background-size: 70%;
    background-position: 50% 80%;
    background-repeat: no-repeat;
    display: flex; /* 使用flex布局 */
    align-items: center; /* 垂直居中 */
    justify-content: center; /* 水平居中 */
    span{
        font-size: rpx(17);
        color: white;
    }
  }
.top-left-inner-box{
  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;
  }
}

.middle-wrapper {
  height: 60%;
  overflow: hidden; /* 溢出隐藏 */
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
}

.middle-box {
  min-width: rpx(660); /* 固定最小宽度 */
  height: 100%;
  margin: 0 rpx(50);
  overflow-x: auto; /* 水平滚动条 */
  overflow-y: hidden; /* 取消上下滚动 */
  white-space: nowrap; /* 防止元素换行 */
  scroll-behavior: smooth; /* 平滑滚动效果 */
  -webkit-overflow-scrolling: touch; /* 触摸设备支持 */
  position: relative;
  flex: 1;
}

.middle-inner-box{
  width: rpx(130); /* 设置固定宽度 */
  height: 100%; /* 设置固定高度 */
  position: relative;
  cursor: pointer; /* 显示可抓取图标 */
  user-select: none; /* 禁止文本选择 */
  display: inline-block; /* 水平排列 */
  margin-right: rpx(20);
  margin-left: rpx(15);
  vertical-align: middle; /* 垂直居中对齐 */
}

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

/* 隐藏滚动条 */
.middle-box::-webkit-scrollbar {
  height: rpx(0);
}


.new-white-box {
  width: 100%;
  height: 65%;
  margin-top: rpx(20);
  background-color: white;
  border-radius: rpx(15);
  display: flex;
  flex-direction: column;
  transition: all 0.3s ease; /* 过渡效果 */
  position: relative;
}

/* 小三角效果 */
.new-white-box::after {
  content: '';
  position: absolute;
  bottom: -rpx(8);
  left: 50.5%;
  transform: translateX(-50%);
  width: 0;
  height: 0;
  top: rpx(150);
  border-left: rpx(10) solid transparent;
  border-right: rpx(10) solid transparent;
  border-top: rpx(10) solid white;
}

/* 鼠标悬浮/选中时的放大效果 */
.new-white-box:hover:not(.disabled),
.new-white-box.active:not(.disabled) {
  transform: scale(1.1); /* 放大1.1倍 */
  z-index: 10; /* 确保放大时在顶层显示 */
  border: rpx(5) solid #D0D7F7; /* 边框效果 */
  box-shadow: 0 0 rpx(10) rgba(0, 0, 0, 0.5);
}
/* 禁用状态样式 */
.new-white-box.disabled {
  cursor: not-allowed;
  filter: grayscale(0%); /* 改为100%黑白色 */
  pointer-events: none;
  position: relative;
}

/* 禁用状态下的文字颜色 */
.new-white-box.disabled .box-title {
  color: #676666;
}

/* 禁用状态下的遮挡层 */
.new-white-box.disabled::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.3);
  background-image: var(--lock-image);
  background-size: 40%;
  background-position: center;
  background-repeat: no-repeat;
  border-radius: rpx(15);
  z-index: 2;
}
/* 小三角效果 */
.new-white-box.disabled::after {
  top: rpx(150);
  opacity: 0.5;
}

/* 背景图容器 */
.bg-image-container {
  width: 100%;
  height: 85%;
  background-size: 105%; 
  background-position: center;
  background-repeat: no-repeat;
  position: relative;
}

/* star图标样式 */
.star-icon {
  position: absolute;
  top: rpx(10);
  width: rpx(20);
  height: rpx(20);
  background-size: contain;
  background-position: center;
  background-repeat: no-repeat;
  z-index: 1;
}

/* 文字容器 */
.text-container {
  width: 100%;
  height: 15%; 
  display: flex;
  line-height: rpx(10);
  justify-content: center;
}

/* 标题样式 */
.box-title {
  color: #333;
  text-align: center;
  font-size: rpx(11); 
  color: #45300b;
}

/* unlock盒子样式 */
.unlock-box {
  position: absolute;
  width: 100%;
  height: 30%;
  background-size: contain;
  background-position: center;
  background-repeat: no-repeat;
  left: 51%;
  transform: translateX(-50%);
  top: rpx(148);
  z-index: 5;
}
.bottom-box {
  height: 20%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.line-container {
  width: 65%;
  position: relative;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.bold-line {
  position: absolute;
  width: 100%;
  height: rpx(5);
  background-color: rgba(37, 115, 188, 0.5);
  border-radius: rpx(3);
}

.circle-button {
  width: rpx(7);
  height: rpx(7);
  border-radius: 50%;
  background-color: rgba(255, 255, 255);
  border: rpx(1) solid #00c1fc;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.3s ease;
  z-index: 1;
}
.circle-button:hover {
  background-color: white;
  transform: scale(1.5); // 放大效果
}
.circle-button.active {
  background-color: #f9df04;
  border: rpx(1.5) solid #00c1fc;
  color: white;
  transform: scale(2);
  box-shadow: 0 0 rpx(10) rgba(0, 0, 0, 0.5);
}

/* 轮播图按钮样式 */
.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: 10;
  box-shadow: 0 rpx(5) rpx(10) rgba(0, 0, 0, 0.2);
  transition: all 0.3s ease;
}

.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: 2%;
}

.next-btn {
  right: 2%;
}

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

</style>