TextViewer.vue 26.2 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
<template>
  <div class="text-viewer">
    <!-- 工具栏 -->
    <div class="text-toolbar">
      <div class="toolbar-left">
        <el-select
          v-model="syntaxHighlighting"
          size="small"
          placeholder="语法高亮"
          @change="applySyntaxHighlighting"
          style="width: 120px"
        >
          <el-option label="无高亮" value="plain"></el-option>
          <el-option label="JavaScript" value="javascript"></el-option>
          <el-option label="HTML" value="html"></el-option>
          <el-option label="CSS" value="css"></el-option>
          <el-option label="JSON" value="json"></el-option>
          <el-option label="XML" value="xml"></el-option>
          <el-option label="Python" value="python"></el-option>
          <el-option label="SQL" value="sql"></el-option>
          <el-option label="Markdown" value="markdown"></el-option>
        </el-select>

        <el-button-group class="ml-10">
          <el-button size="small" @click="increaseFontSize" title="增大字体">
            <template #icon>
              <svg
                xmlns="http://www.w3.org/2000/svg"
                viewBox="0 0 1024 1024"
                width="16"
                height="16"
              >
                <path
                  fill="currentColor"
                  d="M512 128a384 384 0 1 0 384 384A384 384 0 0 0 512 128zm192 416H544v160a32 32 0 0 1-64 0V544H320a32 32 0 0 1 0-64h160V320a32 32 0 0 1 64 0v160h160a32 32 0 0 1 0 64z"
                />
              </svg>
            </template>
          </el-button>
          <el-button size="small" @click="decreaseFontSize" title="减小字体">
            <template #icon>
              <svg
                xmlns="http://www.w3.org/2000/svg"
                viewBox="0 0 1024 1024"
                width="16"
                height="16"
              >
                <path
                  fill="currentColor"
                  d="M512 128a384 384 0 1 0 384 384A384 384 0 0 0 512 128zm192 416H320a32 32 0 0 1 0-64h384a32 32 0 0 1 0 64z"
                />
              </svg>
            </template>
          </el-button>
          <el-button size="small" @click="resetFontSize" title="重置字体大小">
            <template #icon>
              <svg
                xmlns="http://www.w3.org/2000/svg"
                viewBox="0 0 1024 1024"
                width="16"
                height="16"
              >
                <path
                  fill="currentColor"
                  d="M512 64C264.6 64 64 264.6 64 512s200.6 448 448 448 448-200.6 448-448S759.4 64 512 64zm192 472c0 4.4-3.6 8-8 8H544v152c0 4.4-3.6 8-8 8h-48c-4.4 0-8-3.6-8-8V544H328c-4.4 0-8-3.6-8-8v-48c0-4.4 3.6-8 8-8h152V328c0-4.4 3.6-8 8-8h48c4.4 0 8 3.6 8 8v152h152c4.4 0 8 3.6 8 8v48z"
                />
              </svg>
            </template>
          </el-button>
        </el-button-group>

        <el-switch
          v-model="wordWrap"
          active-text="自动换行"
          inactive-text="不换行"
          class="ml-10"
        />
      </div>
      <div class="toolbar-right">
        <el-button size="small" @click="downloadFileContent">
          <template #icon>
            <svg
              xmlns="http://www.w3.org/2000/svg"
              viewBox="0 0 1024 1024"
              width="16"
              height="16"
            >
              <path
                fill="currentColor"
                d="M505.7 661a8 8 0 0 0 12.6 0l112-141.7c4.1-5.2.4-12.9-6.3-12.9h-74.1V168c0-4.4-3.6-8-8-8h-60c-4.4 0-8 3.6-8 8v338.3H400c-6.7 0-10.4 7.7-6.3 12.9l112 141.8zM878 626h-60c-4.4 0-8 3.6-8 8v154H214V634c0-4.4-8-8-8-8h-60c-4.4 0-8 3.6-8 8v198c0 17.7 14.3 32 32 32h684c17.7 0 32-14.3 32-32V634c0-4.4-3.6-8-8-8z"
              />
            </svg>
          </template>
          下载
        </el-button>
      </div>
    </div>

    <!-- 文本容器 -->
    <div class="text-container" :class="{ 'wrap-text': wordWrap }">
      <textarea
        v-if="isEditing"
        v-model="editableContent"
        ref="textareaRef"
        class="editor-textarea"
        :style="{ fontSize: `${fontSize}px` }"
        @blur="handleEditorBlur"
      />

      <div v-else-if="loading" class="loading-container">
        <el-skeleton :rows="20" animated />
      </div>

      <div v-else-if="error" class="error-container">
        <i class="fas fa-exclamation-triangle"></i>
        <p>{{ error }}</p>
        <el-button size="small" type="primary" @click="loadContent"
          >重试</el-button
        >
      </div>

      <pre
        v-else
        ref="textContentRef"
        :class="['text-content', syntaxHighlighting]"
        :style="{ fontSize: `${fontSize}px` }"
        >{{ content }}</pre
      >
    </div>
  </div>
</template>

<script setup lang="ts">
import {
  ref,
  computed,
  onMounted,
  onBeforeUnmount,
  onActivated,
  onDeactivated,
  watch,
  nextTick,
} from "vue";
import {
  ElButton,
  ElMessage,
  ElSelect,
  ElOption,
  ElButtonGroup,
  ElSwitch,
  ElSkeleton,
} from "element-plus";
import { downloadFile, saveFileContent, getFileMeta } from "@/api/files";
import { apiUpdateDraft } from "@/api/drafts";
import { fileCache } from "@/utils/fileCache";

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

interface Emits {
  (e: "mounted"): void;
}

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

// 状态管理
const loading = ref(true);
const error = ref<string | null>(null);
const content = ref("");
const editableContent = ref("");
const currentContent = ref(""); // 当前内容(用于比较)
const originalContent = ref(""); // 原始内容
const lastSavedContent = ref(""); // 最后保存的内容
const syntaxHighlighting = ref("plain");
const fontSize = ref(14);
const wordWrap = ref(true);
const isEditing = ref(true);
const textContentRef = ref<HTMLPreElement | null>(null);
const textareaRef = ref<HTMLTextAreaElement | null>(null);

// 多重自动保存机制相关状态
const hasUserEdited = ref(false); // 用户是否编辑过
const hasUnsavedChanges = ref(false); // 是否有未保存的更改
const isSaving = ref(false); // 是否正在保存
const isDestroying = ref(false); // 是否正在销毁组件

// TOS 存储相关状态
const storageType = ref<string>("LOCAL"); // 文件存储类型
const hasPendingTosSync = ref(false); // 是否有待同步到 TOS 的修改
const tosSyncTimer = ref<number | null>(null); // TOS 定时同步定时器
const TOS_SYNC_INTERVAL = 60000; // TOS 同步间隔:60 秒
const isTosFile = computed(() => storageType.value && storageType.value !== "LOCAL");

// ===== TextViewer 滚动位置缓存(KeepAlive)=====
const textScrollTop = ref(0);

// 获取滚动容器
const getScrollEl = (): HTMLElement | null => {
  // 编辑态
  if (isEditing.value) {
    return textareaRef.value;
  }
  // 预览态
  return textContentRef.value;
};

// 滚动监听,实时记录滚动位置
const handleScroll = () => {
  const el = getScrollEl();
  if (el) {
    textScrollTop.value = el.scrollTop;
  }
};

// 定时器管理
const autoSaveTimer = ref<number | null>(null); // 防抖自动保存定时器
const contentWatcherInterval = ref<number | null>(null); // 内容监听定时器

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

  try {
    const fileId = props.fileId;

    // 获取文件元信息以确定存储类型(非 chatAnswer 时)
    // 必须在缓存检查之前执行,否则缓存命中时 storageType 始终为默认值 LOCAL
    if (!props.isChatAnswer) {
      try {
        const metaRes = await getFileMeta(props.fileId);
        if (metaRes?.data?.storageType) {
          storageType.value = metaRes.data.storageType;
        }
      } catch (e) {
        console.warn("获取文件元信息失败,默认使用 LOCAL:", e);
      }
    }

    // 1. 尝试从持久化缓存读取
    try {
      const cached = await fileCache.getFile(fileId);
      if (cached) {
        // 如果缓存中是字符串,直接使用
        if (typeof cached.content === "string") {
          console.log("文本文件命中持久化缓存:", fileId);
          content.value = cached.content;
          editableContent.value = cached.content;
          currentContent.value = cached.content;
          originalContent.value = cached.content;
          lastSavedContent.value = cached.content;

          detectSyntaxHighlighting();
          startContentWatcher();
          // TOS 文件启动定时同步
          if (isTosFile.value) {
            startTosSyncTimer();
          }
          loading.value = false;
          return;
        }
        // 如果缓存中是 Blob(来自 Codex),转换为字符串
        if (cached.content instanceof Blob) {
          console.log("文本文件从 Blob 缓存转换:", fileId);
          const text = await cached.content.text();
          content.value = text;
          editableContent.value = text;
          currentContent.value = text;
          originalContent.value = text;
          lastSavedContent.value = text;

          detectSyntaxHighlighting();
          startContentWatcher();
          // TOS 文件启动定时同步
          if (isTosFile.value) {
            startTosSyncTimer();
          }
          loading.value = false;
          return;
        }
      }
    } catch (e) {
      console.warn("读取文本持久化缓存失败:", e);
    }

    console.log("开始加载文本文件,fileId:", props.fileId, "isChatAnswer:", props.isChatAnswer, "storageType:", storageType.value);
    // 统一使用文件下载 API
    const response = await downloadFile(props.fileId);
    console.log("文本文件加载响应:", response);

    let text = "";

    // 处理不同的响应格式
    if (response instanceof Blob) {
      text = await response.text();
    } else if (typeof response === "string") {
      text = response;
    } else if ((response as any).data) {
      const data = (response as any).data;
      if (data instanceof Blob) {
        text = await data.text();
      } else if (typeof data === 'object' && data.content) {
        text = data.content;
      } else {
        text = String(data);
      }
    } else {
      throw new Error("无法解析文件内容");
    }

    // 2. 写入持久化缓存
    await fileCache.setFile({
      fileId,
      content: text,
      type: "text",
      fileName: props.fileName,
    });

    content.value = text;
    editableContent.value = text;
    currentContent.value = text;
    originalContent.value = text;
    lastSavedContent.value = text;

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

    // 自动检测语法高亮
    detectSyntaxHighlighting();

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

    // TOS 文件启动定时同步
    if (isTosFile.value) {
      startTosSyncTimer();
    }

    loading.value = false;
    console.log("文本文件加载成功,内容长度:", text.length);
  } catch (err: any) {
    console.error("加载文件内容失败:", err);
    error.value = err.message || "加载文件内容失败";
    loading.value = false;
    ElMessage.error(`加载文件失败: ${error.value}`);
  }
};

// 自动检测语法高亮
const detectSyntaxHighlighting = () => {
  const fileName = props.fileName.toLowerCase();
  if (fileName.endsWith(".js") || fileName.endsWith(".jsx")) {
    syntaxHighlighting.value = "javascript";
  } else if (fileName.endsWith(".html") || fileName.endsWith(".htm")) {
    syntaxHighlighting.value = "html";
  } else if (fileName.endsWith(".css")) {
    syntaxHighlighting.value = "css";
  } else if (fileName.endsWith(".json")) {
    syntaxHighlighting.value = "json";
  } else if (fileName.endsWith(".xml")) {
    syntaxHighlighting.value = "xml";
  } else if (fileName.endsWith(".py")) {
    syntaxHighlighting.value = "python";
  } else if (fileName.endsWith(".sql")) {
    syntaxHighlighting.value = "sql";
  } else if (fileName.endsWith(".md")) {
    syntaxHighlighting.value = "markdown";
  } else {
    syntaxHighlighting.value = "plain";
  }
};

// 应用语法高亮
const applySyntaxHighlighting = () => {
  console.log("应用语法高亮:", syntaxHighlighting.value);
  // 这里可以集成 highlight.js 或 prismjs 等语法高亮库
  // 目前只是设置 CSS 类名
};

// 字体大小控制
const increaseFontSize = () => {
  fontSize.value = Math.min(24, fontSize.value + 1);
};

const decreaseFontSize = () => {
  fontSize.value = Math.max(10, fontSize.value - 1);
};

const resetFontSize = () => {
  fontSize.value = 14;
};

// 保存文本文件(多重自动保存机制)
// forceRemote: 强制同步到远端(用于关闭/离开时的兜底上传)
const saveTextFile = async (forceRemote = false) => {
  // forceRemote 模式只需检查 hasPendingTosSync,不依赖 hasUnsavedChanges
  if (forceRemote) {
    if (!hasPendingTosSync.value || isSaving.value) return;
  } else {
    if (!hasUnsavedChanges.value || isSaving.value) return;
  }

  try {
    isSaving.value = true;
    console.log("💾 开始保存文本文件,fileId:", props.fileId, "storageType:", storageType.value, "forceRemote:", forceRemote);

    // TOS 文件:自动保存只写本地缓存,不上传远端(除非 forceRemote)
    if (isTosFile.value && !forceRemote) {
      // 只写 IndexedDB 缓存
      await fileCache.setFile({
        fileId: props.fileId,
        content: editableContent.value,
        type: "text",
        fileName: props.fileName,
      });

      // 更新保存状态
      content.value = editableContent.value;
      currentContent.value = editableContent.value;
      lastSavedContent.value = editableContent.value;
      originalContent.value = editableContent.value;
      hasUnsavedChanges.value = false;
      hasUserEdited.value = false;
      hasPendingTosSync.value = true; // 标记有待同步到 TOS 的修改

      console.log("💾 TOS 文件已保存到本地缓存,等待定时同步");
      return;
    }

    // LOCAL 文件或强制远端同步:调用 API 保存文件内容
    let response;
    if (props.isChatAnswer) {
      response = await apiUpdateDraft(props.fileId, {
        content: editableContent.value,
        title: props.fileName.replace(/\.[^/.]+$/, ""),
      });
    } else {
      response = await saveFileContent(props.fileId, {
        content: editableContent.value,
        fileName: props.fileName,
      }, storageType.value);
    }

    // 检查保存是否成功
    const anyResponse = response as any;
    const isSuccess =
      response && (anyResponse.code === 200 || anyResponse.status === 200);

    if (isSuccess) {
      // 更新保存状态
      content.value = editableContent.value;
      currentContent.value = editableContent.value;
      lastSavedContent.value = editableContent.value;
      originalContent.value = editableContent.value;
      hasUnsavedChanges.value = false;
      hasUserEdited.value = false;
      hasPendingTosSync.value = false; // 已同步到远端

      // 同步成功后更新 IndexedDB 缓存
      if (isTosFile.value) {
        await fileCache.setFile({
          fileId: props.fileId,
          content: editableContent.value,
          type: "text",
          fileName: props.fileName,
        });
      }
    } else {
      const errorMsg = (response as any)?.message || "文件保存失败";
      throw new Error(errorMsg);
    }
  } catch (error) {
    console.error("❌ 保存文本文件失败:", error);
    ElMessage.error(`文本内容保存失败: ${(error as Error).message}`);
  } finally {
    isSaving.value = false;
  }
};

// TOS 定时同步:每 60 秒检查是否有待同步的修改
const syncToTos = async () => {
  if (!hasPendingTosSync.value || isSaving.value) return;
  console.log("🔄 TOS 定时同步触发");
  await saveTextFile(true);
};

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

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

// 下载文件
const downloadFileContent = async () => {
  try {
    let blob: Blob;

    // 如果是 Codex 文件,尝试从缓存读取
    if (props.isChatAnswer) {
      try {
        const cached = await fileCache.getFile(props.fileId);
        if (cached && cached.content instanceof Blob) {
          blob = cached.content;
        } else if (cached && typeof cached.content === "string") {
          blob = new Blob([cached.content], { type: "text/plain" });
        } else {
          // 如果没有缓存,使用当前内容
          blob = new Blob([content.value], { type: "text/plain" });
        }
      } catch (error) {
        // 如果缓存读取失败,使用当前内容
        blob = new Blob([content.value], { type: "text/plain" });
      }
    } else {
      // 普通文件使用文件下载 API
      const response = await downloadFile(props.fileId);
      if (response instanceof Blob) {
        blob = response;
      } else if ((response as any).data instanceof Blob) {
        blob = (response as any).data;
      } else {
        // 如果没有 Blob,创建一个包含文本内容的 Blob
        blob = new Blob([content.value], { type: "text/plain" });
      }
    }

    const url = window.URL.createObjectURL(blob);
    const a = document.createElement("a");
    a.href = url;
    a.download = props.fileName;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    window.URL.revokeObjectURL(url);

    ElMessage.success("文件下载成功");
  } catch (err: any) {
    console.error("下载文件失败:", err);
    ElMessage.error(`文件下载失败: ${err.message || "未知错误"}`);
  }
};

// 监听 fileId 变化,重新加载内容
watch(
  () => props.fileId,
  (newFileId, oldFileId) => {
    // 滚动缓存重置(新文件语义)
    textScrollTop.value = 0;
    if (newFileId !== oldFileId) {
      console.log("📝 检测到 fileId 变化,重新加载文本:", {
        oldFileId,
        newFileId,
      });

      // TOS 文件切换前:先同步旧文件的修改到远端
      if (!isSaving.value && isTosFile.value) {
        if ((hasUserEdited.value && hasUnsavedChanges.value) || hasPendingTosSync.value) {
          hasPendingTosSync.value = true;
          saveTextFile(true);
        }
      } else if (!isSaving.value && hasUserEdited.value && hasUnsavedChanges.value) {
        // LOCAL 文件:正常保存
        saveTextFile();
      }

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

      // 重置状态
      isEditing.value = true; // 默认进入编辑模式
      fontSize.value = 14;
      wordWrap.value = true;
      syntaxHighlighting.value = "plain";

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

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

      // 重新加载内容
      loadContent();
    }
  },
);

// 处理内容变化
const handleContentChange = (newContent: string) => {
  currentContent.value = newContent;
  hasUserEdited.value = true;
  hasUnsavedChanges.value = newContent !== lastSavedContent.value;

  console.log("📝 内容发生变化:", {
    newContentLength: newContent.length,
    lastSavedLength: lastSavedContent.value.length,
    hasUnsavedChanges: hasUnsavedChanges.value,
    hasUserEdited: hasUserEdited.value,
  });

  // 触发防抖自动保存机制
  debouncedAutoSave();
};

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

  console.log("⏰ 设置防抖自动保存定时器,10秒后执行");

  // 设置新的定时器:用户停止编辑 10 秒后自动保存 (从 3s 增加到 10s 以解决编辑器卡顿)
  autoSaveTimer.value = window.setTimeout(() => {
    console.log("⏰ 防抖定时器触发,检查保存条件:", {
      hasUserEdited: hasUserEdited.value,
      hasUnsavedChanges: hasUnsavedChanges.value,
      isSaving: isSaving.value,
    });

    if (hasUserEdited.value && hasUnsavedChanges.value && !isSaving.value) {
      console.log("✅ 条件满足,触发防抖自动保存");
      saveTextFile();
    } else {
      console.log("❌ 条件不满足,跳过防抖自动保存");
    }
  }, 3000); // 3秒防抖时间
};

// 注意:移除了立即保存调度,只保留防抖自动保存和失焦保存

// 启动内容监听器
const startContentWatcher = () => {
  // 清除之前的监听器
  if (contentWatcherInterval.value) {
    clearInterval(contentWatcherInterval.value);
  }

  console.log("👁️ 启动内容监听器,每500ms检查一次");

  // 每500ms检查内容变化
  contentWatcherInterval.value = window.setInterval(() => {
    if (isDestroying.value) {
      return;
    }

    try {
      // 检查当前编辑内容是否与记录的内容不同
      if (editableContent.value !== currentContent.value) {
        console.log("👁️ 内容监听器检测到内容变化");
        handleContentChange(editableContent.value);
      }
    } catch (error) {
      console.error("内容监听器错误:", error);
    }
  }, 2000); // 增加监听间隔,从 500ms 提高到 2s,减少 CPU 占用
};

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

  if (hasUserEdited.value && hasUnsavedChanges.value && !isSaving.value) {
    console.log("👋 编辑器失焦,立即保存");
    saveTextFile();
  }
};

// 注意:不使用 watch 监听 editableContent,因为会与内容监听器重复触发
// 只使用 setInterval 内容监听器来检测变化

// 组件销毁时的清理逻辑
onBeforeUnmount(() => {
  // 滚动事件解绑
  const el = getScrollEl();
  if (el) {
    el.removeEventListener("scroll", handleScroll);
  }

  isDestroying.value = true;

  // 清除所有定时器
  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; // 确保 forceRemote 检查通过
        saveTextFile(true);
      }
    } else {
      // LOCAL 文件:正常保存
      if (hasUserEdited.value && hasUnsavedChanges.value) {
        console.log("🔄 组件销毁前自动保存");
        saveTextFile();
      }
    }
  }
});

onMounted(() => {
  loadContent();
  emit("mounted");
  // 滚动监听(KeepAlive 场景)
  nextTick(() => {
    const el = getScrollEl();
    if (el) {
      el.addEventListener("scroll", handleScroll, { passive: true });
    }
  });
});

// KeepAlive 生命周期:缓存/恢复滚动
onDeactivated(() => {
  // 不从 DOM 读,scroll 已在 handleScroll 中实时缓存
});

onActivated(() => {
  nextTick(() => {
    const el = getScrollEl();
    if (el) {
      el.scrollTop = textScrollTop.value;
    }
  });
});
</script>

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

.text-toolbar {
  padding: 8px 16px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: var(--color-card);
  border-bottom: 1px solid var(--color-border);
  flex-wrap: wrap;
  gap: 8px;
  flex-shrink: 0;
}

.ml-10 {
  margin-left: 10px;
}

.file-info {
  font-size: 14px;
  color: var(--color-text-secondary);
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 300px;
  text-align: center;
}

.toolbar-left,
.toolbar-right {
  display: flex;
  align-items: center;
  gap: 8px;
}

.text-container {
  flex: 1;
  overflow: hidden;
  padding: 0;
  position: relative;
  background: var(--color-bg);
}

.text-content {
  margin: 0;
  padding: 16px;
  background: var(--color-bg);
  font-family: "Consolas", "Monaco", "Courier New", monospace;
  line-height: 1.5;
  white-space: pre;
  overflow: auto;
  tab-size: 4;
  min-height: 100%;
  box-sizing: border-box;
  color: var(--color-text);

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

  &::-webkit-scrollbar-track {
    background: transparent;
  }

  &::-webkit-scrollbar-thumb {
    background: var(--color-border);
    border-radius: 3px;
  }

  &::-webkit-scrollbar-thumb:hover {
    background: var(--color-text-secondary);
  }
}

.wrap-text .text-content {
  white-space: pre-wrap;
  overflow-wrap: break-word;
  background: var(--color-bg);
}

.editor-textarea {
  width: 100%;
  height: 100%;
  border: none;
  outline: none;
  resize: none;
  background: var(--color-bg);
  color: var(--color-text);
  font-family: "Consolas", "Monaco", "Courier New", monospace;
  line-height: 1.5;
  padding: 16px;
  tab-size: 4;
  box-sizing: border-box;
  overflow: auto;

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

  &::-webkit-scrollbar-track {
    background: transparent;
  }

  &::-webkit-scrollbar-thumb {
    background: var(--color-border);
    border-radius: 3px;
  }

  &::-webkit-scrollbar-thumb:hover {
    background: var(--color-text-secondary);
  }
}

.loading-container,
.error-container {
  width: 100%;
  height: 100%;
  padding: 20px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  box-sizing: border-box;
  gap: 16px;
}

.error-container {
  color: var(--color-danger, #ff4d4f);
  text-align: center;

  i {
    font-size: 48px;
    margin-bottom: 16px;
  }

  p {
    margin: 0;
    font-size: 14px;
  }
}

/* 语法高亮相关样式(基础样式,将来可集成语法高亮库) */
// 为不同语法类型预留的样式钩子
// 可以在将来集成 highlight.js 或 prismjs 时使用
</style>