<script setup lang="ts">
import type { UploadInstance, UploadProps, UploadRawFile } from 'element-plus'

import { SYS_INFO } from '@vben/preferences'
import { useAccessStore } from '@vben/stores'

import { genFileId } from 'element-plus'

import audioPlay from '#/assets/image/audio_play.png'

const props = defineProps({
  modelValue: {
    type: String,
    default: '',
  },
})
const emits = defineEmits(['update:modelValue'])
const upload = ref<UploadInstance>()
const { accessToken } = storeToRefs(useAccessStore())

const handleExceed: UploadProps['onExceed'] = (files) => {
  upload.value!.clearFiles()
  const file = files[0] as UploadRawFile
  file.uid = genFileId()

  upload.value!.handleStart(file)
}
// 音频上传前
const beforeUploadVoice: UploadProps['beforeUpload'] = (rawFile) => {
  const fileType = ['audio/mpeg']
  if (!fileType.includes(rawFile.type)) {
    ElMessage.error('上传格式不正确，只支持mp3')
    return false
  }
}
// 音频上传成功回调
const handleSuccessVoice: UploadProps['onSuccess'] = (response, _) => {
  if (response.code === 200) {
    emits('update:modelValue', response.data.filePath)
  }
}
// const submitUpload = () => {
//   upload.value!.submit()
// }
// 音频相关
const audio = ref(new Audio())
function playAudio(url: string) {
  nextTick(() => {
    audio.value.src = url
    // 从头开始
    audio.value.currentTime = 0
    // 播放
    audio.value?.play()
  })
}
function closeAudio() {
  audio.value.pause()
  upload.value!.clearFiles()
  emits('update:modelValue', '')
}

// function onClear() {}
</script>

<template>
  <div style="height: min-content">
    <el-upload
      ref="upload"
      class="upload-demo"
      action="/api/main/sysFileInfo/tenUploadAll"
      :headers="{
        Authorization: `Bearer ${accessToken}`,
        'X-Tenant-Id': SYS_INFO.tenantId,
      }"
      :limit="1"
      :on-exceed="handleExceed"
      :before-upload="beforeUploadVoice"
      :on-success="handleSuccessVoice"
      :show-file-list="false"
    >
      <el-button
        :disabled="props.modelValue.length > 0"
        type="primary"
        size="small"
      >
        点击上传
      </el-button>
    </el-upload>
    <div v-if="props.modelValue" class="img-audio">
      <el-image
        class="img"
        :src="audioPlay"
        @click="playAudio(props.modelValue)"
      />
      <div class="close" @click="closeAudio">x</div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.img-audio {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 75px;
  height: 10px;
  transform: translate(-5px, 7px);

  .img {
    width: 40px;
    height: 40px;
    cursor: pointer;
  }

  .close {
    display: none;
    cursor: pointer;
  }

  &:hover {
    .close {
      display: block;
    }
  }
}
</style>
