<template>
  <n-upload
    :custom-request="handleCustomRequest"
    :max="1"
    :show-file-list="true"
    accept="*"
  >
    <div style="display: flex">
      <n-button dashed>
        <Icon name="LineMdUpload" />
        <span>选择文件上传</span>
      </n-button>
      <n-button
        style="margin-left: 10px"
        @click.stop="handlePreview"
        :disabled="!previewURL"
      >
        <span>预览文件</span>
      </n-button>
    </div>
  </n-upload>
</template>

<script setup lang="tsx">
  import axios from "@/axios";
  import { message } from "@/utils/index";
  import { Icon } from "@/components/icon/index";
  import { getPreSignedUrl, onlinePreview } from "./index";
  import { type UploadCustomRequestOptions, useModal } from "naive-ui";
  const previewURL = defineModel<string>("value", { required: true });
  const modal = useModal();
  const fileName = ref("");
  const show = ref(true);
  const modalRef = ref();

  const handleCustomRequest = async (options: UploadCustomRequestOptions) => {
    const { file, onFinish, onError } = options;
    try {
      fileName.value = file.name;
      const { preSignedUrl, objectUrl } = await getPreSignedUrl(fileName.value);
      const finalURL = __APP_ENV.VITE_APP_MINIO_URL + objectUrl;
      console.log(
        "_________________________ ~ handleCustomRequest ~ finalURL:",
        finalURL
      );
      await axios.put(preSignedUrl, file.file as File);
      onFinish();
      previewURL.value = finalURL;
      message.success("上传成功！");
    } catch (err) {
      console.error(err);
      onError?.();
      message.error("上传失败！");
    }
  };

  const handlePreview = () => {
    if (!previewURL.value) {
      message.warning("没有可预览的文件");
      return;
    }

    modalRef.value = modal.create({
      title: `${fileName.value} 预览`,
      preset: "card",
      style: {
        width: "800px",
      },
      content: () => (
        <n-spin show={show.value}>
          <iframe
            src={onlinePreview(previewURL.value)}
            style={{ width: "100%", height: "50vh" }}
            onLoad={() => (show.value = false)}
          />
        </n-spin>
      ),
      footer: () => (
        <n-space class="flex-end">
          <n-button
            type="info"
            onClick={() =>
              window.open(onlinePreview(previewURL.value), "_blank")
            }
          >
            新窗口预览
          </n-button>
          <n-button onClick={() => modalRef.value?.destroy()}>关闭</n-button>
        </n-space>
      ),
      onAfterLeave: () => {
        modalRef.value?.destroy();
      },
    });
  };
</script>
