<script setup lang="ts">
import type { VxeUploadPropTypes } from 'vxe-pc-ui'

defineOptions({ name: 'MjFormUpload' })

const props = defineProps<{
  fileTypes?: VxeUploadPropTypes.FileTypes
  modelValue: any
}>()

const emit = defineEmits(['update:modelValue'])
const fileObj = ref([] as any)

watch(
  () => props.modelValue,
  (val) => {
    fileObj.value = val ? [val] : []
  },
  { immediate: true },
)

watch(
  () => fileObj.value,
  () => {
    emit('update:modelValue', fileObj.value[0])
  },
)

const uploadMethod = async (params: any) => {
  // 保留文件属性
  params.option.file = params.file
}
</script>

<template>
  <div class="mj-form-upload">
    <vxe-upload
      v-model="fileObj"
      :limit-count="1"
      :file-types="fileTypes"
      :upload-method="uploadMethod"
    />
    <span class="desc" v-if="fileTypes?.length">
      支持{{ fileTypes.join('/') }}文件</span
    >
  </div>
</template>

<style lang="scss" scoped>
.mj-form-upload {
  position: relative;

  :deep(.vxe-upload--file-wrapper) {
    .vxe-upload--file-action-btn,
    .vxe-button {
      width: 100%;
      height: 100px;
    }
  }

  .desc {
    pointer-events: none;
    position: absolute;
    color: #999;
    left: 0;
    right: 0;
    bottom: 5px;
    text-align: center;
  }
}
</style>
