<template>
  <div style="display: flex">
    <n-image
      v-if="!!previewURL"
      height="50"
      :src="previewURL"
    />
    <n-upload
      @remove="onRemove"
      :custom-request="handleCustomRequest"
      :max="1"
      :show-file-list="true"
      accept="*"
    >
      <n-button
        dashed
        style="margin-right: 5px"
      >
        <Icon name="LineMdUpload" />
        <span>选择照片上传</span>
      </n-button>
    </n-upload>
  </div>
</template>

<script setup lang="tsx">
  import axios from "@/axios";
  import { message } from "@/utils/index";
  import { getPreSignedUrl } from "../customFileUpload/index";
  import {
    type UploadCustomRequestOptions,
    type UploadFileInfo,
  } from "naive-ui";

  const fileName = ref("");
  const previewURL = defineModel<string>("value", { required: true });
  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 onRemove = (options: {
    file: UploadFileInfo;
    fileList: Array<UploadFileInfo>;
    index: number;
  }): Promise<boolean> | boolean | any => {
    console.log("onRemove");
    previewURL.value = "";
  };
</script>
