<template>
  <a-upload :show-file-list="true" :custom-request="handelUpload == null ? customRequest : handelUpload"
    :list-type="listType" :file-list="fileList" :limit="minx" @before-remove="beforeRemove" :show-remove-button="showRemoveButton" :show-cancel-button="false"
    :image-preview="imagePreview" :accept="accept" @before-upload="beforeUpload" />
</template>

<script setup>
import { toRef, ref, watch, watchEffect, onMounted } from 'vue';
import { useSystemStore } from '@/store/modules/systemStore';
import { Modal } from "@arco-design/web-vue";
import { useI18n } from 'vue-i18n';
import { Message } from "@arco-design/web-vue";

const systemStore = useSystemStore();
const { t } = useI18n();

// 自定义请求：上传文件的处理逻辑
const customRequest = async (option) => {
  const { file } = option.fileItem;
  const fileName = `thumbnail_${file.name}`;
  const key = `test/${fileName}`;

  // 获取上传客户端（假设 systemStore 已经定义了上传接口）
  const client = await systemStore.getSTSClient();
  const resClient = await client.putObject({
    key: key,
    body: file
  });


  // 上传成功后，更新 fileList 和 modelValue
  if (resClient.statusCode === 200) {
    const uploadedFileUrl = resClient.url;
    fileList.value.push({ url: uploadedFileUrl, name: fileName, status: resClient.statusCode, uid: '0' });
    // 更新父组件的 modelValue
    if (minx.value === 1) {
      emit('update:modelValue', uploadedFileUrl);
    } else {
      emit('update:modelValue', fileList.value.map(res => res.url).join(','));
    }
  }
};
// 接收外部传入的 props：modelValue 和 minx
const props = defineProps({
  modelValue: {
    type: [String, Array],
    default: "",
  },
  minx: {
    type: Number,
    default: 1
  },
  listType: {
    type: String,
    default: 'picture-card'
  },// 上传样式
  imagePreview: {
    type: Boolean,
    default: true
  }, // 是否支持预览
  accept: {
    type: String,
    default: ''
  }, // 上传文件类型
  handelUpload: {
    type: Function,
    default: null  // 外部传入的自定义上传方法
  },
  showRemoveButton:{
    type: Boolean,
    default: true  // 是否显示删除按钮
  },
  beforeUpload: {
    type: Boolean,
    default: false,
  },
});

// 使用 toRef 确保对 props 的访问是响应式的
const minx = toRef(props, 'minx');
const modelValue = toRef(props, 'modelValue');
const listType = toRef(props, 'listType');
const imagePreview = toRef(props, 'imagePreview');
const handelUpload = toRef(props, 'handelUpload');
// 定义 emit，用于向外抛出事件
const emit = defineEmits(["update:modelValue"]);

// 用于存储文件列表，初始化时显示传递给子组件的值
const fileList = ref([]);


// 删除文件处理逻辑
const beforeRemove = (file) => {
  return new Promise((resolve, reject) => {
    Modal.confirm({
      title: $t("customer.confirmRemoveUpload"),
      onOk: () => {
        // 更新 fileList 和 modelValue，移除删除的文件
        fileList.value = fileList.value.filter((item) => item.url !== file.url);
        if (minx.value === 1) {
          emit(
            "update:modelValue",
            fileList.value.length > 0 ? fileList.value[0].url : ""
          );
        } else {
          emit(
            "update:modelValue",
            fileList.value.map((res) => res.url).join(",")
          );
        }
        resolve(true); // 确认删除
      },
      onCancel: () => reject("cancel"), // 取消删除
    });
  });
};

watchEffect(() => {
  if (modelValue.value) {
    if (Array.isArray(modelValue.value)) {
      // 如果传递的是数组，则直接使用
      fileList.value = modelValue.value.map(item => ({ url: item, status: item.status, name: item.name }));
    } else if (typeof modelValue.value === 'string') {
      // 如果传递的是字符串，则将字符串按逗号分割成数组
      const urlList = modelValue.value.split(',').map(url => ({ url: url.trim() }));
      fileList.value = urlList;
    }
  } else {
    fileList.value = [];
  }
})

onMounted(() => {

})

// 上传前校验
const beforeUpload = (rawFile) => {
  if(!props.beforeUpload) return true
  const isAllowType =
    rawFile.type === "image/png" ||
    rawFile.type === "image/jpg" ||
    rawFile.type === "image/jpeg";
  if (!isAllowType) {
    Message.error("图片仅支持jpg或png");
    return false;
  } else if (rawFile.size / 1024 / 1024 > 2) {
    Message.error("图片不能大于2M");
    return false;
  }
  return true;
};

</script>

<style scoped>
/* 可自定义样式 */
</style>
