<template>
    <div class="m-main">
        <div class="sidebar el-card">
            <h3 style="text-align: center">模块组件</h3>
            <div style="display: flex; flex-wrap: wrap">
                <el-button
                    v-for="(button, index) in moduleButtons"
                    :key="index"
                    class="module-button"
                    draggable="true"
                    @dragstart="onDragStart(button)"
                    @dragend="onDragEnd"
                >
                    {{ button }}
                </el-button>
            </div>
        </div>
        <div class="dropzone el-card" @dragover.prevent @dragleave="onDragLeave" @drop="onDrop">
            <template v-for="(module, moduleIndex) in dropzoneModules" :key="moduleIndex">
                <div
                    draggable="true"
                    @dragstart="onModuleDragStart(module, moduleIndex)"
                    @dragend="onDragEnd"
                    @click="selectModule(module, moduleIndex)"
                    style="
                        position: relative;
                        display: flex;
                        align-items: center;
                        justify-content: center;
                        width: 100%;
                        height: auto;
                        min-height: 40px;
                        margin: 0;
                        cursor: pointer;
                        border: 1px solid #eeeeee;
                    "
                >
                    <el-image
                        v-if="module.type === '图片模块'"
                        :src="module.imageUrl"
                        :style="{
                            borderRadius: module.borderRadius + 'px',
                            width: module.width + 'px',
                            height: module.height + 'px',
                            border: `2px solid #ccc`,
                            boxSizing: 'border-box'
                        }"
                    />

                    <div
                        v-if="module.type === '文字模块'"
                        :class="['text-module', `text-align-${module.textAlign}`]"
                        :style="{
                            fontSize: module.fontSize + 'px',
                            color: module.fontColor,
                            fontWeight: module.isBold ? 'bold' : 'normal',
                            fontStyle: module.isItalic ? 'italic' : 'normal'
                        }"
                    >
                        {{ module.text }}
                        <!--  @input="updateText(module, $event.target.innerHTML)" -->
                        <!-- 使用 v-html 来渲染富文本内容 -->
                    </div>
                    <span v-if="module.type === '视频模块'">{{ module.type }}</span>
                    <span v-if="module.type === '图文模块'">{{ module.type }}</span>
                    <el-carousel v-if="module.type === '轮播图模块'" arrow="always" style="width: 100%; height: 300px">
                        <el-carousel-item v-for="(item, index) in module.images" :key="index">
                            <el-image :src="item" alt="轮播图" style="width: 100%; height: 100%; object-fit: cover" />
                        </el-carousel-item>
                    </el-carousel>
                    <el-icon style="cursor: pointer" class="delete-btn" @click="deleteModule(moduleIndex)"
                        ><CircleCloseFilled
                    /></el-icon>
                </div>
            </template>
        </div>
        <div class="right-sidebar el-card">
            <div v-if="selectedModule">
                <h3>{{ selectedModule.type }} 属性配置</h3>
                <el-form :model="selectedModule" class="config-form">
                    <el-form-item label="模块类型">
                        <span>{{ selectedModule.type }}</span>
                    </el-form-item>

                    <el-form-item label="图片地址" v-if="selectedModule.type === '图片模块'">
                        <el-input v-model="selectedModule.imageUrl" @input="updateImageSize" />
                    </el-form-item>
                    <el-form-item label="上传图片" v-if="selectedModule.type === '图片模块'">
                        <el-upload action="#" :show-file-list="false" :on-change="handleImageUpload">
                            <el-button type="primary">选择图片</el-button>
                        </el-upload>
                    </el-form-item>
                    <el-form-item label="图片圆角" v-if="selectedModule.type === '图片模块'">
                        <el-input-number v-model="selectedModule.borderRadius" :min="0" />
                    </el-form-item>
                    <el-form-item label="图片宽度" v-if="selectedModule.type === '图片模块'">
                        <el-input-number v-model="selectedModule.width" :min="1" />
                    </el-form-item>
                    <el-form-item label="图片高度" v-if="selectedModule.type === '图片模块'">
                        <el-input-number v-model="selectedModule.height" :min="1" />
                    </el-form-item>
                    <el-form-item label="文字内容" v-if="selectedModule.type === '文字模块'">
                        <el-input v-model="selectedModule.text" type="textarea" />
                    </el-form-item>
                    <el-form-item label="字体大小" v-if="selectedModule.type === '文字模块'">
                        <el-input-number v-model="selectedModule.fontSize" :min="12" :max="72" />
                    </el-form-item>
                    <el-form-item label="字体颜色" v-if="selectedModule.type === '文字模块'">
                        <el-color-picker v-model="selectedModule.fontColor" />
                    </el-form-item>
                    <el-form-item label="字体加粗" v-if="selectedModule.type === '文字模块'">
                        <el-switch v-model="selectedModule.isBold" />
                    </el-form-item>
                    <el-form-item label="字体倾斜" v-if="selectedModule.type === '文字模块'">
                        <el-switch v-model="selectedModule.isItalic" />
                    </el-form-item>
                    <el-form-item label="文字对齐" v-if="selectedModule.type === '文字模块'">
                        <el-radio-group v-model="selectedModule.textAlign">
                            <el-radio-button label="left">左对齐</el-radio-button>
                            <el-radio-button label="center">居中对齐</el-radio-button>
                            <el-radio-button label="right">右对齐</el-radio-button>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item label="视频地址" v-if="selectedModule.type === '视频模块'">
                        <el-input v-model="selectedModule.videoUrl" />
                    </el-form-item>
                    <el-form-item label="图文文字" v-if="selectedModule.type === '图文模块'">
                        <el-input v-model="selectedModule.textContent" />
                    </el-form-item>
                    <el-form-item label="图文图片地址" v-if="selectedModule.type === '图文模块'">
                        <el-input v-model="selectedModule.imageContentUrl" />
                    </el-form-item>
                    <template v-if="selectedModule.type === '轮播图模块'">
                        <el-form-item
                            label="轮播图地址"
                            v-for="(image, index) in selectedModule.images"
                            :key="index"
                            style="min-width: 240px"
                        >
                            <el-input v-model="selectedModule.images[index]" style="width: 195px" />
                            <el-button type="danger" @click="deleteCarouselImage(selectedModule, index)" style="margin-left: 10px"
                                >删除</el-button
                            >
                        </el-form-item>
                        <el-form-item label="添加本地图片">
                            <el-upload action="#" :show-file-list="false" :on-change="handleCarouselImageUpload(selectedModule)">
                                <el-button type="primary">选择图片</el-button>
                            </el-upload>
                        </el-form-item>
                        <el-form-item label="添加网络图片" style="min-width: 240px">
                            <el-input v-model="newCarouselImageUrl" placeholder="输入网络图片地址" style="width: 195px" />
                            <el-button @click="addCarouselImage(selectedModule)" style="margin-left: 10px">添加</el-button>
                        </el-form-item>
                    </template>
                </el-form>
            </div>
        </div>
    </div>
</template>

<script lang="ts" setup>
import { ref } from "vue";
import { CircleCloseFilled } from "@element-plus/icons-vue";
//"图文模块",
const moduleButtons = ref(["图片模块", "文字模块", "视频模块", "轮播图模块"]);
const dropzoneModules = ref<any[]>([]);
const draggedModule = ref<any | null>(null);
const draggedModuleIndex = ref<number | null>(null);
const targetModuleIndex = ref<number | null>(null);
const selectedModule = ref<any | null>(null);
const selectedModuleIndex = ref<number | null>(null);
const newCarouselImageUrl = ref("");

const onDragStart = (buttonText: string) => {
    let newModule;
    if (buttonText === "轮播图模块") {
        newModule = {
            type: buttonText,
            images: [
                "https://dummyimage.com/800x600/ff0000/ffffff",
                "https://dummyimage.com/800x600/00ff00/ffffff",
                "https://dummyimage.com/800x600/0000ff/ffffff"
            ]
        };
    } else if (buttonText === "图片模块") {
        newModule = {
            type: buttonText,
            imageUrl: "https://dummyimage.com/800x600/cccccc/ffffff",
            borderRadius: 0,
            width: 800,
            height: 600
        };
    } else if (buttonText === "视频模块") {
        newModule = {
            type: buttonText,
            videoUrl: ""
        };
    } else if (buttonText === "图文模块") {
        newModule = {
            type: buttonText,
            textContent: "",
            imageContentUrl: ""
        };
    } else if (buttonText === "文字模块") {
        newModule = {
            type: buttonText,
            text: "",
            fontSize: 16,
            fontColor: "#000000",
            isBold: false,
            isItalic: false,
            textAlign: "left"
        };
    }

    draggedModule.value = newModule;
    draggedModuleIndex.value = null;
    targetModuleIndex.value = null;
};

const onDragEnd = () => {
    draggedModule.value = null;
    draggedModuleIndex.value = null;
    targetModuleIndex.value = null;
};

const onDrop = (event: DragEvent) => {
    if (draggedModule.value) {
        let target = event.target as HTMLElement;
        // 确保 target 是模块元素
        while (target && !target.classList.contains("dropzone") && !target.hasAttribute("draggable")) {
            target = target.parentNode as HTMLElement;
        }
        if (target.hasAttribute("draggable")) {
            const targetIndex = Array.from(target.parentNode!.children).indexOf(target);
            targetModuleIndex.value = targetIndex;
        }

        if (draggedModuleIndex.value !== null && targetModuleIndex.value !== null) {
            const temp = dropzoneModules.value[draggedModuleIndex.value];
            dropzoneModules.value[draggedModuleIndex.value] = dropzoneModules.value[targetModuleIndex.value];
            dropzoneModules.value[targetModuleIndex.value] = temp;
        } else if (draggedModuleIndex.value === null) {
            if (targetModuleIndex.value !== null) {
                dropzoneModules.value.splice(targetModuleIndex.value, 0, draggedModule.value);
            } else {
                dropzoneModules.value.push(draggedModule.value);
            }
        }
        draggedModule.value = null;
        draggedModuleIndex.value = null;
        targetModuleIndex.value = null;
    }
};

const onDragLeave = () => {
    // 可添加样式恢复逻辑
};

const onModuleDragStart = (module: any, index: number) => {
    draggedModule.value = module;
    draggedModuleIndex.value = index;
};

const deleteModule = (index: number) => {
    dropzoneModules.value.splice(index, 1);
    if (selectedModuleIndex.value === index) {
        selectedModule.value = null;
        selectedModuleIndex.value = null;
    }
};

// 确保选中模块时属性已初始化
const initModuleProperties = (module: any) => {
    if (module.type === "视频模块") {
        module.videoUrl = module.videoUrl || "";
    } else if (module.type === "图文模块") {
        module.textContent = module.textContent || "";
        module.imageContentUrl = module.imageContentUrl || "";
    } else if (module.type === "文字模块") {
        module.fontSize = module.fontSize || 16;
        module.fontColor = module.fontColor || "#000000";
        module.isBold = module.isBold || false;
        module.isItalic = module.isItalic || false;
        module.textAlign = module.textAlign || "left";
    } else if (module.type === "图片模块") {
        module.borderRadius = module.borderRadius || 0;
        module.width = module.width || 800;
        module.height = module.height || 600;
    }
};

const selectModule = (module: any, index: number) => {
    initModuleProperties(module);
    selectedModule.value = module;
    selectedModuleIndex.value = index;
};

// const updateText = (module: any, text: string) => {
//     // 之前的逻辑，未修改，可根据需要添加更多处理
//     module.text = text;
// };

const handleImageUpload = (file: any) => {
    const reader = new FileReader();
    reader.onload = (e: any) => {
        if (selectedModule.value) {
            selectedModule.value.imageUrl = e.target?.result as string;
            const img = new Image();
            img.src = selectedModule.value.imageUrl;
            img.onload = () => {
                selectedModule.value.width = img.width;
                selectedModule.value.height = img.height;
            };
        }
    };
    reader.readAsDataURL(file.raw);
};

const updateImageSize = () => {
    if (selectedModule.value && selectedModule.value.type === "图片模块") {
        const img = new Image();
        img.src = selectedModule.value.imageUrl;
        img.onload = () => {
            selectedModule.value.width = img.width;
            selectedModule.value.height = img.height;
        };
    }
};

const deleteCarouselImage = (module: any, index: number) => {
    module.images.splice(index, 1);
};

const handleCarouselImageUpload = (module: any) => {
    return (file: any) => {
        const reader = new FileReader();
        reader.onload = e => {
            if (e.target?.result) {
                const newImageUrl = e.target.result.toString();
                if (!module.images.includes(newImageUrl)) {
                    module.images.push(newImageUrl);
                }
            }
        };
        reader.readAsDataURL(file.raw);
    };
};

const addCarouselImage = (module: any) => {
    if (newCarouselImageUrl.value) {
        if (!module.images.includes(newCarouselImageUrl.value)) {
            module.images.push(newCarouselImageUrl.value);
        }
        newCarouselImageUrl.value = "";
    }
};
</script>

<style scoped>
.m-main {
    display: flex;
    min-width: 1280px;
    height: 100%;
    margin: 0;
    font-family: Arial, sans-serif;
}
.sidebar {
    flex: 1;
    padding: 10px;
    overflow-y: hidden;
}
.module-button {
    display: block;
    width: 40%;
    margin: 10px auto;
}
.dropzone {
    display: flex;
    flex: 3;
    flex-direction: column;
    align-content: flex-start;
    min-width: 820px;
    height: 100%;
    padding: 10px;
    margin: 0 20px;
    overflow-y: auto;
    border: 1px solid #cccccc;
}
.delete-btn {
    position: absolute;
    top: 5px;
    right: 5px;
}
.right-sidebar {
    /* width: 25%; */
    flex: 2;
    padding: 10px;
    overflow-y: hidden;
}
.config-form {
    padding: 10px;
}
.text-module {
    /* 确保文字模块的宽度为 100%，以便对齐生效 */
    width: 100%;
    padding: 10px;
}
.text-align-left {
    text-align: left;
}
.text-align-center {
    text-align: center;
}
.text-align-right {
    text-align: right;
}
</style>
