<template>
  <a-upload
    :custom-request="customRequest"
    list-type="picture-card"
    action="/"
    :limit="limit"
    :fileList="fileList"
    image-preview
    @change="onChange"
    @success="handleSuccess"
    @error="handleError"
  />
</template>

<script setup lang="ts">
import { ref } from 'vue';
import { Message } from '@arco-design/web-vue';
import { fetchImageUploadFile } 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 = (option) => {
  const { onProgress, onError, onSuccess, fileItem, name } = option;
  const xhr = new XMLHttpRequest();
  if (xhr.upload) {
    xhr.upload.onprogress = function (event) {
      let percent;
      if (event.total > 0) {
        // 0 ~ 1
        percent = event.loaded / event.total;
      }
      onProgress(percent, event);
    };
  }
  xhr.onerror = function error(e) {
    onError(e);
  };
  xhr.onload = function onload() {
    if (xhr.status < 200 || xhr.status >= 300) {
      return onError(xhr.responseText);
    }
    let response = JSON.parse(xhr.response);
    if (response && response.data.upload_url) {
      const blob = new Blob([fileItem.file], { type: fileItem.file.type });
      axios
        .put(response.data.upload_url, blob, {
          headers: { 'Content-Type': fileItem.file.type },
        })
        .then(() => {
          onSuccess(xhr.response);
        })
        .catch((error) => {
          onError(error);
        });
    } else {
      onError(xhr.response);
    }
  };

  const formData = new FormData();
  formData.append(name || 'file', fileItem.file);
  xhr.open('get', '/api/v1/oss/image-pre-signed-url?suffix=png', true);
  xhr.send(formData);
  let extension = getFileExtension(fileItem.file.name);
  return {
    abort() {
      xhr.abort();
    },
  };
};

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

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