<template>
    <div class="class-compopnents">
        <!-- 容器用于放置所有课程分类 -->
        <div class="class-container">
            <!-- 循环生成可拖拽的课程分类 -->
            <div
                v-for="(item, index) in classTypeList"
                class="class-type"
                :key="index"
                :style="{ 'background-color': item.color }"
                :draggable="item.draggable"
                @dragstart="onDragStart(index)"
                @dragover.prevent="() => onDragOver(index)"
                @dragend="onDragEnd"
                :class="{ dragging: draggingIndex === index }"
            >
                {{ item.name }}
            </div>
        </div>
        <div class="course-schedule-container">
            <table>
                <tbody>
                    <tr v-for="(item, index) in classScheduleCardList" :key="index">
                        <td
                            v-for="(v, i) in item.courseList"
                            :key="i"
                            :parentIndex="index"
                            @dragstart="e => tdDragStart(index, i, e)"
                            @dragover.prevent="e => tdDragOver(index, i, e)"
                            @dragleave="e => tdDragleave(index, i, e)"
                            @dragend="e => tdDragend(index, i, e)"
                            :draggable="v && v.draggable"
                            :style="{
                                'background-color': v ? v.color : '#fff',
                                width: '150px',
                                cursor: 'grab'
                            }"
                        >
                            <div class="course-name">
                                <span class="title notSelect">
                                    {{ v ? v.name : '' }}
                                </span>
                                <div class="remove" v-if="v" @click.stop="() => remove(index, i)">+</div>
                            </div>
                        </td>
                    </tr>
                </tbody>
            </table>
        </div>
    </div>
</template>

<script lang="ts" setup>
import { ref } from 'vue'

// 定义课程分类数据
const classTypeList = ref([
    { name: 'A1', color: '#8dedfb', draggable: true },
    { name: 'A2', color: '#f1957b', draggable: true },
    { name: 'A3', color: '#f6f1a9', draggable: true },
    { name: 'A4', color: '#8cdb27', draggable: true },
    { name: 'B1', color: '#d3dc28', draggable: true },
    { name: 'B2', color: '#e5b46f', draggable: true },
    { name: 'B3', color: '#656ef9', draggable: true },
    { name: 'B4', color: '#f6efa1', draggable: true }
])

const classScheduleCardList = ref<any>([
    {
        courseList: [null, null]
    },
    {
        courseList: [null, null]
    },
    {
        courseList: [null, null]
    },
    {
        courseList: [null, null]
    },
    {
        courseList: [null, null]
    },
    {
        courseList: [null, null]
    },
    {
        courseList: [null, null]
    },
    {
        courseList: [null, null]
    }
])

// 当前正在拖拽的元素索引
const draggingIndex = ref<number | null>(null)

// 拖拽开始：记录当前拖拽的索引
function onDragStart(index: number) {
    draggingIndex.value = index
}

// 拖拽经过：动态调整拖拽顺序
function onDragOver(targetIndex: number) {
    if (draggingIndex.value !== null && draggingIndex.value !== targetIndex) {
        // 拖拽元素和目标位置互换
        const draggedItem = classTypeList.value[draggingIndex.value]
        classTypeList.value.splice(draggingIndex.value, 1) // 移除拖拽的元素
        classTypeList.value.splice(targetIndex, 0, draggedItem) // 插入到目标位置
        draggingIndex.value = targetIndex // 更新拖拽元素的当前索引
    }
}

// 拖拽结束：清空拖拽状态
function onDragEnd() {
    draggingIndex.value = null
    currentTDinfo.value = null
    processCourseData()
}

// 处理课程数据
function processCourseData() {
    // 拖拽结束后, 将课程表进行处理,添加上 自定义删除的标识,避免其他元素移出后,将其置空
    const list = JSON.parse(JSON.stringify(classScheduleCardList.value))
    list.forEach((item: any) => {
        item.courseList.forEach((v: any) => {
            if (v) v.customDelete = true
        })
    })
    classScheduleCardList.value = list
}

// 拖拽中的 td 元素
const dragingTdInfo = ref<any>(null)
// 移动到的 td 信息
const currentTDinfo = ref<any>(null)

// td 中开始拖拽拖拽
function tdDragStart(parentIndex: number, index: number, e: any) {
    // if (!classScheduleCardList.value[parentIndex].courseList[index]) return
    // const item = JSON.parse(JSON.stringify(classScheduleCardList.value[parentIndex].courseList[index]))
    // item.customDelete = false
    // dragingTdInfo.value = item
    // classScheduleCardList.value[parentIndex].courseList[index] = null
}

// 移动到 td 上触发
function tdDragOver(parentIndex: number, index: number, e: any) {
    currentTDinfo.value = { parentIndex, index }
    const currentTd = classScheduleCardList.value[parentIndex].courseList[index]
    if (draggingIndex.value !== null && !currentTd) {
        const draggedItem = classTypeList.value[draggingIndex.value]
        // 将对应的课程数据 暂时 放入到td中
        classScheduleCardList.value[parentIndex].courseList[index] = draggedItem
    }

    // td 中进行拖拽
    if (dragingTdInfo.value && !currentTd) {
        classScheduleCardList.value[parentIndex].courseList[index] = JSON.parse(JSON.stringify(dragingTdInfo.value))
    }
}

// 课程在 td 上离开
function tdDragleave(parentIndex: number, index: number, event: any) {
    // 检查 relatedTarget 是否在目标元素内
    const relatedTarget = event.relatedTarget as HTMLElement
    const isInside = relatedTarget?.closest('td') === event.currentTarget
    if (!isInside) {
        // 如果存在课程 return ,只有用户删除之后才可以添加新的课程
        // 存在 customDelete 删除属性,只能用户主动删除才可以清空,其余情况 拖拽元素移出就 清空
        const currentTd = classScheduleCardList.value[parentIndex].courseList[index]
        // 从课程类型中拖拽到 td 中
        if (draggingIndex.value !== null && currentTd && !currentTd.customDelete) {
            classScheduleCardList.value[parentIndex].courseList[index] = null
        }

        // td 中进行拖拽
        if (dragingTdInfo.value && !dragingTdInfo.value.customDelete && currentTd && !currentTd.customDelete) {
            classScheduleCardList.value[parentIndex].courseList[index] = null
        }
    }
}

//  td中拖拽课程结束
function tdDragend(parentIndex: number, index: number, e: any) {
    if (currentTDinfo.value == null) return
    const { parentIndex: currentParentIndex, index: currentIndex } = currentTDinfo.value

    const currentTd = classScheduleCardList.value[currentParentIndex].courseList[currentIndex]
    if (!currentTd) return

    const isSameTd = currentParentIndex === parentIndex && currentIndex === index
    const tdHasCourses = classScheduleCardList.value[currentParentIndex].courseList[currentIndex].customDelete
    if (isSameTd || tdHasCourses) {
        classScheduleCardList.value[parentIndex].courseList[index] = JSON.parse(JSON.stringify(dragingTdInfo.value))
    }

    dragingTdInfo.value = null
    currentTDinfo.value = null
    processCourseData()
}

// 删除
function remove(parentIndex: number, index: number) {
    classScheduleCardList.value[parentIndex].courseList[index] = null
}
</script>

<style lang="scss" scoped>
.class-compopnents {
    display: flex;
    justify-content: flex-start;
}
.class-container {
    display: flex;
    flex-direction: column;
    width: 120px;
    margin-right: 20px;
}

.class-type {
    width: 50px;
    padding: 10px 10px;
    border-radius: 10px;
    margin-bottom: 10px;
    text-align: center;
    cursor: grab;

    text-align: center;
    user-select: none; /* 防止拖拽时选中文字 */
    transition: transform 0.2s, background-color 0.2s;

    &:hover {
        transform: scale(1.05); /* 鼠标悬浮时的缩放效果 */
    }
}

/* 正在拖拽的元素样式 */
.dragging {
    opacity: 0.5;
    transform: scale(1.1); /* 拖拽中的缩放效果 */
    //   background-color: #d3d3d3;
}

.class {
    width: 100%;
    height: 100%;
}

.course-schedule-container {
    width: 100%;
    height: 100%;
    text-align: center;
}

table {
    width: 300px;
    border-radius: 10px;
}

.header-tr {
    background-color: #f8f8f8;

    color: #aaa;
}

.notSelect {
    user-select: none;
}
.course-name {
    width: 100%;
    height: 100%;
    position: relative;

    .remove {
        width: 20px;
        height: 20px;
        text-align: center;
        line-height: 20px;
        position: absolute;
        top: -20px;
        right: -20px;
        font-size: 20px;
        transform: rotate(45deg);
        border-radius: 50%;
        border: 1px solid #000;
        cursor: pointer;
    }
}
table,
th,
td {
    border: 1px solid #ccc;
    border-collapse: collapse; /* 消除双边框效果 */
    transition: all 0.3s;
}

th,
td {
    padding: 20px;
}
</style>
