<template>
  <div class="media-input">
    <Tabs :tabs="tabs" v-model:value="type" :tabsStyle="{ marginBottom: '15px' }" />
    <template v-if="type === 'video'">
      <ElUpload
        class="uploadCon"
        action=""
        :show-file-list="false"
        accept=".mp4,.avi,.flv"
        :http-request="
          (fileData: any) => {
            handleUpload('video', fileData)
            return undefined
          }
        "
      >
        <Button type="primary">上传视频</Button>
      </ElUpload>
    </template>

    <template v-if="type === 'audio'">
      <ElUpload
        class="uploadCon"
        action=""
        :show-file-list="false"
        accept=".mp3,.wav,.m4a"
        :http-request="
          (fileData: any) => {
            handleUpload('audio', fileData)
            return undefined
          }
        "
      >
        <Button type="primary">上传音频</Button>
      </ElUpload>
    </template>
  </div>
</template>

<script lang="ts" setup>
import { ref } from "vue"
import message from "@/utils/message"
import Tabs from "@/components/Tabs.vue"
import Button from "@/components/Button.vue"
import { ElUpload, ElButton, ElMessage, type UploadRequestOptions } from "element-plus"
import fileUpload from "@/utils/oss-file-upload"

type TypeKey = "video" | "audio"
interface TabItem {
  key: TypeKey
  label: string
}

const emit = defineEmits<{
  (event: "insertVideo", payload: string): void
  (event: "insertAudio", payload: string): void
  (event: "close"): void
}>()

const type = ref<TypeKey>("video")
const tabs: TabItem[] = [
  { key: "video", label: "视频" },
  { key: "audio", label: "音频" }
]

async function handleUpload(type: TypeKey, fileData: UploadRequestOptions) {
  fileUpload(fileData.file.name, fileData.file)
    .then(res => {
      if (type === "audio") {
        emit("insertAudio", res)
      } else {
        emit("insertVideo", res)
      }
    })
    .catch(() => {
      ElMessage({
        showClose: true,
        message: "上传失败!",
        type: "error"
      })
    })
}
</script>

<style lang="scss" scoped>
.media-input {
  width: 120px;
  & :deep(.tabs) {
    justify-content: center;
  }
  .uploadCon {
    text-align: center;
  }
}
</style>
