<script setup>
import { apiSystemCommon } from '@/api/system'
import { ElMessage } from 'element-plus'

const props=defineProps({
  showFileList:{
    type:Boolean,
    default:false
  },
  fileSize:{//上传大小控制 -1则不控制 以M为单位
    type:Number,
    default:-1,
  },
  accept:{//多个用英文逗号隔开 eg:.doc,.docx,
    type:String,
    default:''
  },
  autoUpload:{
    type:Boolean,
    default:true
  }
})

const emits=defineEmits(['success'])

function beforeUpload(e){
  // console.log(e);
  // 校验文件类型
  if(props.accept){
    const typeArr=props.accept.split(',')
    if(!typeArr.includes(e.type)){
      ElMessage.warning('请上传正确的文件类型')
      return false
    }
  }
  // 校验文件大小
  if(props.fileSize!==-1){
    const acceptSize=props.fileSize*1024*1024
    if(acceptSize<e.size){
      ElMessage.warning('文件过大')
      return false
    }
  }

  return true
}

const loading=ref(false)
async function handleUpload(e){
  const form = new FormData()
  form.append("File", e.file)
  loading.value=true
  const res=await apiSystemCommon.uploadFile(form)
  loading.value=false
  if(res.Ret===200){
    emits('success',res.Data)
  }
}


</script>

<template>
  <el-upload
    ref="uploadRef"
    action=""
    :auto-upload="props.autoUpload"
    :showFileList="props.showFileList"
    :accept="props.accept"
    :before-upload="beforeUpload"
    :http-request="handleUpload"
  >
    
    <template #trigger>
      <div v-loading="loading" element-loading-text="上传中...">
        <slot name="trigger"></slot>
      </div>
    </template>
    
    <slot></slot>
    
    <template #tip>
      <slot name="tip"></slot>
    </template>
  </el-upload>
</template>