<template>
  <div class="wang-editor-wrapper" :class="{ focused: isFocused }">
    <div ref="toolbarRef" class="toolbar-container"></div>
    <div ref="editorRef" class="editor-container"></div>
  </div>
</template>

<script setup lang="ts">
import { ref, watch, onMounted, onBeforeUnmount, nextTick } from "vue";
import { ElMessage } from "element-plus";
import "@wangeditor/editor/dist/css/style.css";
import { uploadFile } from "@/api/file";

interface Props {
  modelValue: string;
}

const props = withDefaults(defineProps<Props>(), {
  modelValue: "",
});

const emit = defineEmits<{
  "update:modelValue": [value: string];
}>();

const toolbarRef = ref<HTMLDivElement>();
const editorRef = ref<HTMLDivElement>();
const isFocused = ref(false);
let editorInstance: any = null;
let isDestroyed = false;

// 获取上传文件的 URL
const getUploadUrl = (): string => {
  return import.meta.env.VITE_API_BASE_URL;
};

// 获取 Authorization Header
const getAuthHeaders = () => {
  const token = localStorage.getItem("token");
  return token ? { Authorization: `Bearer ${token}` } : {};
};

// 上传图片处理函数
const handleUploadImage = async (
  file: File,
  insertFn: (url: string, alt?: string, href?: string) => void,
) => {
  try {
    const formData = new FormData();
    formData.append("file", file);
    formData.append("cate", "article");

    const response: any = await uploadFile(formData);

    // 200=新文件上传成功，201=文件已存在（使用已有文件的链接）
    if (
      response &&
      (response.code === 200 || response.code === 201) &&
      response.data &&
      response.data.url
    ) {
      const fileUrl = response.data.url;
      const baseUrl = getUploadUrl() || window.location.origin;

      let fullUrl = fileUrl;
      if (!fileUrl.startsWith("http")) {
        const base = baseUrl.replace(/\/$/, "");
        const url = fileUrl.startsWith("/") ? fileUrl : "/" + fileUrl;
        fullUrl = `${base}${url}`;
      }

      insertFn(fullUrl, file.name, fullUrl);
      ElMessage.success(
        response.code === 201 ? "使用已有图片" : "图片上传成功",
      );
    } else {
      ElMessage.error("上传失败：" + (response?.msg || "未知错误"));
    }
  } catch (error: any) {
    console.error("Upload error:", error);
    ElMessage.error("上传失败：" + (error.message || "未知错误"));
  }
};

// 上传视频处理函数
const handleUploadVideo = async (
  file: File,
  insertFn: (url: string, poster?: string) => void,
) => {
  try {
    const formData = new FormData();
    formData.append("file", file);
    formData.append("cate", "article");

    const response: any = await uploadFile(formData);

    // 200=新文件上传成功，201=文件已存在（使用已有文件的链接）
    if (
      response &&
      (response.code === 200 || response.code === 201) &&
      response.data &&
      response.data.url
    ) {
      const fileUrl = response.data.url;
      const baseUrl = getUploadUrl() || window.location.origin;

      let fullUrl = fileUrl;
      if (!fileUrl.startsWith("http")) {
        const base = baseUrl.replace(/\/$/, "");
        const url = fileUrl.startsWith("/") ? fileUrl : "/" + fileUrl;
        fullUrl = `${base}${url}`;
      }

      insertFn(fullUrl, "");
      ElMessage.success(
        response.code === 201 ? "使用已有视频" : "视频上传成功",
      );
    } else {
      ElMessage.error("上传失败：" + (response?.msg || "未知错误"));
    }
  } catch (error: any) {
    console.error("Upload error:", error);
    ElMessage.error("上传失败：" + (error.message || "未知错误"));
  }
};

// 上传附件处理函数
const handleUploadAttachment = async (
  file: File,
  insertFn: (url: string, text?: string) => void,
) => {
  try {
    const formData = new FormData();
    formData.append("file", file);
    formData.append("cate", "article");

    const response: any = await uploadFile(formData);

    // 200=新文件上传成功，201=文件已存在（使用已有文件的链接）
    if (
      response &&
      (response.code === 200 || response.code === 201) &&
      response.data &&
      response.data.url
    ) {
      const fileUrl = response.data.url;
      const baseUrl = getUploadUrl() || window.location.origin;

      let fullUrl = fileUrl;
      if (!fileUrl.startsWith("http")) {
        const base = baseUrl.replace(/\/$/, "");
        const url = fileUrl.startsWith("/") ? fileUrl : "/" + fileUrl;
        fullUrl = `${base}${url}`;
      }

      insertFn(fullUrl, file.name);
      ElMessage.success(
        response.code === 201 ? "使用已有附件" : "附件上传成功",
      );
    } else {
      ElMessage.error("上传失败：" + (response?.msg || "未知错误"));
    }
  } catch (error: any) {
    console.error("Upload error:", error);
    ElMessage.error("上传失败：" + (error.message || "未知错误"));
  }
};

// 初始化编辑器
const initEditor = async () => {
  if (!editorRef.value || !toolbarRef.value || isDestroyed) return;

  try {
    // 动态导入 wangEditor
    const { createEditor, createToolbar } = await import("@wangeditor/editor");

    const editorConfig = {
      placeholder: "请输入内容...",
      onChange: (editor: any) => {
        if (!isDestroyed) {
          const html = editor.getHtml();
          emit("update:modelValue", html);
        }
      },
      // 自定义上传配置
      MENU_CONF: {
        // 图片上传配置
        uploadImage: {
          server: "/api/files",
          fieldName: "file",
          headers: getAuthHeaders(),
          customUpload: async (
            file: File,
            insertFn: (url: string, alt?: string, href?: string) => void,
          ) => {
            await handleUploadImage(file, insertFn);
          },
          allowedFileTypes: ["image/*"],
          maxFileSize: 5 * 1024 * 1024, // 5MB
        },
        // 视频上传配置
        uploadVideo: {
          server: "/api/files",
          fieldName: "file",
          headers: getAuthHeaders(),
          customUpload: async (
            file: File,
            insertFn: (url: string, poster?: string) => void,
          ) => {
            await handleUploadVideo(file, insertFn);
          },
          allowedFileTypes: ["video/*"],
          maxFileSize: 100 * 1024 * 1024, // 100MB
        },
        // 附件上传配置
        uploadAttachment: {
          server: "/api/files",
          fieldName: "file",
          headers: getAuthHeaders(),
          customUpload: async (
            file: File,
            insertFn: (url: string, text?: string) => void,
          ) => {
            await handleUploadAttachment(file, insertFn);
          },
          allowedFileTypes: ["*"],
          maxFileSize: 50 * 1024 * 1024, // 50MB
        },
      },
    };

    // 创建编辑器
    editorInstance = createEditor({
      selector: editorRef.value,
      html: props.modelValue || "",
      config: editorConfig,
      mode: "default",
    });

    // 创建工具栏
    createToolbar({
      editor: editorInstance,
      selector: toolbarRef.value,
      config: {},
    });

    // 监听编辑器焦点事件（兼容不同版本的 API）
    nextTick(() => {
      if (editorInstance) {
        // 方法1: 使用 on 方法（如果存在）
        if (typeof editorInstance.on === "function") {
          editorInstance.on("focus", () => {
            isFocused.value = true;
          });

          editorInstance.on("blur", () => {
            isFocused.value = false;
          });
        }

        // 方法2: 直接在 DOM 元素上监听
        const editorDom = editorRef.value;
        if (editorDom) {
          const textDom = editorDom.querySelector(".w-e-text");
          if (textDom) {
            textDom.addEventListener("focus", () => {
              isFocused.value = true;
            });
            textDom.addEventListener("blur", () => {
              isFocused.value = false;
            });
          }
        }
      }
    });
  } catch (error) {
    console.error("Failed to initialize editor:", error);
  }
};

// 监听外部值变化
watch(
  () => props.modelValue,
  (newVal) => {
    if (editorInstance && newVal !== editorInstance.getHtml()) {
      editorInstance.setHtml(newVal || "");
    }
  },
);

// 暴露方法
defineExpose({
  clear: () => {
    if (editorInstance) {
      editorInstance.clear();
    }
  },
  getContent: () => {
    if (editorInstance) {
      return editorInstance.getHtml();
    }
    return props.modelValue;
  },
  setContent: (content: string) => {
    if (editorInstance) {
      editorInstance.setHtml(content || "");
    }
  },
});

onMounted(() => {
  nextTick(() => {
    setTimeout(() => {
      initEditor();
    }, 100);
  });
});

onBeforeUnmount(() => {
  isDestroyed = true;
  if (editorInstance) {
    editorInstance.destroy();
    editorInstance = null;
  }
});
</script>

<style lang="less">
.wang-editor-wrapper {
  display: flex;
  flex-direction: column;
  height: 650px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  overflow: hidden;
  background: #ffffff;

  .toolbar-container {--fill-color-light
    position: sticky;
    top: 0;
    z-index: 10;
    background: #f5f7fa;
    border-bottom: 1px solid #dcdfe6;
    flex-shrink: 0;
  }

  .editor-container {
    flex: 1;
    overflow-y: auto;
    overflow-x: hidden;
    padding: 0;

    &::-webkit-scrollbar {
      width: 6px;
      height: 6px;
    }

    &::-webkit-scrollbar-thumb {
      background: #c0c4cc;
      border-radius: 3px;
    }

    &::-webkit-scrollbar-track {
      background: #f5f7fa;
      border-radius: 3px;
    }
  }

  :deep(.w-e-text),
    :deep(.w-e-text-container) {
      p {
        color: #1a1a2e !important;
        margin: 8px 0 !important;
        line-height: 1.8 !important;
      }

      h1, h2, h3, h4, h5, h6 {
        color: #1a1a2e !important;
        font-weight: 600 !important;
        margin: 16px 0 8px !important;
      }

      a {
        color: #3973ff !important;
        text-decoration: underline !important;
      }

      code {
        background: #f5f7fa !important;
        color: #1a1a2e !important;
        border: 1px solid #e4e7ed !important;
        border-radius: 3px;
        padding: 2px 6px;
        font-family: 'Consolas', 'Monaco', monospace;
        font-size: 13px;
      }

      pre {
        background: #f5f7fa !important;
        border: 1px solid #e4e7ed !important;
        border-radius: 4px;
        padding: 12px 16px;
        margin: 12px 0;
        overflow-x: auto;
        color: #1a1a2e !important;

        code {
          background: transparent !important;
          border: none !important;
          padding: 0;
          font-size: 13px;
          line-height: 1.6;
          color: #1a1a2e !important;
        }
      }

      blockquote {
        border-left: 4px solid #3973ff !important;
        background: #f5f7fa !important;
        color: #606266 !important;
        padding: 8px 16px;
        margin: 12px 0;
      }

      table {
        border-collapse: collapse !important;
        border: 1px solid #e4e7ed !important;
        width: 100% !important;
        margin: 12px 0;

        th, td {
          border: 1px solid #e4e7ed !important;
          padding: 8px 12px !important;
          min-width: 60px;
        }

        th {
          background: #f5f7fa !important;
          font-weight: 600;
        }
      }

      ul, ol {
        color: #1a1a2e !important;
        padding-left: 24px !important;
        margin: 8px 0;
      }

      li {
        color: #1a1a2e !important;
        line-height: 1.8 !important;
        margin: 4px 0;
      }

      hr {
        border-top: 1px solid #e4e7ed !important;
        margin: 16px 0 !important;
      }

      img {
        max-width: 100% !important;
        border-radius: 4px !important;
        margin: 8px 0;
      }
    }
}

html.dark {
  .wang-editor-wrapper {
    border-color: #3d3d3d;
    background: #1a1a1a;

    .toolbar-container {
      background: #2d2d2d;
      border-color: #3d3d3d;
    }

    .editor-container {
      &::-webkit-scrollbar {
        width: 6px;
        height: 6px;
      }

      &::-webkit-scrollbar-thumb {
        background: #4d4d4d;
        border-radius: 3px;
      }

      &::-webkit-scrollbar-track {
        background: #2d2d2d;
        border-radius: 3px;
      }
    }

    :deep(.w-e-text),
    :deep(.w-e-text-container) {
      background: transparent !important;

      p, h1, h2, h3, h4, h5, h6 {
        color: #e0e0e0 !important;
      }

      a {
        color: #4f84ff !important;
        text-decoration: underline !important;
      }

      code {
        background: #2d2d2d !important;
        color: #e0e0e0 !important;
        border-color: #3d3d3d !important;
      }

      pre {
        background: #2d2d2d !important;
        border-color: #3d3d3d !important;
        color: #e0e0e0 !important;

        code {
          background: transparent !important;
          border: none !important;
          color: #e0e0e0 !important;
        }
      }

      blockquote {
        border-color: #4f84ff !important;
        background: #2d2d2d !important;
        color: #b0b0b0 !important;
      }

      table {
        border-color: #3d3d3d !important;

        th, td {
          border-color: #3d3d3d !important;
          background: #1a1a1a !important;
          color: #e0e0e0 !important;
        }

        th {
          background: #2d2d2d !important;
        }
      }

      ul, ol {
        color: #e0e0e0 !important;
        padding-left: 24px !important;
        margin: 8px 0;
      }

      li {
        color: #e0e0e0 !important;
        line-height: 1.8 !important;
        margin: 4px 0;
      }

      hr {
        border-color: #3d3d3d !important;
      }

      img {
        max-width: 100% !important;
        border-radius: 4px !important;
        margin: 8px 0;
      }
    }
  }
}

.toolbar-container {
  border-bottom: 1px solid #dcdfe6;
  background-color: #f5f7fa;
  transition: all 0.3s ease;
}

.editor-container {
  min-height: 400px;
  background-color: #ffffff;
  transition: background-color 0.3s ease;
}
</style>
