<template>
  <div class="file-reader" v-if="file">
    <div class="reader-header">
      <h3>{{ file.name }}</h3>
      <div class="header-actions">
        <button
          v-if="file.isRemote"
          :disabled="!loadedFile.name"
          @click="downloadFile"
        >
          {{
            fileTypeCheck == "unsupported-size"
              ? $t("fileReader.remoteTransfer")
              : $t("fileReader.browserDownload")
          }}
        </button>
        <button v-if="canEdit" @click="toggleEdit">
          {{ isEditing ? $t("fileReader.save") : $t("fileReader.edit") }}
        </button>
        <button @click="$emit('close')">{{ $t("fileReader.close") }}</button>
      </div>
    </div>

    <div class="reader-content">
      <!-- 文本预览 -->
      <div v-if="fileTypeCheck === 'text' || openWithText" class="text-viewer">
        <div v-if="isEditing" class="editor">
          <textarea
            v-model="editingContent"
            :style="{ height: editorHeight + 'px' }"
            @input="adjustEditorHeight"
          ></textarea>
        </div>
        <pre v-else>{{ fileContent }}</pre>
      </div>

      <!-- 图片预览 -->
      <div
        v-else-if="fileTypeCheck === 'image'"
        class="image-viewer"
        @wheel.prevent="handleWheel"
        @touchstart="handleTouchStart"
        @touchmove.prevent="handleTouchMove"
        @touchend="handleTouchEnd"
        @dblclick="resetZoom"
      >
        <img
          :src="fileUrl"
          :alt="file.name"
          :style="{
            transform: `scale(${scale}) translate(${translateX}px, ${translateY}px)`,
            transition: isTransitioning ? 'transform 0.3s' : 'none',
            cursor: scale > 1 ? 'grab' : 'default',
          }"
          @mousedown="startDrag"
          @mousemove="onDrag"
          @mouseup="stopDrag"
          @mouseleave="stopDrag"
        />
      </div>

      <!-- 视频预览 -->
      <div v-else-if="fileTypeCheck === 'video'" class="video-viewer">
        <video controls>
          <source :src="fileUrl" :type="mimeType" />
          {{ $t("fileReader.videoNotSupported") }}
        </video>
      </div>

      <!-- 音频预览 -->
      <div v-else-if="fileTypeCheck === 'audio'" class="audio-viewer">
        <audio controls>
          <source :src="fileUrl" :type="mimeType" />
          {{ $t("fileReader.audioNotSupported") }}
        </audio>
      </div>

      <!-- 代码预览 -->
      <div v-else-if="fileTypeCheck === 'code'" class="code-viewer">
        <div class="code-header">
          <select v-model="selectedLanguage">
            <option value="auto">{{ $t("fileReader.autoDetect") }}</option>
            <option value="javascript">JavaScript</option>
            <option value="typescript">TypeScript</option>
            <option value="html">HTML</option>
            <option value="css">CSS</option>
            <option value="python">Python</option>
            <option value="java">Java</option>
            <option value="cpp">C++</option>
            <option value="go">Go</option>
            <option value="rust">Rust</option>
            <option value="lua">Lua</option>
            <option value="sql">SQL</option>
            <option value="shell">Shell</option>
            <option value="json">JSON</option>
            <option value="other">{{ $t("fileReader.other") }}</option>
          </select>
        </div>
        <div v-if="isEditing" class="editor">
          <textarea
            v-model="editingContent"
            :style="{ height: editorHeight + 'px', minHeight: '100%' }"
            @input="adjustEditorHeight"
          ></textarea>
        </div>
        <pre v-else><code v-html="highlightedCode"></code></pre>
      </div>

      <!-- 不支持的文件类型 -->
      <div v-else class="unsupported">
        <div>
          {{
            fileTypeCheck === "unsupported-size"
              ? $t("fileReader.fileTooLarge")
              : $t("fileReader.unsupportedType")
          }}
        </div>
        <div>
          <Button
            v-if="fileTypeCheck != 'unsupported-size'"
            @click="openWithText = true"
            >{{ $t("fileReader.openAsText") }}</Button
          >
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, computed } from "vue";
import { useI18n } from "vue-i18n";
import {
  fileMgrInstance,
  type FileData,
  type FileInfo,
} from "../utils/fileMgr";
import hljs from "highlight.js";
import "highlight.js/styles/github.css";
import { Modal } from "ant-design-vue";
import { localCurrentFile, remoteCurrentFile } from "../utils/common";
import { NEED_CHUNK_FILE_SIZE_PREVIEW } from "../utils/fileTransfer";

const { t } = useI18n();

const props = defineProps<{
  file: FileInfo;
}>();

const emit = defineEmits<{
  (e: "close"): void;
}>();

const fileUrl = ref("");
const fileContent = ref("");
const mimeType = ref("");
const selectedLanguage = ref("auto");
const isEditing = ref(false);
const editingContent = ref("");
const editorHeight = ref(300);
const openWithText = ref(false);
const scale = ref(1);
const translateX = ref(0);
const translateY = ref(0);
const isTransitioning = ref(false);
const isDragging = ref(false);
const lastMouseX = ref(0);
const lastMouseY = ref(0);
const lastTouchDistance = ref(0);

// 下载文件
const downloadFile = async () => {
  if (fileTypeCheck.value == "unsupported-size") {
    await props.file.getFile(
      false,
      localCurrentFile.value.path.replace(
        (await fileMgrInstance.getRootFile()).path,
        "",
      ),
      remoteCurrentFile.value.path,
    );
    localCurrentFile.value.loadLocalDirectory();
    return;
  }
  Modal.confirm({
    title: t("fileReader.downloadTitle"),
    content: t("fileReader.downloadConfirm", { name: props.file.name }),
    onOk: () => {
      const blob = new Blob([loadedFile.value.buffer], {
        type: loadedFile.value.type || "application/octet-stream",
      });
      const url = URL.createObjectURL(blob);
      const a = document.createElement("a");
      a.href = url;
      a.download = props.file.name;
      a.click();
      URL.revokeObjectURL(url);
    },
  });
};

// 是否可以编辑
const canEdit = computed(() => {
  return fileTypeCheck.value === "text" || fileTypeCheck.value === "code";
});

// 文件类型判断
const fileTypeCheck = computed(() => {
  //如果文件大于30M，则不预览
  if (props.file.size > NEED_CHUNK_FILE_SIZE_PREVIEW) {
    return "unsupported-size";
  }
  const ext = props.file.name.split(".").pop()?.toLowerCase() || "";

  // 图片类型
  if (["jpg", "jpeg", "png", "gif", "webp", "svg"].includes(ext)) {
    return "image";
  }

  // 视频类型
  if (["mp4", "webm", "ogg"].includes(ext)) {
    return "video";
  }
  // 音频类型
  if (["mp3", "wav", "ogg"].includes(ext)) {
    return "audio";
  }

  // 代码类型
  if (
    [
      "js",
      "ts",
      "json",
      "html",
      "css",
      "vue",
      "jsx",
      "tsx",
      "py",
      "java",
      "cpp",
      "c",
      "go",
      "rs",
      "lua",
      "sql",
      "shell",
      "cfg",
      "ini",
      "conf",
      "xml",
      "yaml",
      "toml",
      "applescript",
      "sh",
      "bat",
      "ps1",
      "asp",
      "aspx",
      "php",
      "jsp",
      "cc",
      "c++",
      "cs",
      "dart",
      "sh",
      "bash",
      "kt",
      "swift",
      "rb",
      "R",
      "rust",
    ].includes(ext)
  ) {
    return "code";
  }

  // 文本类型
  if (["txt", "md", "log"].includes(ext)) {
    return "text";
  }

  return "unsupported-type";
});

// 代码高亮处理
const highlightedCode = computed(() => {
  if (!fileContent.value) return "";
  try {
    if (selectedLanguage.value && selectedLanguage.value !== "auto") {
      // 使用指定的语言
      const result = hljs.highlight(fileContent.value, {
        language: selectedLanguage.value,
      });
      return result.value;
    } else {
      // 自动检测语言
      const result = hljs.highlightAuto(fileContent.value);
      selectedLanguage.value = result.language || "auto";
      return result.value;
    }
  } catch (err) {
    console.error("代码高亮失败:", err);
    return fileContent.value;
  }
});

// 切换编辑模式
const toggleEdit = async () => {
  if (isEditing.value) {
    // 保存文件
    try {
      const encoder = new TextEncoder();
      const buffer = encoder.encode(editingContent.value);
      await props.file.saveFile(buffer);
      fileContent.value = editingContent.value;
      isEditing.value = false;
    } catch (err) {
      console.error("保存文件失败:", err);
      alert(t("fileReader.saveFailed") + ": " + (err as Error).message);
    }
  } else {
    // 进入编辑模式
    editingContent.value = fileContent.value;
    isEditing.value = true;
    adjustEditorHeight();
  }
};

// 自动调整编辑器高度
const adjustEditorHeight = () => {
  const textarea = document.querySelector(
    ".editor textarea",
  ) as HTMLTextAreaElement;
  if (textarea) {
    textarea.style.height = "auto";
    textarea.style.height = textarea.scrollHeight + "px";
    editorHeight.value = textarea.scrollHeight;
  }
};
const loadedFile = ref<{
  type: string;
  buffer: ArrayBuffer;
  name: string;
  size: number;
  lastModified: number;
}>({
  type: "",
  buffer: undefined,
  name: "",
  size: 0,
  lastModified: 0,
});
// 加载文件内容
const loadFile = async () => {
  try {
    if (fileTypeCheck.value === "unsupported-size") {
      return;
    }
    const file: FileData = (await props.file.getFile(true)) as FileData;
    loadedFile.value = file;
    if (file.buffer == null) {
      file.buffer = props.file.previewCache;
    }
    if (fileTypeCheck.value === "image" || fileTypeCheck.value === "video") {
      fileUrl.value = URL.createObjectURL(new Blob([file.buffer]));
      mimeType.value = file.type;
    } else if (
      fileTypeCheck.value === "code" ||
      fileTypeCheck.value === "text"
    ) {
      fileContent.value = new TextDecoder().decode(file.buffer);
    } else {
      fileContent.value = new TextDecoder().decode(file.buffer);
    }
  } catch (err) {
    console.error("加载文件失败:", err);
  }
};

// 处理鼠标滚轮缩放
const handleWheel = (e: WheelEvent) => {
  const delta = e.deltaY > 0 ? -0.1 : 0.1;
  const newScale = Math.max(0.1, Math.min(5, scale.value + delta));
  scale.value = newScale;
};

// 处理触摸开始
const handleTouchStart = (e: TouchEvent) => {
  if (e.touches.length === 2) {
    const touch1 = e.touches[0];
    const touch2 = e.touches[1];
    lastTouchDistance.value = Math.hypot(
      touch2.clientX - touch1.clientX,
      touch2.clientY - touch1.clientY,
    );
  } else if (e.touches.length === 1) {
    isDragging.value = true;
    lastMouseX.value = e.touches[0].clientX;
    lastMouseY.value = e.touches[0].clientY;
  }
};

// 处理触摸移动
const handleTouchMove = (e: TouchEvent) => {
  if (e.touches.length === 2) {
    const touch1 = e.touches[0];
    const touch2 = e.touches[1];
    const distance = Math.hypot(
      touch2.clientX - touch1.clientX,
      touch2.clientY - touch1.clientY,
    );

    const delta = distance - lastTouchDistance.value;
    const scaleDelta = delta * 0.01;
    scale.value = Math.max(0.1, Math.min(5, scale.value + scaleDelta));
    lastTouchDistance.value = distance;
  } else if (e.touches.length === 1 && isDragging.value) {
    const deltaX = e.touches[0].clientX - lastMouseX.value;
    const deltaY = e.touches[0].clientY - lastMouseY.value;
    translateX.value += deltaX;
    translateY.value += deltaY;
    lastMouseX.value = e.touches[0].clientX;
    lastMouseY.value = e.touches[0].clientY;
  }
};

// 处理触摸结束
const handleTouchEnd = () => {
  isDragging.value = false;
  lastTouchDistance.value = 0;
};

// 开始拖动
const startDrag = (e: MouseEvent) => {
  if (scale.value > 1) {
    isDragging.value = true;
    lastMouseX.value = e.clientX;
    lastMouseY.value = e.clientY;
  }
};

// 拖动中
const onDrag = (e: MouseEvent) => {
  if (isDragging.value) {
    const deltaX = e.clientX - lastMouseX.value;
    const deltaY = e.clientY - lastMouseY.value;
    translateX.value += deltaX;
    translateY.value += deltaY;
    lastMouseX.value = e.clientX;
    lastMouseY.value = e.clientY;
  }
};

// 停止拖动
const stopDrag = () => {
  isDragging.value = false;
};

// 双击重置缩放
const resetZoom = () => {
  isTransitioning.value = true;
  scale.value = 1;
  translateX.value = 0;
  translateY.value = 0;
  setTimeout(() => {
    isTransitioning.value = false;
  }, 300);
};

onMounted(() => {
  openWithText.value = false;
  loadFile();
});

// 组件卸载时清理资源
onUnmounted(() => {
  if (fileUrl.value) {
    URL.revokeObjectURL(fileUrl.value);
    props.file.clearPreviewCache();
  }
});
</script>

<style scoped>
.file-reader {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(255, 255, 255, 0.98);
  z-index: 1000;
  display: flex;
  flex-direction: column;
  padding: 20px;
}

.reader-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-bottom: 20px;
  border-bottom: 1px solid #eee;
}

.reader-content {
  flex: 1;
  overflow: auto;
  padding: 20px 0;
}

.image-viewer {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  overflow: hidden;
  user-select: none;
  touch-action: none;
}

.image-viewer img {
  max-width: 100%;
  max-height: 100%;
  object-fit: contain;
  will-change: transform;
  transform-origin: center center;
}

.video-viewer {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
}

.video-viewer video {
  max-width: 100%;
  max-height: 100%;
}

.code-viewer,
.text-viewer {
  height: 100%;
  overflow: auto;
}

.code-viewer pre,
.text-viewer pre {
  margin: 0;
  padding: 20px;
  background: #f5f5f5;
  border-radius: 4px;
  white-space: pre-wrap;
  word-wrap: break-word;
}

.unsupported {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  height: 100%;
  color: #666;
}

button {
  padding: 6px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  background: white;
  cursor: pointer;
}

button:hover {
  background: #f5f5f5;
}

.code-header {
  padding: 10px;
  background: #f8f8f8;
  border-bottom: 1px solid #eee;
}

.code-header select {
  padding: 4px 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
  background: white;
}

.code-viewer pre {
  margin: 0;
  padding: 20px;
  background: #f8f8f8;
  border-radius: 4px;
  overflow-x: auto;
}

.code-viewer code {
  font-family: "Fira Code", "Consolas", monospace;
  font-size: 14px;
  line-height: 1.5;
}

/* 取消 scoped 样式对 highlight.js 的影响 */
:deep(.hljs) {
  background: transparent;
  padding: 0;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.editor {
  height: 100%;
  padding: 20px;
  background: #f8f8f8;
  border-radius: 4px;
}

.editor textarea {
  width: 100%;
  min-height: 300px;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-family: "Fira Code", "Consolas", monospace;
  font-size: 14px;
  line-height: 1.5;
  resize: none;
  background: white;
}

.editor textarea:focus {
  outline: none;
  border-color: #4a9eff;
}
</style>
