<template>
  <el-upload
    :show-file-list="false"
    :accept="accept"
    :disabled="disabled || loading"
    :http-request="handleUpload"
  >
    <el-button :type="buttonType" :plain="plain" :loading="loading">
      {{ buttonText }}
    </el-button>
  </el-upload>
</template>

<script setup>
import { ref } from 'vue';
import { ElMessage } from 'element-plus';
import { uploadAsset } from '../api/uploads';

const props = defineProps({
  hospitalId: {
    type: Number,
    default: null,
  },
  buttonText: {
    type: String,
    default: '上传文件',
  },
  buttonType: {
    type: String,
    default: 'primary',
  },
  plain: {
    type: Boolean,
    default: false,
  },
  accept: {
    type: String,
    default: '',
  },
  disabled: {
    type: Boolean,
    default: false,
  },
});

const emit = defineEmits(['uploaded']);
const loading = ref(false);

const handleUpload = async (options) => {
  loading.value = true;
  try {
    const asset = await uploadAsset(options.file, props.hospitalId);
    emit('uploaded', asset);
    options.onSuccess?.(asset);
    ElMessage.success('上传成功');
  } catch (error) {
    options.onError?.(error);
  } finally {
    loading.value = false;
  }
};
</script>
