<template>
    <el-upload
        :id="uuid"
        action="#"
        :multiple="true"
        :show-file-list="false"
        :http-request="() => {}"
        :before-upload="() => false"
        @change="handleFileChange"
        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";

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

// 自定义模块
import ImageBlot from "./quill-image";
import Video from "./quill-video";
Quill.register(Video);
Quill.register(ImageBlot);

// 路由相关
const $router = useRouter();
const routerValueName = $router.currentRoute.value.name;
const routerName = ref(routerObj[routerValueName]);

// 核心：上传队列 + 临时去重集合
const uploadQueue = ref([]);
const isProcessing = ref(false);
const uuid = ref(generateUUID());
const tempProcessedFiles = ref(new Set());

// 编辑器基础
const { proxy } = getCurrentInstance();
const emit = defineEmits(["update:content", "handleRichTextContentChange"]);
const uploadFileVideo = ref(null);
const myQuillEditor = ref(null);
const oldContent = ref("");

// Props
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 options = reactive({
    theme: "snow",
    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: () => proxy.$refs.uploadRef.click(),
                video: () => document.querySelector("#uploadFileVideo")?.click()
            }
        }
    },
    placeholder: "请输入内容...",
    readOnly: props.readOnly
});

// 处理文件选择（关键修改：记录原始顺序）
const handleFileChange = (file, fileList) => {
    if (!fileList.length) return;

    const rawEditor = toRaw(myQuillEditor.value);
    const quill = rawEditor?.getQuill();
    if (!quill) return;

    // 生成文件唯一标识
    const getFileKey = file => `${file.name}-${file.size}-${file.lastModified}`;

    // 过滤重复文件
    const newFiles = fileList.filter(item => {
        const file = item.raw;
        const key = getFileKey(file);
        if (tempProcessedFiles.value.has(key)) {
            console.log(`跳过重复文件: ${file.name}`);
            return false;
        }
        if (!validateFile(file)) return false;
        tempProcessedFiles.value.add(key);
        return true;
    });

    if (!newFiles.length) return;

    // 获取初始光标位置（所有图片将按顺序插入此位置之后）
    const baseCursorIndex = quill.selection.savedRange?.index || quill.getLength();

    // 按用户选择顺序添加到队列（关键修改：使用原始索引）
    newFiles.forEach((item, index) => {
        uploadQueue.value.push({
            file: item.raw,
            originalIndex: index, // 记录用户选择的原始顺序
            baseCursorIndex // 所有图片共享同一个基础位置
        });
    });

    if (!isProcessing.value) {
        processQueue();
    }
};

// 文件校验
const validateFile = file => {
    const isImage = file.type.startsWith("image/");
    if (!isImage) {
        alert("请上传图片文件");
        return false;
    }

    const fileSizeMB = file.size / 1024 / 1024;
    if (fileSizeMB > props.fileSizeLimit) {
        alert(`文件 ${file.name} 大小超过 ${props.fileSizeLimit} MB`);
        return false;
    }

    return true;
};

// 处理上传队列（关键修改：按原始顺序插入）
const processQueue = async () => {
    if (isProcessing.value || uploadQueue.value.length === 0) return;

    isProcessing.value = true;
    const { file, originalIndex, baseCursorIndex } = uploadQueue.value[0];

    try {
        const formData = new FormData();
        formData.append("image", file);
        const result = await uploadImg(formData, routerName.value);

        if (result?.code === 0) {
            const rawEditor = toRaw(myQuillEditor.value);
            const quill = rawEditor.getQuill();

            // 关键修改：计算正确的插入位置（基于原始顺序和基础位置）
            const insertPosition = baseCursorIndex + originalIndex;

            quill.insertEmbed(insertPosition, "image", {
                url: h + result.data.path,
                id: generateUUID()
            });

            // 不更新光标位置，确保后续图片按原始顺序插入
            // quill.setSelection(insertPosition + 1);
        }
    } catch (error) {
        console.error(`文件 ${file.name} 上传失败:`, error);
    } finally {
        uploadQueue.value.shift();
        if (uploadQueue.value.length === 0) {
            tempProcessedFiles.value.clear();
        }
        isProcessing.value = false;
        processQueue();
    }
};

// 视频上传
const handleVideoUpload = async evt => {
    if (evt.target.files.length === 0) return;

    const file = evt.target.files[0];
    const formData = new FormData();
    formData.append("video", file);

    try {
        const rawEditor = toRaw(myQuillEditor.value);
        const quill = rawEditor.getQuill();
        const cursorIndex = quill.selection.savedRange?.index || 0;

        const { data } = await uploadVideo(formData);
        quill.insertEmbed(cursorIndex, "video", {
            url: h + data.path,
            id: generateUUID()
        });
        quill.setSelection(cursorIndex + 1);
    } catch (error) {
        console.error("视频上传失败:", error);
    } finally {
        evt.target.value = "";
    }
};

// 内容变化监听
const onContentChange = content => {
    emit("handleRichTextContentChange", content);
};

// 初始化标题提示
const initTitle = () => {
    for (const item of titleConfig.value) {
        const tip = document.querySelector(`.ql-toolbar ${item.Choice}`);
        if (tip) tip.setAttribute("title", item.title);
    }
};

onMounted(() => {
    initTitle();
    oldContent.value = props.content;
});
</script>
<style lang="scss">
@import "./index.scss";
</style>
