<template>
  <a-upload
    :custom-request="customRequest"
    action="/"
    :limit="limit"
    :fileList="fileList"
    @change="onChange"
    @success="handleSuccess"
    @error="handleError"
  />
</template>

<script setup lang="ts">
import { ref } from 'vue';
import { Message } from '@arco-design/web-vue';
import { fetchImageUploadFile, fetchUploadFile } from '@/api/all';
import axios from 'axios';

const fileList = ref([]);

const props = defineProps({
  modelValue: {
    type: [Array, String],
    default: '',
  },
  limit: {
    type: Number,
    default: 0, // 0 表示不限制
  },
});

const emit = defineEmits(['update:modelValue']);

const handleSuccess = (fileItem) => {
  let response = fileItem.response;
  response = JSON.parse(response);
  if (response && response.data.file_url) {
    if (props.limit === 1) {
      emit('update:modelValue', response.data.file_url);
    } else {
      emit('update:modelValue', [...props.modelValue, response.data.file_url]);
    }
  }
};

watch(
  () => props.modelValue,
  async (value) => {
    console.log(value, 'value');
    if (value) {
      fileList.value =
        props.limit == 1
          ? [
              {
                name: '',
                url: props.modelValue as string,
              },
            ]
          : (props.modelValue as string[]).map((item) => {
              return {
                name: '',
                url: item,
              };
            });
    } else {
      fileList.value = [];
    }
  },
  { once: true },
);

let previousFileListLength = 0;
//删除图片
const onChange = (fileList) => {
  if (fileList.length < previousFileListLength) {
    if (props.limit === 1) {
      if (fileList.length === 0) {
        emit('update:modelValue', '');
      }
    } else {
      if (fileList.length === 0) {
        emit('update:modelValue', []);
      } else {
        let image_data = fileList.map((item) => item.url);
        emit('update:modelValue', image_data);
      }
    }
  }

  previousFileListLength = fileList.length;
};

const beforeUpload = (file, files) => {
  if (props.limit > 0 && files.length >= props.limit) {
    Message.warning(`最多只能上传 ${props.limit} 张图片`);
    return false; // 阻止上传
  }
  return true;
};

const handleError = (error) => {
  Message.error('上传失败');
  console.error(error);
};

const customRequest = async (option) => {
  const { onProgress, onError, onSuccess, fileItem, name } = option;
  try {
    // 1. 获取预签名上传URL
    const response = await fetchUploadFile({ suffix: getFileExtension(fileItem.file.name) });
    const preSignedUrl = response?.data?.upload_url;

    if (!preSignedUrl) {
      throw new Error('未能获取有效的预签名上传地址');
    }
    console.log('preSignedUrl', preSignedUrl);
    // 2. 使用预签名URL上传文件
    const blob = new Blob([fileItem.file], { type: fileItem.file.type });
    await axios.put(preSignedUrl, blob, {
      headers: { 'Content-Type': fileItem.file.type },
    });

    onSuccess(JSON.stringify(response));
  } catch (error) {
    onError(error);
  }
};

function getFileExtension(filename: string): string {
  const match = filename.match(/\.([^.]+)$/);
  return match ? match[1].toLowerCase() : '';
}
</script>

<style scoped>
/* 添加一些样式 */
</style>
