<template>
    <div class="container-drag">
        <div style="width: 100%;text-align:center;margin: 10px;">
            <a-button type="primary" class="random-button" @click="randomDragOrder">随机顺序</a-button>
        </div>
        <div class="container-drag-box">
            <div class="container-drag-left">
                <!-- <> -->
                <div v-for="item in state.dragConfig.sourceArray" :key="item.id" class="drag-item-box"
                    :id="state.dragConfig.sourceDomPrefix + '-' + item.id">
                    <div class="drag-item" draggable="true" :id="state.dragConfig.dragDomPrefix + '-' + item.id">
                        <!-- 拖拽对象 data-order 校验排序用 -->
                        <img :src="item.src" width="280" height="280" :data-order="item.id" />
                    </div>
                </div>
            </div>

            <div class="container-drag-right" id="target-box-id">
                <!-- 目标对象 data-order 校验排序用-->
                <div v-for="item in state.dragConfig.sourceArray" :key="item" class="target-item-box dropzone"
                    :id="state.dragConfig.targetDomPrefix + '-' + item.id" :data-order="item.id">

                </div>
            </div>
        </div>
        <div style="width: 100%;text-align:center">
            <a-button type="primary" @click="confirmImg">
                确定
            </a-button>
        </div>
    </div>
</template>

<script setup>
import { reactive, onMounted } from 'vue'
import { message } from 'ant-design-vue'
const state = reactive({
    dragConfig: {
        sourceDomPrefix: 'source-item',
        targetDomPrefix: 'target-item',
        dragDomPrefix: 'drag-item',
        dragTarget: null,
        sourceImg: '/img/imageSource.png',
        sourceArray: [{
            id: 1,
            src: '/img/image1.png'
        },
        {
            id: 2,
            src: '/img/image2.png'
        },
        {
            id: 3,
            src: '/img/image3.png'
        },
        {
            id: 4,
            src: '/img/image4.png'
        },
        ]
    }
})
// 数组随机顺序
const randomDragOrder = () => {
    const sourceArray = [...state.dragConfig.sourceArray]
    sourceArray.sort(() => Math.random() - 0.5);
    state.dragConfig.sourceArray = sourceArray
}

// 拖拽对象
const drag = (event) => {
    console.log("dragging", event);
}

const dragStart = (event) => {
    // 保存被拖动元素的引用
    state.dragConfig.dragTarget = event.target;
    // 设置为半透明
    event.target.classList.add("dragging");
}

const dragEnd = (event) => {
    // 拖动结束，重置透明度
    event.target.classList.remove("dragging");
}

// 目标对象

const dragOver = (event) => {
    // 阻止默认行为以允许放置
    event.preventDefault();
}

const dragLeave = (event) => {
    // 在可拖动元素离开潜在放置目标元素时重置该目标的背景
    if (event.target.classList.contains("dropzone")) {
        event.target.classList.remove("dragover");
    }
}

const dragEnter = (event) => {
    // 在可拖动元素进入潜在的放置目标时高亮显示该目标
    if (event.target.classList.contains("dropzone")) {
        event.target.classList.add("dragover");
    }
}

const drop = (event) => {
    // 阻止默认行为（会作为某些元素的链接打开）
    event.preventDefault();
    // 将被拖动元素移动到选定的目标元素中
    if (event.target.classList.contains("dropzone")) {
        event.target.classList.remove("dragover");
        // 删除自身
        state.dragConfig.dragTarget.parentNode.removeChild(state.dragConfig.dragTarget);
        // 添加元素
        event.target.appendChild(state.dragConfig.dragTarget);
    }
}

const initDragAction = (sourceElement) => {
    if (!sourceElement) {
        return
    }
    /* 在放置拖拽对象上触发的事件 */
    sourceElement.addEventListener("drag", drag);

    sourceElement.addEventListener("dragstart", dragStart);

    sourceElement.addEventListener("dragend", dragEnd);
}

const initTargetAction = (targetElement) => {
    if (!targetElement) {
        return
    }
    /* 在放置目标对象上触发的事件 */

    targetElement.addEventListener(
        "dragover",
        dragOver,
        false,
    );

    targetElement.addEventListener("dragenter", dragEnter);

    targetElement.addEventListener("dragleave", dragLeave);

    targetElement.addEventListener("drop", drop);
}

// 校验
const confirmImg = () => {
    const rightDom = document.getElementById('target-box-id')
    console.log('rightDom', rightDom)
    const rightDomChildNodes = rightDom.childNodes
    console.log('rightDomChildNodes', rightDomChildNodes)
    if (rightDomChildNodes.length) {
        // childNodes会出现空文本节点
        for (let i = 0, length = rightDomChildNodes.length; i < length; ++i) {
            console.log('childNodes', rightDomChildNodes[i])
            if (rightDomChildNodes[i].nodeType !== 1) {
                // 跳过文本节点
                continue
            }
            else if (rightDomChildNodes[i].hasChildNodes) {
                console.log('childNodes attr', rightDomChildNodes[i])
                const currentDataOrder = rightDomChildNodes[i].getAttribute('data-order')
                const imgDataOrder = rightDomChildNodes[i].getElementsByTagName('img')[0].getAttribute('data-order')
                console.log('currentDataOrder', currentDataOrder)
                console.log('imgDataOrder', imgDataOrder)
                if (currentDataOrder !== imgDataOrder) {
                    return message.warn('拼图位置错误：\t第' + currentDataOrder+'张图片')
                }
            }
            else {
                return message.warn('没有完成拼图，请拖拽图片')
            }
        }
    }
    else {
        return message.warn('没有完成拼图，请拖拽图片')
    }
    return message.success('恭喜你完成拼图')
}

// 生命周期
onMounted(() => {
    // 拖拽对象
    const dragArr = state.dragConfig.sourceArray.map(item => {
        return state.dragConfig.dragDomPrefix + '-' + item.id
    })
    dragArr.forEach(id => {
        initDragAction(document.getElementById(id))
    })


    // 目标对象
    const sourceArr = state.dragConfig.sourceArray.map(item => {
        return state.dragConfig.sourceDomPrefix + '-' + item.id
    })
    sourceArr.forEach(id => {
        initTargetAction(document.getElementById(id))
    })

    const targetArr = state.dragConfig.sourceArray.map(item => {
        return state.dragConfig.targetDomPrefix + '-' + item.id
    })
    targetArr.forEach(id => {
        initTargetAction(document.getElementById(id))
    })
})

</script>

<style>
.container-drag {

    min-width: 800px;
}

.random-button {
    margin: 5px;
    cursor: pointer;
}

.container-drag-box {
    display: flex;
    justify-content: space-between;
}

.container-drag-left {
    width: 800px;

}

.container-drag-right {
    width: 600px;
    height: 600px;
    margin: 0;
}

.drag-item-box {
    display: inline-block;
    margin: 2px;
    padding: 0;
    width: 280px;
    height: 280px;
    border: 1px solid rgb(255, 255, 255);
    overflow: hidden;

}


.target-item-box {
    display: inline-block;
    width: 280px;
    height: 280px;
    border: 1px solid rgb(255, 255, 255);
    box-sizing: border-box;
    overflow: hidden;
    margin-right: 5px;
    margin-bottom: 0;
    margin-top: 0;
}

/* 拖拽对象 */
.drag-item {
    margin: 0;
    text-align: center;
    cursor: pointer;
}

/* 拖拽中 */
.dragging {
    opacity: .5;
}

/* 悬浮上方 */
.dragover {
    background: rgba(0,255,0,.5);
}
</style>