WordEditor.vue 36.1 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297
<template>
  <div class="word-editor-container">
    <!-- 加载状态 -->
    <div v-if="loading" class="loading-state">
      <i class="fas fa-spinner fa-spin"></i>
      <span>加载文档中...</span>
    </div>

    <!-- 错误状态 -->
    <div v-else-if="error" class="error-state">
      <i class="fas fa-exclamation-triangle"></i>
      <p class="error-text">{{ error }}</p>
      <el-button @click="loadDocument" size="small">重试</el-button>
    </div>

    <!-- 编辑器容器 -->
    <div v-else-if="editorContent !== null" class="editor-wrapper">
      <!-- 懒加载 UmoEditor 组件,只有在需要时才加载 @umoteam/editor -->
      <component
        v-if="UmoEditorComponent"
        :is="UmoEditorComponent"
        ref="editorRef"
        :model-value="editorContent"
        :options="editorOptions"
        :height="editorHeight"
        @update:model-value="handleContentUpdate"
      />
      <!-- UmoEditor 正在按需加载时的占位 -->
      <div v-else class="loading-state">
        <i class="fas fa-spinner fa-spin"></i>
        <span>加载编辑器中...</span>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import {
  ref,
  computed,
  onMounted,
  onBeforeUnmount,
  watch,
  nextTick,
} from "vue";
import { ElButton, ElMessage } from "element-plus";
import * as filesApi from "@/api/files";
import { apiUpdateDraft } from "@/api/drafts";
import mammoth from "mammoth";
import { Document, Packer, Paragraph, TextRun, HeadingLevel } from "docx";
import { fileCache } from "@/utils/fileCache";
import { triggerNewbieTask } from "@/utils/newbieTask";

interface Props {
  fileId: string | number;
  fileName: string;
  isChatAnswer?: boolean;
}

interface Emits {
  (
    e: "content-change",
    data: { text: string; html: string; hasChanges: boolean },
  ): void;
  (
    e: "file-saved",
    data: {
      fileId: string | number;
      fileName: string;
      content: string;
      isAutoSave: boolean;
    },
  ): void;
}

const props = defineProps<Props>();
const emit = defineEmits<Emits>();

// 动态加载的 UmoEditor 组件
const UmoEditorComponent = ref<any | null>(null);

const editorRef = ref<any | null>(null);
const loading = ref(true);
const error = ref<string | null>(null);
const editorContent = ref<string | null>(null);
const originalContent = ref<string>("");
const currentContent = ref<string>("");
const hasUnsavedChanges = ref(false);
const hasUserEdited = ref(false); // 标记用户是否编辑过
const isSaving = ref(false); // 标记是否正在保存
const isUpdating = ref(false); // 防止递归更新
const autoSaveTimer = ref<number | null>(null);
const contentWatcherInterval = ref<number | null>(null); // 内容轮询定时器
const editorHeight = ref("100%");
const editorKey = ref(String(Date.now()));
const originalDocxBlob = ref<Blob | null>(null); // 保存原始 Word 文档的 Blob
const isWordDocument = ref(false); // 标记是否为 Word 文档

// TOS 存储相关状态
const fileStorageType = ref<string>("LOCAL");
const hasPendingTosSync = ref(false);
const tosSyncTimer = ref<number | null>(null);
const TOS_SYNC_INTERVAL = 60000;
const isTosFile = computed(() => fileStorageType.value && fileStorageType.value !== "LOCAL");

// 懒加载 UmoEditor 及其样式,避免在应用根路由就拉取 @umoteam/editor 相关大包
const loadUmoEditorIfNeeded = async () => {
  if (UmoEditorComponent.value) return;

  try {
    const [editorModule] = await Promise.all([
      import("@umoteam/editor"),
      import("@umoteam/editor/style"),
    ]);
    UmoEditorComponent.value =
      (editorModule as any).UmoEditor || (editorModule as any).default;
  } catch (e) {
    console.error("加载 UmoEditor 失败:", e);
    ElMessage.error("加载文档编辑器失败,请稍后重试");
    error.value = "加载文档编辑器失败,请稍后重试";
  }
};

// 编辑器选项
const editorOptions = computed(() => ({
  editorKey: editorKey.value,
  locale: "zh-CN",
  dicts: [],
  toolbar: {
    defaultMode: "classic" as const,
    disableMenuItems: ["save"], // 禁用保存按钮,使用自动保存
    menus: [
      "undo",
      "redo",
      "|",
      "heading",
      "fontFamily",
      "fontSize",
      "|",
      "bold",
      "italic",
      "underline",
      "strike",
      "foreColor",
      "backColor",
      "|",
      "alignment",
      "bulletList",
      "orderedList",
      "|",
      "link",
      "image",
      "table",
      "|",
      "blockquote",
      "code",
      "codeBlock",
      "|",
      "clearFormat",
    ],
  },
  page: {
    defaultOrientation: "portrait" as const,
    defaultBackground: "#ffffff",
    showLineNumber: false,
    showToc: false,
  },
  document: {
    title: props.fileName,
    content: editorContent.value || "",
    placeholder: "开始编辑文档...",
    enableMarkdown: false,
    enableBubbleMenu: true,
    enableBlockMenu: true,
    readOnly: false,
    autosave: false, // 禁用编辑器内置的自动保存,使用自定义逻辑
  },
  assistant: {
    enabled: false,
  },
  autoFocus: false, // 禁用自动聚焦,避免自动滚动
}));

// 处理内容更新
const handleContentUpdate = (newContent?: string) => {
  // 防止递归更新
  if (isUpdating.value) {
    return;
  }

  try {
    isUpdating.value = true;

    // 获取HTML内容
    const htmlContent = newContent || editorContent.value || "";

    // 检查内容是否真的变化了(提前检查,避免不必要的处理)
    if (htmlContent === currentContent.value) {
      isUpdating.value = false;
      return;
    }

    // 尝试从编辑器实例获取文本内容
    let textContent = "";
    if (
      editorRef.value &&
      typeof (editorRef.value as any).getText === "function"
    ) {
      textContent = (editorRef.value as any).getText();
    } else {
      // 如果无法获取,使用简单的 HTML 转文本
      textContent = htmlContent.replace(/<[^>]*>/g, " ").trim();
    }

    currentContent.value = htmlContent;
    hasUnsavedChanges.value = htmlContent !== originalContent.value;
    hasUserEdited.value = true; // 标记用户已编辑

    emit("content-change", {
      text: textContent,
      html: htmlContent,
      hasChanges: hasUnsavedChanges.value,
    });

    // 触发防抖自动保存
    debouncedAutoSave();
  } catch (err) {
    console.error("获取编辑器内容失败:", err);
  } finally {
    // 延迟重置标记,避免立即触发新的更新
    setTimeout(() => {
      isUpdating.value = false;
    }, 100);
  }
};

// 加载文档内容
const loadDocument = async () => {
  loading.value = true;
  error.value = null;

  try {
    const fileId = props.fileId;
    let content = "";
    let blob: Blob | null = null;

    // 获取文件元信息以确定存储类型(非 chatAnswer 时)
    if (!props.isChatAnswer) {
      try {
        const metaRes = await filesApi.getFileMeta(fileId);
        if (metaRes?.data?.storageType) {
          fileStorageType.value = metaRes.data.storageType;
        }
      } catch (e) {
        console.warn("获取文件元信息失败,默认使用 LOCAL:", e);
      }
    }

    // 1. 尝试从持久化缓存读取
    try {
      const cached = await fileCache.getFile(fileId);
      if (cached) {
        if (cached.type === "word" && cached.content instanceof Blob) {
          console.log("Word 命中持久化缓存 (Blob):", fileId);
          blob = cached.content;
        } else if (cached.type === "word-html" && typeof cached.content === "string") {
          console.log("Word 命中持久化缓存 (HTML):", fileId);
          content = cached.content;
          // 注意:如果只有 HTML 没有 Blob,后续保存 Word 功能可能会受限
          // 这里我们优先尝试获取 Blob 以保证功能完整
        }
      }
    } catch (e) {
      console.warn("读取 Word 持久化缓存失败:", e);
    }

    // 如果没有命中有意义的缓存,则进入正常的加载流程
    if (!content && !blob) {
      // 如果是 Codex 文件,尝试从缓存读取
      if (props.isChatAnswer) {
        try {
          const cached = await fileCache.getFile(fileId);
          if (cached && cached.content instanceof Blob) {
            blob = cached.content;
          } else if (cached && typeof cached.content === "string") {
            content = cached.content;
            isWordDocument.value = false;
          } else {
            throw new Error("缓存中未找到文件内容");
          }
        } catch (error) {
          throw new Error("无法从缓存获取文件内容");
        }
      } else {
        // 检测文件扩展名
        const fileName = props.fileName || "";
        const fileExt = fileName.split(".").pop()?.toLowerCase() || "";
        const isDocx = fileExt === "docx";
        const isDoc = fileExt === "doc";
        isWordDocument.value = isDocx || isDoc;

        // 普通文件,使用文件下载 API(返回 Blob)
        const response = await filesApi.downloadFile(props.fileId);

        // 处理 Blob 响应
        // 如果响应被包装了,提取 Blob
        if (response instanceof Blob) {
          blob = response;
        } else if (response && typeof response === "object") {
          const anyResponse = response as any;
          if (anyResponse.data instanceof Blob) {
            blob = anyResponse.data;
          } else if (
            anyResponse.data?.code === 200 &&
            anyResponse.data?.data instanceof Blob
          ) {
            blob = anyResponse.data.data;
          }
        }

        if (blob instanceof Blob) {
          // 写入持久化缓存 (Blob 类型)
          await fileCache.setFile({
            fileId,
            content: blob,
            type: "word",
            fileName: props.fileName,
          });
        }
      }
    }

    // 处理获取到的内容 (不管是来自缓存还是 API)
    if (blob instanceof Blob) {
      const fileName = props.fileName || "";
      const fileExt = fileName.split(".").pop()?.toLowerCase() || "";
      const isDocx = fileExt === "docx";
      const isDoc = fileExt === "doc";
      isWordDocument.value = isDocx || isDoc;

      if (isDocx) {
        try {
          originalDocxBlob.value = blob;
          const arrayBuffer = await blob.arrayBuffer();
          const result = await mammoth.convertToHtml(
            { arrayBuffer },
            {
              styleMap: [
                "p[style-name='Heading 1'] => h1:fresh",
                "p[style-name='Heading 2'] => h2:fresh",
                "p[style-name='Heading 3'] => h3:fresh",
              ],
            },
          );
          content = result.value;
        } catch (mammothError: any) {
          console.error("Mammoth 解析失败:", mammothError);
          throw new Error(
            `Word 文档解析失败: ${mammothError.message || "文件格式可能不正确,请确保是标准的 .docx 文件"}`,
          );
        }
      } else if (isDoc) {
        throw new Error(
          "暂不支持预览 .doc 格式。请将其另存为 .docx 格式后再上传,或直接下载查看。",
        );
      } else {
        // 非 Word 文档,尝试获取文本内容
        try {
          const contentResponse = await filesApi.getFileContent(props.fileId);
          if (
            contentResponse &&
            contentResponse.data &&
            typeof contentResponse.data === "string"
          ) {
            content = contentResponse.data;
          } else {
            content = await blob.text();
          }
        } catch (contentError) {
          try {
            content = await blob.text();
          } catch (textError) {
            throw new Error(
              `无法读取文件内容: ${(textError as Error).message || "未知错误"}`,
            );
          }
        }
      }
    }

    // 后续逻辑保持不变

    // 如果内容为空或只有空白,设置默认内容
    if (!content || content.trim() === "") {
      content = "<p>开始编辑文档...</p>";
    }

    originalContent.value = content;
    currentContent.value = content;
    editorContent.value = content;
    hasUserEdited.value = false; // 重置编辑标记
    hasUnsavedChanges.value = false; // 重置未保存标记

    // 更新 editorKey 强制编辑器重新渲染
    editorKey.value = String(Date.now());

    loading.value = false;

    // 等待编辑器渲染后,尝试设置内容
    await nextTick();
    if (
      editorRef.value &&
      typeof (editorRef.value as any).setContent === "function"
    ) {
      (editorRef.value as any).setContent(content);
    }

    // 确保文档打开时滚动到顶部
    await nextTick();
    setTimeout(() => {
      const editorContent = document.querySelector(".umo-editor-content");
      if (editorContent) {
        editorContent.scrollTop = 0;
      }
    }, 100);

    // 启动内容监听器
    startContentWatcher();

    // TOS 文件启动定时同步
    if (isTosFile.value) {
      startTosSyncTimer();
    }
  } catch (err: any) {
    error.value = `加载失败: ${err.message || "未知错误"}`;
    loading.value = false;
    ElMessage.error(`文档加载失败: ${err.message || "未知错误"}`);
  }
};

// 启动内容监听器(轮询检查内容变化)
const startContentWatcher = () => {
  // 清除旧的定时器
  if (contentWatcherInterval.value) {
    clearInterval(contentWatcherInterval.value);
  }

  // 每2s检查一次内容是否变化 (从 500ms 提高到 2s,减少 CPU 占用)
  contentWatcherInterval.value = window.setInterval(() => {
    if (isUpdating.value || !editorRef.value) {
      return;
    }

    try {
      // 尝试从编辑器实例获取当前内容
      let currentEditorContent = "";
      if (typeof (editorRef.value as any).getHTML === "function") {
        currentEditorContent = (editorRef.value as any).getHTML();
      } else if (typeof (editorRef.value as any).getValue === "function") {
        currentEditorContent = (editorRef.value as any).getValue();
      } else {
        currentEditorContent = editorContent.value || "";
      }

      // 如果内容变化了,触发更新
      if (
        currentEditorContent &&
        currentEditorContent !== currentContent.value
      ) {
        editorContent.value = currentEditorContent;
        handleContentUpdate(currentEditorContent);
      }
    } catch (error) {
      // 静默失败,不影响正常使用
    }
  }, 2000);
};

// 防抖自动保存 - 用户停止编辑后自动保存
const debouncedAutoSave = () => {
  // 清除之前的定时器
  if (autoSaveTimer.value) {
    clearTimeout(autoSaveTimer.value);
  }

  // 设置新的定时器:用户停止编辑 10 秒后自动保存 (从 3s 增加到 10s 以解决编辑器卡顿)
  autoSaveTimer.value = window.setTimeout(() => {
    if (hasUserEdited.value && hasUnsavedChanges.value && !isSaving.value) {
      autoSaveDocument();
    }
  }, 10000); // 10秒防抖时间
};

// 处理编辑器失焦 - 失焦时立即保存
const handleEditorBlur = () => {
  // 清除防抖定时器,立即保存
  if (autoSaveTimer.value) {
    clearTimeout(autoSaveTimer.value);
  }

  if (hasUserEdited.value && hasUnsavedChanges.value && !isSaving.value) {
    autoSaveDocument();
  }
};

// 将 HTML 内容解析为 docx 段落数组
const parseHtmlToDocxParagraphs = (htmlContent: string): Paragraph[] => {
  const paragraphs: Paragraph[] = [];

  // 创建一个临时 DOM 元素来解析 HTML
  const tempDiv = document.createElement("div");
  tempDiv.innerHTML = htmlContent;

  // 处理文本节点和格式化元素
  const processTextContent = (element: HTMLElement): TextRun[] => {
    const textRuns: TextRun[] = [];

    const processNode = (node: Node) => {
      if (node.nodeType === Node.TEXT_NODE) {
        const text = node.textContent || "";
        if (text.trim()) {
          textRuns.push(new TextRun(text));
        }
      } else if (node.nodeType === Node.ELEMENT_NODE) {
        const el = node as HTMLElement;
        const tagName = el.tagName.toLowerCase();
        const text = el.textContent || "";

        if (text.trim()) {
          const isBold =
            tagName === "strong" ||
            tagName === "b" ||
            el.style.fontWeight === "bold" ||
            parseInt(el.style.fontWeight) >= 600;
          const isItalic =
            tagName === "em" ||
            tagName === "i" ||
            el.style.fontStyle === "italic";
          const isUnderline =
            tagName === "u" || el.style.textDecoration?.includes("underline");

          textRuns.push(
            new TextRun({
              text: text,
              bold: isBold,
              italics: isItalic,
              underline: isUnderline
                ? {
                    type: "single",
                  }
                : undefined,
            }),
          );
        }
      }
    };

    Array.from(element.childNodes).forEach(processNode);
    return textRuns;
  };

  // 遍历所有顶级节点
  const processNode = (node: Node) => {
    if (node.nodeType === Node.ELEMENT_NODE) {
      const element = node as HTMLElement;
      const tagName = element.tagName.toLowerCase();

      switch (tagName) {
        case "h1":
          paragraphs.push(
            new Paragraph({
              text: element.textContent || "",
              heading: HeadingLevel.HEADING_1,
              spacing: { after: 200 },
            }),
          );
          break;
        case "h2":
          paragraphs.push(
            new Paragraph({
              text: element.textContent || "",
              heading: HeadingLevel.HEADING_2,
              spacing: { after: 200 },
            }),
          );
          break;
        case "h3":
          paragraphs.push(
            new Paragraph({
              text: element.textContent || "",
              heading: HeadingLevel.HEADING_3,
              spacing: { after: 200 },
            }),
          );
          break;
        case "h4":
          paragraphs.push(
            new Paragraph({
              text: element.textContent || "",
              heading: HeadingLevel.HEADING_4,
              spacing: { after: 200 },
            }),
          );
          break;
        case "h5":
          paragraphs.push(
            new Paragraph({
              text: element.textContent || "",
              heading: HeadingLevel.HEADING_5,
              spacing: { after: 200 },
            }),
          );
          break;
        case "h6":
          paragraphs.push(
            new Paragraph({
              text: element.textContent || "",
              heading: HeadingLevel.HEADING_6,
              spacing: { after: 200 },
            }),
          );
          break;
        case "p":
          // 处理段落中的格式(粗体、斜体等)
          const textRuns = processTextContent(element);
          if (textRuns.length > 0) {
            paragraphs.push(
              new Paragraph({
                children: textRuns,
                spacing: { after: 200 },
              }),
            );
          } else if (element.textContent?.trim()) {
            paragraphs.push(
              new Paragraph({
                text: element.textContent.trim(),
                spacing: { after: 200 },
              }),
            );
          }
          break;
        case "br":
          paragraphs.push(new Paragraph({ text: "" }));
          break;
        case "ul":
        case "ol":
          // 处理列表
          const listItems = element.querySelectorAll("li");
          listItems.forEach((li) => {
            const liTextRuns = processTextContent(li);
            if (liTextRuns.length > 0) {
              paragraphs.push(
                new Paragraph({
                  children: liTextRuns,
                  bullet: { level: 0 },
                  spacing: { after: 100 },
                }),
              );
            } else if (li.textContent?.trim()) {
              paragraphs.push(
                new Paragraph({
                  text: li.textContent.trim(),
                  bullet: { level: 0 },
                  spacing: { after: 100 },
                }),
              );
            }
          });
          break;
        case "li":
          // 列表项已在父元素中处理,跳过
          break;
        case "div":
        case "span":
          // 对于 div 和 span,递归处理子节点
          Array.from(element.childNodes).forEach(processNode);
          break;
        default:
          // 对于其他元素,如果包含文本内容,创建段落
          const text = element.textContent?.trim();
          if (text) {
            paragraphs.push(
              new Paragraph({
                text: text,
                spacing: { after: 200 },
              }),
            );
          } else {
            // 否则递归处理子节点
            Array.from(element.childNodes).forEach(processNode);
          }
          break;
      }
    } else if (node.nodeType === Node.TEXT_NODE) {
      const text = node.textContent?.trim();
      if (text) {
        paragraphs.push(
          new Paragraph({
            text: text,
            spacing: { after: 200 },
          }),
        );
      }
    }
  };

  // 处理所有顶级节点
  Array.from(tempDiv.childNodes).forEach(processNode);

  // 如果没有解析到任何段落,至少创建一个包含文本内容的段落
  if (paragraphs.length === 0) {
    const textContent = tempDiv.textContent?.trim() || "";
    if (textContent) {
      paragraphs.push(
        new Paragraph({
          text: textContent,
          spacing: { after: 200 },
        }),
      );
    }
  }

  return paragraphs;
};

// 将 HTML 内容转换为 Word 文档 Blob
const convertHtmlToDocx = async (htmlContent: string): Promise<Blob> => {
  try {
    // 如果内容为空,使用默认内容
    if (!htmlContent || htmlContent.trim() === "") {
      htmlContent = "<p>开始编辑文档...</p>";
    }

    // 解析 HTML 为 docx 段落数组
    const paragraphs = parseHtmlToDocxParagraphs(htmlContent);

    if (paragraphs.length === 0) {
      throw new Error("解析 HTML 后未生成任何段落");
    }

    // 创建 Word 文档
    const doc = new Document({
      sections: [
        {
          properties: {},
          children: paragraphs,
        },
      ],
    });

    // 生成 Blob
    const blob = await Packer.toBlob(doc);
    return blob;
  } catch (err: any) {
    throw new Error(`转换失败: ${err.message || "未知错误"}`);
  }
};

// 获取编辑器的最新 HTML 内容
const getEditorHtmlContent = (): string => {
  let htmlContent = "";

  // 优先从编辑器实例获取内容
  if (editorRef.value) {
    const editor = editorRef.value as any;
    // 尝试多种方法获取 HTML 内容
    if (typeof editor.getHTML === "function") {
      htmlContent = editor.getHTML();
    } else if (typeof editor.getContent === "function") {
      htmlContent = editor.getContent();
    } else if (typeof editor.getValue === "function") {
      htmlContent = editor.getValue();
    }
  }

  // 如果从编辑器获取失败,使用缓存的当前内容
  if (!htmlContent || htmlContent.trim() === "") {
    htmlContent = currentContent.value || editorContent.value || "";
  }

  return htmlContent;
};

// 保存 Word 文档(将 HTML 转换为 Word 并调用 replaceFile)
const saveWordDocument = async (htmlContent?: string): Promise<void> => {
  try {
    // 获取最新的 HTML 内容
    const finalHtmlContent = htmlContent || getEditorHtmlContent();

    // 验证内容不为空
    if (!finalHtmlContent || finalHtmlContent.trim() === "") {
      throw new Error("编辑器内容为空,无法保存");
    }

    // 将 HTML 转换为 Word 文档 Blob
    const docxBlob = await convertHtmlToDocx(finalHtmlContent);

    // 验证生成的 Blob 是否有效
    if (!docxBlob || docxBlob.size === 0) {
      throw new Error("生成的 Word 文档为空");
    }

    // 创建 File 对象
    const fileName = props.fileName || "document.docx";
    const file = new File([docxBlob], fileName, {
      type: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
    });

    // 调用 replaceFile API 替换文件(传入 storageType 以区分 LOCAL/TOS)
    await filesApi.replaceFile(props.fileId, file, fileStorageType.value);

    // 更新原始 Blob 引用,以便后续使用
    originalDocxBlob.value = docxBlob;
  } catch (err: any) {
    console.error("❌ 保存 Word 文档失败:", err);
    throw err;
  }
};

// 自动保存文档
const autoSaveDocument = async (forceRemoteSave = false) => {
  // forceRemoteSave 模式只需检查 hasPendingTosSync
  if (forceRemoteSave) {
    if (!hasPendingTosSync.value || isSaving.value) return;
  } else {
    if (!hasUnsavedChanges.value || isSaving.value) return;
  }

  // 如果是智能体回答文件(草稿),跳过自动保存
  if (props.isChatAnswer) {
    return;
  }

  try {
    isSaving.value = true;

    // TOS 文件:自动保存只写 IndexedDB 缓存(除非强制远端)
    if (isTosFile.value && !forceRemoteSave) {
      const latestContent = getEditorHtmlContent();
      await fileCache.setFile({
        fileId: props.fileId,
        content: latestContent,
        type: "word-html",
        fileName: props.fileName,
      });
      currentContent.value = latestContent;
      originalContent.value = latestContent;
      hasUnsavedChanges.value = false;
      hasPendingTosSync.value = true;

      emit("file-saved", {
        fileId: props.fileId,
        fileName: props.fileName,
        content: currentContent.value,
        isAutoSave: true,
      });
      console.log("💾 TOS Word 文件已保存到本地缓存,等待定时同步");
      return;
    }

    // 如果是 Word 文档,转换为 Word 格式并保存
    if (isWordDocument.value) {
      const latestContent = getEditorHtmlContent();
      await saveWordDocument(latestContent);
      currentContent.value = latestContent;
      originalContent.value = latestContent;
    } else if (props.isChatAnswer) {
      const latestContent = getEditorHtmlContent();
      await apiUpdateDraft(props.fileId, {
        content: latestContent,
        title: props.fileName.replace(/\.[^/.]+$/, ""),
      });
      currentContent.value = latestContent;
      originalContent.value = latestContent;
    } else {
      const content = currentContent.value;
      originalContent.value = content;
    }

    hasUnsavedChanges.value = false;
    hasPendingTosSync.value = false;

    emit("file-saved", {
      fileId: props.fileId,
      fileName: props.fileName,
      content: currentContent.value,
      isAutoSave: true,
    });
  } catch (err: any) {
    ElMessage.error(`自动保存失败: ${err.message}`);
  } finally {
    isSaving.value = false;
  }
};

// TOS 定时同步
const syncToTos = async () => {
  if (!hasPendingTosSync.value || isSaving.value) return;
  console.log("🔄 TOS 定时同步触发");
  await autoSaveDocument(true);
};

const startTosSyncTimer = () => {
  stopTosSyncTimer();
  tosSyncTimer.value = window.setInterval(() => {
    syncToTos();
  }, TOS_SYNC_INTERVAL);
};

const stopTosSyncTimer = () => {
  if (tosSyncTimer.value) {
    clearInterval(tosSyncTimer.value);
    tosSyncTimer.value = null;
  }
};

// 保存文档(手动保存,供外部调用)
const saveDocument = async (isAutoSave: boolean = false) => {
  if (!hasUnsavedChanges.value) {
    console.log("没有未保存的更改");
    return;
  }

  try {
    isSaving.value = true;

    // 如果是 Word 文档,转换为 Word 格式并保存
    if (isWordDocument.value) {
      // 获取最新的编辑器内容
      const latestContent = getEditorHtmlContent();
      await saveWordDocument(latestContent);
      // 更新当前内容为保存的内容
      currentContent.value = latestContent;
      originalContent.value = latestContent;
    } else if (props.isChatAnswer) {
      // 如果是草稿,使用草稿更新 API
      const latestContent = getEditorHtmlContent();
      await apiUpdateDraft(props.fileId, {
        content: latestContent,
        title: props.fileName.replace(/\.[^/.]+$/, ""),
      });
      currentContent.value = latestContent;
      originalContent.value = latestContent;
    } else {
      // 非 Word 文档,使用原有的保存逻辑(如果需要)
      const content = currentContent.value;
      originalContent.value = content;
    }

    hasUnsavedChanges.value = false;

    if (!isAutoSave) {
      ElMessage.success("保存成功");
    }

    emit("file-saved", {
      fileId: props.fileId,
      fileName: props.fileName,
      content: currentContent.value,
      isAutoSave: isAutoSave,
    });

    // 触发新手任务:编辑/生成文档
    triggerNewbieTask("doc_generate_edit");
  } catch (err: any) {
    ElMessage.error(`保存失败: ${err.message}`);
  } finally {
    isSaving.value = false;
  }
};

// 手动保存(供外部调用)
const save = async () => {
  await saveDocument(false);
};

// 获取内容(供外部调用)
const getContent = () => {
  return currentContent.value;
};

// 设置内容(供外部调用)
const setContent = (content: string) => {
  editorContent.value = content;
  currentContent.value = content;

  // 尝试通过编辑器实例设置内容
  if (
    editorRef.value &&
    typeof (editorRef.value as any).setContent === "function"
  ) {
    (editorRef.value as any).setContent(content);
  }
};

// 暴露方法给父组件
defineExpose({
  save,
  getContent,
  setContent,
  hasUnsavedChanges: () => hasUnsavedChanges.value,
});

// 组件挂载
onMounted(async () => {
  // 确保在真正需要渲染编辑器时才加载 @umoteam/editor
  await loadUmoEditorIfNeeded();
  await loadDocument();

  // 等待编辑器初始化完成后,添加失焦事件监听
  await nextTick();
  setTimeout(() => {
    setupEditorBlurListener();
  }, 500);
});

// 设置编辑器失焦监听
const setupEditorBlurListener = () => {
  try {
    // 查找 ProseMirror 编辑器元素
    const editorElement = document.querySelector(".ProseMirror");
    if (editorElement) {
      editorElement.addEventListener("blur", handleEditorBlur);
    }
  } catch (error) {
    console.error("❌ 设置编辑器失焦监听失败:", error);
  }
};

// 组件卸载前清理
onBeforeUnmount(() => {
  // 清除所有定时器
  if (autoSaveTimer.value) {
    clearTimeout(autoSaveTimer.value);
  }
  if (contentWatcherInterval.value) {
    clearInterval(contentWatcherInterval.value);
  }

  // 执行自动保存
  stopTosSyncTimer();
  if (!isSaving.value) {
    if (isTosFile.value) {
      // TOS 文件:如果有未保存的编辑 或 已缓存但未同步的修改,统一直接同步远端
      if ((hasUserEdited.value && hasUnsavedChanges.value) || hasPendingTosSync.value) {
        console.log("🔄 组件销毁前同步 TOS 文件到远端");
        hasPendingTosSync.value = true;
        autoSaveDocument(true);
      }
    } else {
      // LOCAL 文件:正常保存
      if (hasUserEdited.value && hasUnsavedChanges.value) {
        autoSaveDocument();
      }
    }
  }

  // 移除失焦事件监听
  try {
    const editorElement = document.querySelector(".ProseMirror");
    if (editorElement) {
      editorElement.removeEventListener("blur", handleEditorBlur);
    }
  } catch (error) {
    console.error("移除编辑器失焦监听失败:", error);
  }

  // UmoEditor 组件会自动处理销毁
});

// 监听 fileId 变化
watch(
  () => props.fileId,
  async (newFileId, oldFileId) => {
    if (newFileId !== oldFileId) {
      // 文件切换前:同步旧文件的修改
      if (!isSaving.value && isTosFile.value) {
        if ((hasUserEdited.value && hasUnsavedChanges.value) || hasPendingTosSync.value) {
          hasPendingTosSync.value = true;
          autoSaveDocument(true);
        }
      } else if (!isSaving.value && hasUserEdited.value && hasUnsavedChanges.value) {
        autoSaveDocument();
      }

      // 清除所有定时器
      if (autoSaveTimer.value) {
        clearTimeout(autoSaveTimer.value);
      }
      if (contentWatcherInterval.value) {
        clearInterval(contentWatcherInterval.value);
      }
      stopTosSyncTimer();

      // 重置状态
      hasUserEdited.value = false;
      hasUnsavedChanges.value = false;
      isSaving.value = false;
      isUpdating.value = false;

      // 重置 TOS 状态
      fileStorageType.value = "LOCAL";
      hasPendingTosSync.value = false;

      await loadDocument();

      // 重新设置失焦监听
      await nextTick();
      setTimeout(() => {
        setupEditorBlurListener();
      }, 500);
    }
  },
);

// 监听编辑器内容变化(作为备用机制)
watch(
  editorContent,
  (newValue) => {
    if (!isUpdating.value && newValue !== null) {
      handleContentUpdate(newValue);
    }
  },
  { deep: false },
);
</script>

<style scoped lang="scss">
.word-editor-container {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  background-color: var(--color-bg);
  overflow: hidden;

  .loading-state,
  .error-state {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    flex: 1;
    gap: 16px;
    color: var(--color-text-secondary);

    i {
      font-size: 48px;
    }

    span,
    .error-text {
      font-size: 14px;
      margin: 0;
    }
  }

  .error-state {
    i {
      color: #f56c6c;
    }
  }

  .editor-wrapper {
    flex: 1;
    overflow: hidden;
    display: flex;
    flex-direction: column;
    background-color: var(--color-bg);

    // Umo Editor 组件样式覆盖
    :deep(.umo-editor) {
      height: 100%;
      display: flex;
      flex-direction: column;
      background-color: var(--color-bg);
    }

    :deep(.umo-toolbar) {
      background-color: var(--color-card);
      border-bottom: 1px solid var(--color-border);
      flex-shrink: 0;
    }

    // 隐藏编辑器顶部的保存状态提示
    :deep(.umo-toolbar__save-status),
    :deep(.umo-save-status),
    :deep(.umo-document-status),
    :deep([class*="save-status"]),
    :deep([class*="document-status"]),
    // 更精确的选择器,针对"文档未保存"状态提示
    :deep(.umo-toolbar .umo-status),
    :deep(.umo-toolbar .umo-status-indicator),
    :deep(.umo-toolbar .umo-document-status-indicator),
    :deep(.umo-toolbar [class*="status"]),
    :deep(.umo-toolbar [class*="unsaved"]),
    :deep(.umo-toolbar [class*="document-not-saved"]),
    // 针对包含"文档未保存"文本的元素(使用更通用的方法)
    :deep(.umo-toolbar [data-status="unsaved"]),
    :deep(.umo-toolbar [data-document-status]),
    // 针对工具栏右侧的状态区域
    :deep(.umo-toolbar .umo-toolbar-right),
    :deep(.umo-toolbar .umo-toolbar-status),
    :deep(.umo-toolbar .umo-toolbar-info) {
      display: none !important;
    }

    :deep(.umo-editor-content) {
      flex: 1;
      overflow-y: auto;
      background-color: var(--color-bg);
      // 确保内容从顶部开始显示
      scroll-behavior: auto;
    }

    :deep(.umo-zoomable-container.umo-page-container) {
      padding: 0 !important;
      background: var(--color-bg);
    }

    // 禁用编辑器的自动滚动行为
    :deep(.umo-editor-content),
    :deep(.umo-page-container) {
      scroll-behavior: auto !important;
    }

    :deep(.ProseMirror) {
      min-height: 100%;
      background-color: var(--color-bg);
      color: var(--color-text);
      outline: none;

      &:focus {
        outline: none;
      }

      p {
        margin: 0 0 1em 0;
        line-height: 1.6;
      }

      h1,
      h2,
      h3,
      h4,
      h5,
      h6 {
        margin: 1.5em 0 0.5em 0;
        font-weight: 600;
        line-height: 1.4;
        color: var(--color-text);
      }

      // 选中文本样式
      ::selection {
        background-color: rgba(24, 144, 255, 0.2);
      }
    }
  }
}

// 深色主题适配
:root.theme-dark {
  .word-editor-container {
    .editor-wrapper {
      background-color: var(--color-bg, #1a1a1a);

      :deep(.umo-editor) {
        background-color: var(--color-bg, #1a1a1a);
      }

      :deep(.umo-toolbar) {
        background-color: var(--color-card, #2a2a2a);
        border-bottom-color: var(--color-border, #333);
      }

      :deep(.umo-editor-content) {
        background-color: var(--color-bg, #1a1a1a);
      }

      :deep(.ProseMirror) {
        background-color: var(--color-bg, #1a1a1a);
        color: var(--color-text, #eee);

        h1,
        h2,
        h3,
        h4,
        h5,
        h6 {
          color: var(--color-text, #eee);
        }
      }
    }
  }
}
</style>