<template>
  <div>
    <el-button link type="primary" icon="Upload" @click="handleUpload">上传</el-button>
    <el-dialog
      v-model="fileDialog"
      title="上传音频"
      append-to-body
      class="file-upload"
      width="500px"
    >
      <el-upload
        :action="`${baseUrl}/system/file/upload`"
        :before-upload="beforeAvatarUpload"
        :data="{ fileType: 3 }"
        :headers="{
          authorization: getToken(),
        }"
        :limit="1"
        :show-file-list="false"
        :on-error="uploadError"
        :on-success="uploadSuccess"
        class="file-uploader"
      >
        <template #trigger>
          <el-button type="primary">选择文件</el-button>
        </template>
        <template #tip>
          <div class="el-upload__tip">支持格式：wav / mp3</div>
        </template>
      </el-upload>
    </el-dialog>
  </div>
</template>
<script setup>
import { ref } from "vue";
import { getToken } from "@/utils/auth.js";
import { isAudioByMimeType } from "@/utils/index.js";
import { ElMessage } from "element-plus";

const emits = defineEmits(['success', 'error'])

const baseUrl = ref(import.meta.env.VITE_APP_BASE_API);
const fileDialog = ref(false);
const handleUpload = () => {
  fileDialog.value = true;
};

const beforeAvatarUpload = (rawFile) => {
  if (isAudioByMimeType(rawFile.type)) {
    return true
  }
  ElMessage.error(`不支持上传格式为${rawFile.type}的文件`)
  return false
}

const uploadSuccess = (e) => {
  fileDialog.value = false
  ElMessage.success('音频文件上传成功')
  emits('success', e.msg)
}
const uploadError = (e) => {
  console.log("uploadError", e)
  emits('error')
}
</script>
