<template>
  <div class="file-panel local">
    <div class="panel-header">
      <div class="path-nav">
        <Button @click="navigateLocal('..')" :disabled="!canNavigateUpLocal">
          {{ $t("fileView.parentDir") }}
        </Button>
        <Select class="sort-select" :value="sortType" @change="refreshLocal">
          <SelectOption value="name">{{
            $t("fileView.sortByName")
          }}</SelectOption>
          <SelectOption value="size">{{
            $t("fileView.sortBySize")
          }}</SelectOption>
          <SelectOption value="type">{{
            $t("fileView.sortByType")
          }}</SelectOption>
          <SelectOption value="date">{{
            $t("fileView.sortByDate")
          }}</SelectOption>
        </Select>
        <Button danger v-if="!isRemote" @click="showPermissionSetting">{{
          $t("fileView.permissionSettings")
        }}</Button>
      </div>
      <div>
        <Breadcrumb>
          <BreadcrumbItem v-for="(path, index) in pathSegments" :key="index">
            <a @click="navigateToPath(index)">{{ path }}</a>
          </BreadcrumbItem>
        </Breadcrumb>
      </div>
    </div>
    <div class="file-list" @contextmenu.prevent="showContextMenu($event, null)">
      <div
        style="text-align: center"
        v-if="isRemote && !currentDirInfo?.isInit"
      >
        <Button @click="refreshLocal">{{ $t("fileView.initialize") }}</Button>
      </div>
      <div v-else-if="!currentDirInfo?.isInit">
        <div @click="selectLocalDirectory" class="file-item">
          <div class="file-icon">📁</div>
          <div class="file-info">
            <div class="file-name">{{ $t("fileView.selectDirHint") }}</div>
          </div>
        </div>
      </div>
      <FileItem
        v-for="file in localFiles"
        :key="file.name"
        :file="file"
        @dblclick="handleLocalFileClick(file)"
        :class="{ selected: selectedLocalFiles.includes(file.path) }"
        @click="toggleLocalFileSelect(file)"
        @contextmenu.stop.prevent="showContextMenu($event, file)"
      />
    </div>
    <div v-if="currentDirInfo?.isInit" class="panel-footer">
      <Button v-if="!isRemote" @click="selectLocalDirectory">{{
        $t("fileView.selectDirectory")
      }}</Button>
      <Button @click="refreshLocal">{{ $t("fileView.refresh") }}</Button>
      <Button @click="createNewFolder">{{ $t("fileView.newFolder") }}</Button>
      <Button @click="createNewFile">{{ $t("fileView.newFile") }}</Button>
      <Button @click="deleteSelected" :disabled="!hasSelectedFiles">
        {{ $t("fileView.delete") }}
      </Button>
    </div>

    <!-- 右键菜单 -->
    <div v-if="showMenu" class="context-menu" :style="menuPosition">
      <div v-if="activeFile">
        <div class="menu-item" @click="handleRename">
          {{ $t("fileView.rename") }}
        </div>
        <div class="menu-item" @click="handleDelete">
          {{ $t("fileView.delete") }}
        </div>
        <div
          class="menu-item"
          v-if="props.isRemote && remoteCurrentFile?.isInit"
          @click="handleDownload"
        >
          {{ $t("fileView.download") }}
        </div>
      </div>
      <div v-else-if="!currentDirInfo?.isInit">
        <div class="menu-item" @click="selectLocalDirectory">
          {{ $t("fileView.selectLocalDir") }}
        </div>
      </div>
      <div v-else>
        <div class="menu-item" @click="refreshLocal">
          {{ $t("fileView.refresh") }}
        </div>
        <div class="menu-item" @click="createNewFolder">
          {{ $t("fileView.newFolder") }}
        </div>
        <div class="menu-item" @click="createNewFile">
          {{ $t("fileView.newFile") }}
        </div>
        <div class="menu-item" @click="deleteSelected" v-if="hasSelectedFiles">
          {{ $t("fileView.delete") }}
        </div>
      </div>
    </div>

    <!-- 文件预览 -->
    <FileReader
      v-if="previewFile"
      :file="previewFile"
      @close="previewFile = null"
    />

    <!-- 权限设置对话框 -->
    <FilePermissionSetDialog ref="permissionDialogRef" />
  </div>
</template>

<script setup lang="ts">
import {
  ref,
  onMounted,
  computed,
  onUnmounted,
  type Ref,
  h,
  reactive,
} from "vue";
import { useI18n } from "vue-i18n";
import { Button, Select, SelectOption, Modal } from "ant-design-vue";
import { FileInfo, fileMgrInstance } from "../utils/fileMgr";
import FileItem from "./fileItem.vue";
import FileReader from "./fileReader.vue";
import { Breadcrumb, BreadcrumbItem } from "ant-design-vue";
import emitter, { EmitterEvent } from "../utils/emitter";
import { localCurrentFile, remoteCurrentFile } from "../utils/common";
import FilePermissionSetDialog from "./filePermissionSetDialog.vue";

const { t } = useI18n();
const props = defineProps<{
  isRemote: boolean;
  selectedFiles: string[];
}>();

// 状态管理
const currentLocalPath = ref("/");
const localFiles: Ref<FileInfo[]> = ref([]);
const selectedLocalFiles = ref(props.selectedFiles);
const newFileName = ref("");
const folderName = ref("");
const fileName = ref("");
const currentDirInfo = props.isRemote ? remoteCurrentFile : localCurrentFile;
const sortType = ref<"name" | "size" | "type" | "date">("type");
currentDirInfo.value = props.isRemote ? fileMgrInstance.remoteRootFile : null;
// 右键菜单状态
const showMenu = ref(false);
const menuPosition = ref({ top: "0px", left: "0px" });
const activeFile: Ref<FileInfo> = ref(null);
// 文件预览状态
const previewFile: Ref<FileInfo> = ref(null);

// 计算属性
const canNavigateUpLocal = ref(false);
const hasSelectedFiles = computed(() => selectedLocalFiles.value.length > 0);

// 计算当前路径的分段
const pathSegments = computed(() => {
  return currentLocalPath.value.split("/").filter((p) => p);
});

// 导航到指定层级的路径
const navigateToPath = (index: number) => {
  const targetPath = pathSegments.value.slice(0, index + 1).join("/");
  navigateLocal(targetPath);
};

//选择目录
!props.isRemote &&
  emitter.on(EmitterEvent.choosed_local_directory, async (file: FileInfo) => {
    currentDirInfo.value = await fileMgrInstance.getRootFile();
    await refreshLocal();
  });

//选择目录
const selectLocalDirectory = async () => {
  try {
    await fileMgrInstance.selectLocalDirectory();
  } catch (err) {
    console.error("选择目录失败:", err);
  }
};
const handleDownload = async () => {
  if (!activeFile.value) return;
  const file = activeFile.value;
  await fileMgrInstance.getRootFile();
  await file.getFile(
    false,
    localCurrentFile.value.path.replace(
      (await fileMgrInstance.getRootFile()).path,
      "",
    ),
    remoteCurrentFile.value.path,
  );
};

//刷新目录
emitter.on(EmitterEvent.update_directory, async (file: FileInfo) => {
  if (file.isRemote != props.isRemote) return;
  if (currentDirInfo.value.path == file.path) {
    const files = currentDirInfo.value.files;
    for (const file of files) {
      if (!file.isDirectory) {
        file.size = await file.getFileSize();
      }
    }
    currentLocalPath.value = currentDirInfo.value.path;
    localFiles.value = files;
    canNavigateUpLocal.value = currentDirInfo.value.parentFileInfo != null;
  }
});
const refreshLocal = async () => {
  try {
    if (!currentDirInfo.value) {
      throw new Error("当前目录为空");
    }
    await currentDirInfo.value.loadLocalDirectory(sortType.value);
  } catch (err) {
    console.error("刷新目录失败:", err);
  }
};

const navigateLocal = async (path: string) => {
  try {
    if (path === "..") {
      if (currentDirInfo.value?.parentFileInfo) {
        currentDirInfo.value = currentDirInfo.value.parentFileInfo;
        currentLocalPath.value = currentDirInfo.value.path;
      }
    } else {
      let root = currentDirInfo.value?.isRemote
        ? fileMgrInstance.remoteRootFile
        : await fileMgrInstance.getRootFile();
      const targetDir = root.getFileInfo(path);
      if (targetDir) {
        currentDirInfo.value = targetDir;
        currentLocalPath.value = targetDir.path;
      }
    }
    selectedLocalFiles.value.length = 0;
    await refreshLocal();
  } catch (err) {
    console.error("导航失败:", err);
  }
};

const handleLocalFileClick = async (file: FileInfo) => {
  if (file.isDirectory) {
    await navigateLocal(file.path);
  } else {
    previewFile.value = file;
  }
};

const toggleLocalFileSelect = (file: FileInfo) => {
  const index = selectedLocalFiles.value.indexOf(file.path);
  if (index === -1) {
    selectedLocalFiles.value.push(file.path);
  } else {
    selectedLocalFiles.value.splice(index, 1);
  }
};

// 右键菜单相关
const showContextMenu = (event: MouseEvent, file: FileInfo) => {
  event.preventDefault();
  showMenu.value = true;
  menuPosition.value = {
    top: `${event.clientY}px`,
    left: `${event.clientX}px`,
  };
  activeFile.value = file;
  console.log(props.isRemote && localCurrentFile.value?.isInit);
};

// 关闭右键菜单
const closeContextMenu = () => {
  showMenu.value = false;
  activeFile.value = null;
};

// 重命名文件
const handleRename = async () => {
  if (!activeFile.value) return;

  newFileName.value = activeFile.value.name;
  const acf = activeFile.value;
  Modal.confirm({
    title: t("fileView.renameTitle"),
    class: "custom-modal",
    content: h("div", [
      h("input", {
        class: "ant-input",
        placeholder: t("fileView.inputNewName"),
        value: newFileName.value,
        onInput: (e: Event) => {
          newFileName.value = (e.target as HTMLInputElement).value;
        },
        style: {
          width: "100%",
          marginTop: "8px",
        },
      }),
    ]),
    okText: t("common.okText"),
    cancelText: t("common.cancelText"),
    async onOk() {
      if (!newFileName.value || newFileName.value === acf.name) {
        return Promise.reject();
      }
      try {
        await acf.renameFile(newFileName.value);
        await refreshLocal();
      } catch (err) {
        console.error("重命名失败:", err);
        Modal.error({
          title: t("fileView.renameTitle") + t("common.failed"),
          content: (err as Error).message || (err as string),
        });
      }
    },
  });
  closeContextMenu();
};

// 删除文件
const handleDelete = async () => {
  if (activeFile.value) {
    if (!selectedLocalFiles.value.includes(activeFile.value.name)) {
      selectedLocalFiles.value.push(activeFile.value.name);
    }
  }
  deleteSelected();
  closeContextMenu();
};

// 删除选中的文件
const deleteSelected = async () => {
  if (!selectedLocalFiles.value.length) return;

  Modal.confirm({
    title: t("fileView.confirmDelete"),
    content: t("fileView.deleteConfirmContent", {
      files: selectedLocalFiles.value.join("<br>"),
      count: selectedLocalFiles.value.length,
    }),
    okText: t("fileView.deleteBtn"),
    okType: "danger",
    cancelText: t("fileView.cancelBtn"),
    async onOk() {
      try {
        for (const fileName of selectedLocalFiles.value) {
          const file = localFiles.value.find((f) => f.path === fileName);
          if (file) {
            await file.deleteItself();
          }
        }
        selectedLocalFiles.value = [];
        await refreshLocal();
      } catch (err) {
        console.error("批量删除失败:", err);
        Modal.error({
          title: t("common.delete") + t("common.failed"),
          content: (err as Error).message,
        });
      }
    },
  });
};

// 创建新文件夹
const createNewFolder = async () => {
  if (!currentDirInfo) return;

  folderName.value = "";
  Modal.confirm({
    title: t("fileView.createFolderTitle"),
    class: "custom-modal",
    content: h("div", [
      h("input", {
        class: "ant-input",
        placeholder: t("fileView.inputFolderName"),
        value: folderName.value,
        onInput: (e: Event) => {
          folderName.value = (e.target as HTMLInputElement).value;
        },
        style: {
          width: "100%",
          marginTop: "8px",
        },
      }),
    ]),
    okText: t("fileView.createBtn"),
    cancelText: t("fileView.cancelBtn"),
    async onOk() {
      if (!folderName.value) {
        Modal.warning({
          title: t("common.warning"),
          content: t("fileView.warningInputFolderName"),
        });
        return Promise.reject();
      }
      try {
        await currentDirInfo.value.createDirectory(folderName.value);
        await refreshLocal();
      } catch (err) {
        console.error("创建文件夹失败:", err);
        Modal.error({
          title: t("fileView.createFolderTitle") + t("common.failed"),
          content: (err as Error).message,
        });
      }
    },
  });
};

// 创建新文件
const createNewFile = async () => {
  if (!currentDirInfo) return;

  fileName.value = "";
  Modal.confirm({
    title: t("fileView.createFileTitle"),
    class: "custom-modal",
    content: h("div", [
      h("input", {
        class: "ant-input",
        placeholder: t("fileView.inputFileName"),
        value: fileName.value,
        onInput: (e: Event) => {
          fileName.value = (e.target as HTMLInputElement).value;
        },
        style: {
          width: "100%",
          marginTop: "8px",
        },
      }),
    ]),
    okText: t("fileView.createBtn"),
    cancelText: t("fileView.cancelBtn"),
    async onOk() {
      if (!fileName.value) {
        Modal.warning({
          title: t("common.warning"),
          content: t("fileView.warningInputFileName"),
        });
        return Promise.reject();
      }
      try {
        const emptyBuffer = new ArrayBuffer(0);
        await currentDirInfo.value.createFile(fileName.value, emptyBuffer);
        await refreshLocal();
      } catch (err) {
        console.error("创建文件失败:", err);
        Modal.error({
          title: t("fileView.createFileTitle") + t("common.failed"),
          content: (err as Error).message,
        });
      }
    },
  });
};

// 点击其他地方关闭右键菜单
onMounted(() => {
  document.addEventListener("click", closeContextMenu);
});

onUnmounted(() => {
  document.removeEventListener("click", closeContextMenu);
});

const permissionDialogRef = ref();

const showPermissionSetting = () => {
  permissionDialogRef.value?.showDialog();
};
</script>

<style scoped>
.file-panel {
  height: 100%;
  display: flex;
  flex-direction: column;
  border: 1px solid #ddd;
}

.panel-header {
  padding: 10px;
  border-bottom: 1px solid #ddd;
}

.path-nav {
  display: flex;
  align-items: center;
  gap: 10px;
}

.file-list {
  flex: 1;
  overflow-y: auto;
  padding: 10px;
}

.file-item {
  display: flex;
  align-items: center;
  padding: 8px;
  cursor: pointer;
  border-radius: 4px;
  margin-bottom: 4px;
}

.file-item:hover {
  background-color: #f5f5f5;
}

.file-item.selected {
  background-color: #e3f2fd;
}

.file-icon {
  margin-right: 10px;
  font-size: 1.2em;
}

.file-info {
  flex: 1;
}

.file-name {
  font-weight: 500;
}

.file-meta {
  font-size: 0.8em;
  color: #666;
}

.panel-footer {
  padding: 10px;
  border-top: 1px solid #ddd;
  display: flex;
  gap: 10px;
}

.context-menu {
  position: fixed;
  background: white;
  border: 1px solid #ddd;
  border-radius: 4px;
  padding: 4px 0;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  z-index: 1000;
}

.menu-item {
  padding: 8px 16px;
  cursor: pointer;
}

.menu-item:hover {
  background-color: #f5f5f5;
}
.sort-select {
  width: 100px;
}
</style>
