<template>
    <!-- 原有模板代码不变 -->
    <el-upload
        :id="uuid"
        action="#"
        :multiple="true"
        :show-file-list="false"
        :http-request="handleHttpUpload"
        :before-upload="handleBeforeUpload"
        class="editor-img-uploader"
        accept=".jpeg,.jpg,.png,.gif"
    >
        <i ref="uploadRef" class="Plus editor-img-uploader"></i>
    </el-upload>

    <input
        type="file"
        accept="video/*"
        name="file"
        ref="uploadFileVideo"
        id="uploadFileVideo"
        @change="handleVideoUpload"
        style="width: 0; height: 0; cursor: pointer; opacity: 0"
    />
    <div class="editor">
        <QuillEditor
            id="editorId"
            ref="myQuillEditor"
            v-model:content="editorContent"
            contentType="html"
            @update:content="onContentChange"
            :options="options"
        />
    </div>
</template>

<script setup name="Editor">
// 原有导入语句不变
import { QuillEditor, Quill } from "@vueup/vue-quill";
import "@vueup/vue-quill/dist/vue-quill.snow.css";
import { getCurrentInstance, reactive, ref, toRaw, computed, onMounted } from "vue";
import { generateUUID } from "@/utils";
import { h } from "@/utils/url";
import { routerObj } from "./utils.js";
import { titleConfig } from "./titleConfig.js";
import { uploadVideo, uploadImg } from "@/api/modules/upload";
import { ElNotification } from "element-plus";

// 字体配置保留
let fontSizeStyle = Quill.import("attributors/style/size");
fontSizeStyle.whitelist = ["12px", "14px", "16px", "18px", "20px", "22px", "24px", "26px", "28px", "30px", "32px"];
Quill.register(fontSizeStyle, true);

// 自定义Blot保留
import ImageBlot from "./quill-image";
import Video from "./quill-video";
const uuid = ref("id-" + generateUUID());
const $router = useRouter();
const routerValueName = $router.currentRoute.value.name;
const routerName = ref(routerObj[routerValueName]);
Quill.register(Video);
Quill.register(ImageBlot);

// 原有响应式变量和props保留
const { proxy } = getCurrentInstance();
const emit = defineEmits(["update:content", "handleRichTextContentChange"]);
const uploadFileVideo = ref(null);
const imageList = ref([]);
const imageListDb = ref([]);
const props = defineProps({
    content: { type: String, default: "" },
    readOnly: { type: Boolean, default: false },
    fileSizeLimit: { type: Number, default: 10 }
});

// 计算属性保留
const editorContent = computed({
    get: () => props.content,
    set: val => {
        emit("update:content", val);
    }
});
const myQuillEditor = ref(null);

// 工具栏配置保留
const options = reactive({
    theme: "snow",
    debug: "warn",
    modules: {
        toolbar: {
            container: [
                ["bold", "italic", "underline", "strike"],
                ["blockquote", "code-block"],
                [{ list: "ordered" }, { list: "bullet" }],
                [{ indent: "-1" }, { indent: "+1" }],
                [{ size: fontSizeStyle.whitelist }],
                [{ header: [1, 2, 3, 4, 5, 6, false] }],
                [{ color: [] }, { background: [] }],
                [{ align: [] }],
                ["clean"],
                ["link", "image", "video"]
            ],
            handlers: {
                image: function (value) {
                    if (value) proxy.$refs.uploadRef.click();
                    else Quill.format("image", true);
                },
                video: function (value) {
                    if (value) document.querySelector("#uploadFileVideo")?.click();
                    else Quill.format("video", true);
                }
            }
        }
    },
    placeholder: "请输入内容...",
    readOnly: props.readOnly,
    clipboard: {
        matchers: [
            [
                "img",
                (node, delta) => {
                    const src = node.getAttribute("src");
                    const id = node.getAttribute("id");
                    delta.insert({ image: { src, id: id } });
                }
            ]
        ]
    }
});

// 恢复排序函数（原有代码保留）
const sortImageListByNumber = () => {
    imageListDb.value.sort((a, b) => {
        const getNumber = fileName => {
            const match = fileName.match(/-(\d+)$/);
            return match ? parseInt(match[1], 10) : 0;
        };
        const numA = getNumber(a.name);
        const numB = getNumber(b.name);
        return numA - numB;
    });
};

// 上传前钩子保留（仅修复错误处理）
const handleBeforeUpload = file => {
    const fileType = file.type;
    file.customUid = generateUUID();
    imageListDb.value.push(file);
    sortImageListByNumber(); // 保留排序调用

    const validTypes = [
        "image/jpeg",
        "image/png",
        "image/gif",
        "image/jpg",
        "image/bmp",
        "image/webp",
        "video/mov",
        "video/ts",
        "video/mp4",
        "video/avi"
    ];

    if (validTypes.includes(fileType)) {
        const isLt = file.size / 1024 / 1024 < props.fileSizeLimit;
        if (!isLt) {
            ElNotification({
                title: "温馨提示",
                message: `上传文件大小不能超过 ${props.fileSizeLimit} MB!`,
                type: "warning"
            });
            // 仅移除当前无效文件（原有逻辑修复）
            imageListDb.value = imageListDb.value.filter(item => item.customUid !== file.customUid);
            return false;
        }
        return true;
    } else {
        ElNotification({
            title: "温馨提示",
            message: `文件格式不正确！`,
            type: "warning"
        });
        // 仅移除当前无效文件（原有逻辑修复）
        imageListDb.value = imageListDb.value.filter(item => item.customUid !== file.customUid);
        return false;
    }
};

// 图片上传（仅修复最后一张删除问题）
const handleHttpUpload = async options => {
    let formData = new FormData();
    formData.append("image", options.file);
    imageList.value.push(options.file);

    try {
        const result = await uploadImg(formData, routerName.value, options.file.customUid);
        if (result?.data?.code === 0) {
            const { data } = result.data;
            const { imgId } = result;

            // 原有文件匹配逻辑保留
            const fileItem = imageListDb.value.find(item => item.customUid === imgId);
            if (fileItem) {
                fileItem.serverImgId = imgId;
                fileItem.path = data.path;
            }

            // 检查所有文件上传完成
            const allFilesUploaded = imageListDb.value.every(item => item.path);
            if (allFilesUploaded) {
                const rawMyQuillEditor = toRaw(myQuillEditor.value);
                const quill = rawMyQuillEditor.getQuill();

                // 关键修复：插入后强制刷新编辑器选区
                imageListDb.value.forEach(item => {
                    const length = quill.getLength() - 1;
                    quill.insertEmbed(length, "image", {
                        url: h + item.path,
                        id: item.serverImgId || generateUUID()
                    });
                    quill.setSelection(length + 1);
                });

                // 修复：清空数组前先保存最后一个光标位置
                const finalLength = quill.getLength();
                quill.setSelection(finalLength); // 确保光标在最后

                imageList.value = [];
                imageListDb.value = [];
            }
        }
    } catch (error) {
        console.error("图片上传失败:", error);
        // 异常时清理当前文件
        imageList.value = imageList.value.filter(item => item.customUid !== options.file.customUid);
        imageListDb.value = imageListDb.value.filter(item => item.customUid !== options.file.customUid);
    }
};

// 视频上传保留
const handleVideoUpload = async evt => {
    if (evt.target.files.length === 0) return;
    const formData = new FormData();
    formData.append("video", evt.target.files[0]);
    try {
        let quill = toRaw(myQuillEditor.value).getQuill();
        let length = quill.selection.savedRange.index;
        const { data } = await uploadVideo(formData);
        quill.insertEmbed(length, "video", {
            url: h + data.path,
            id: generateUUID()
        });
        uploadFileVideo.value.value = "";
    } catch (error) {
        console.log(error);
    }
};

// 内容变化监听（增加选区修复）
const onContentChange = content => {
    emit("handleRichTextContentChange", content);
    emit("update:content", content);
    console.log(content, "================content=================");
    //  修复：当内容为空时确保编辑器可编辑
    const rawMyQuillEditor = toRaw(myQuillEditor.value);
    if (rawMyQuillEditor) {
        const quill = rawMyQuillEditor.getQuill();
        if (content === "") {
            quill.enable(true);
            quill.setSelection(0); // 强制设置光标位置
        }
    }
};

// 原有初始化和清空方法保留
const initTitle = () => {
    document.getElementsByClassName("ql-editor")[0].dataset.placeholder = "";
    for (let item of titleConfig.value) {
        let tip = document.querySelector(".ql-toolbar " + item.Choice);
        if (tip) tip.setAttribute("title", item.title);
    }
};

const clearEditor = () => {
    const rawMyQuillEditor = toRaw(myQuillEditor.value);
    if (rawMyQuillEditor) {
        const quill = rawMyQuillEditor.getQuill();
        quill.setText("");
        editorContent.value = "";
    }
};

onMounted(() => {
    initTitle();
});

defineExpose({ clearEditor });
</script>

<style lang="scss">
@import "./index.scss";

// 增加编辑器内容区交互性确保删除可用
.ql-editor {
    min-height: 100px; // 确保空编辑器也有点击区域
    cursor: text !important;
    user-select: text !important;
}
</style>
