<template>
  <div class="corpus-list">
    <!-- 工具栏 -->
    <div class="list-toolbar">
      <div class="toolbar-left">
        <el-button type="primary" size="default" @click="openDialog(true)">＋新建语料</el-button>
      </div>
    </div>

    <!-- 表格 -->
    <el-table :data="corpusData" stripe style="width:100%;" max-height="400">
      <el-table-column prop="id" label="语料编号" show-overflow-tooltip />
      <el-table-column prop="text" label="文本内容" show-overflow-tooltip />
      <el-table-column prop="categoryName" label="所属分类" show-overflow-tooltip />
      <el-table-column prop="language" label="语种" />
      <el-table-column prop="dialect" label="方言" />
      <el-table-column prop="emotion" label="情绪" />
      <el-table-column prop="voice" label="音色" />
      <el-table-column prop="fileSize" label="文件大小" />
      <el-table-column label="操作" fixed="right">
        <template #default="{ row }">
          <el-button link @click="play(row.audioFilePath)" type="primary" icon="VideoPlay">播放</el-button>
          <el-button icon="Download" link type="primary" @click="handleDownload(row)">下载</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-wrapper">
      <el-pagination background layout="prev, pager, next, jumper" :total="total" :page-size="10"
        v-model:current-page="page" small />
    </div>

    <el-dialog v-model="addCorpusVisible" :title="'新建语料'" :append-to-body="true" width="600px" @close="resetDialog">
      <el-form ref="ruleFormRef" :model="ruleForm" label-width="auto">
        <el-form-item label="模型" prop="model">
          <el-select v-model="ruleForm.model" placeholder="模型">
            <el-option label="科大讯飞" value="科大讯飞" />
          </el-select>
        </el-form-item>
        <el-form-item label="文本" prop="text">
          <el-input type="textarea" :rows="2" v-model="ruleForm.text" placeholder="请输入文本" />
        </el-form-item>
        <el-form-item label="语种" prop="language">
          <el-select v-model="ruleForm.language" placeholder="语种">
            <el-option v-for="item in langOption" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="上传文件">
          <el-upload v-model:file-list="uploadFileList" :action="`${data.baseUrl}/system/file/upload`"
            :before-upload="beforeAvatarUpload" :data="{ fileType: uploadFileType }" :headers="{
              'authorization': getToken()
            }" :limit="1" :on-error="uploadError" :on-success="uploadSuccess" class="file-uploader">
            <el-button type="primary">选取文件</el-button>
            <template #tip>
              <div class="el-upload__tip">
                支持格式：'wav'
              </div>
            </template>
          </el-upload>
        </el-form-item>


      </el-form>
      <template #footer>
        <el-button @click="addCorpusVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmDialog">确定</el-button>
      </template>
    </el-dialog>

    <el-dialog v-model="dialogVisible" title="播放音频" width="600px" :destroy-on-close="true" @close="colseDialog">
      <div class="wave-container">
        <div class="wave">
          <div v-for="(h, index) in waveform" :key="index" :style="{
            width: '4px',
            height: h + '%',
            background: '#3b82f6',
            borderRadius: '2px',
            opacity: 0.6 + (h / 100) * 0.4
          }"></div>
        </div>
        <div class="audio-container">
          <AudioPlayer :src="audioUrl" @audioStatus="audioStatus" />
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { getToken } from "@/utils/auth.js";
import { getCorpusListApi } from '@/api/corpusManger/corpus.js'
import { downloadWavApi } from '@/api/corpusManger/speech_synthesis'
import AudioPlayer from '../../speech_synthesis/components/AudioPlayer.vue';

const props = defineProps({
  categoryId: {
    type: String,
    default: ''
  }
})

const addCorpusVisible = ref(false)

const voiceOption = ref([
  {
    label: '女声',
    value: 'xiaoyan'
  }
])

const langOption = ref([
  {
    label: '中文（普通话）',
    value: '普通话'
  }, {
    label: '英文',
    value: '英文'
  }, {
    label: '粤语',
    value: '粤语'
  }, {
    label: '四川话',
    value: '四川话'
  },
])

const ruleForm = ref({
  text: '',
  model: '科大讯飞',
  voice: 'xiaoyan',
  speed: 50,
  volume: 50,
  pitch: 50,
  sampleRate: '16',
  outputFormat: 'wav'
})

const rules = ref({
  text: [{ required: true, message: '请输入合成文本', trigger: 'blur' }],
  language: [{ required: true, message: '请选择语种', trigger: 'blur' }]
})

const uploadFileList = ref([])
const uploadFileType = ref(null)
const data = {
  baseUrl: import.meta.env.VITE_APP_BASE_API
}

const openDialog = () => {
  addCorpusVisible.value = true
}

const resetDialog = () => {
  addCorpusVisible.value = false
}

const page = ref(1)

const beforeAvatarUpload = (rawFile) => {
  const fileName = rawFile.name.split('.');
  const fileExt = fileName[fileName.length - 1];
  const isTypeOk = ['png', 'jpg', 'jpeg'].indexOf(fileExt) >= 0;
  if (!isTypeOk) {
    proxy.$modal.msgError(`文件格式不正确，请上传${['png', 'jpg', 'jpeg'].join("/")}格式文件!`);
    return false;
  }
  const { label = undefined, value = undefined } = supportType?.find(item => item.label === rawFile.type)
  if (label) {
    uploadFileType.value = value
  }
  // 校检文件大小

  const isLt = rawFile.size / 1024 / 1024 < 5;
  if (!isLt) {
    ElMessage.error(`上传文件大小不能超过 ${5} MB!`);
    return false;
  }

  return true
}

const uploadSuccess = (e) => {
  imgUrl.value = e.msg
  ElMessage.success('上传成功')
}
const uploadError = (e) => {
  console.log("uploadError", e)
}

// 模拟数据
const corpusData = ref([])
const total = ref(0)

const getCorpusList = async () => {
  const obj = {
    pageNum: page.value,
    pageSize: 10,
    categoryId: props.categoryId
  }
  const res = await getCorpusListApi(obj)
  if (res.code === 0) {
    corpusData.value = res.rows
    total.value = res.total
  }
}


const statusType = (status) => {
  if (status === '已通过') return 'success'
  if (status === '待审核') return 'warning'
  return 'info'
}

const dialogVisible = ref(false)

// 波形数据
const waveform = ref(Array.from({ length: 60 }, () => Math.floor(Math.random() * 60 + 20)))
const timer = ref(null)

// 模拟波形动态变化
const updateWaveform = () => {
  waveform.value = Array.from({ length: 60 }, () => Math.floor(Math.random() * 60 + 20))
}

const audioUrl = ref('https://sf1-cdn-tos.huoshanstatic.com/obj/media-fe/xgplayer_doc_video/music/audio.mp3')

const audioStatus = (isPlaying) => {
  if (isPlaying) {
    timer.value = setInterval(updateWaveform, 100)
  } else {
    if (timer.value) clearInterval(timer.value)
  }
}

const play = (url) => {
  dialogVisible.value = true
  audioUrl.value = import.meta.env.VITE_MINIO_URL + url
}

const colseDialog = () => {
  dialogVisible.value = false
  if (timer.value) clearInterval(timer.value)
}

const handleDownload = async (row) => {
  const response = await fetch(import.meta.env.VITE_MINIO_URL + row.audioFilePath)
  const blob = await response.blob()
  const blobUrl = URL.createObjectURL(blob)

  const a = document.createElement('a')
  a.href = blobUrl

  a.download = `${row.id}.${row.audioFilePath.split('.')[1]}`
  a.click()

  URL.revokeObjectURL(blobUrl)
}

watch(() => props.categoryId,
  () => {
    getCorpusList()
})

onMounted(() => {
  getCorpusList()
})

onBeforeUnmount(() => {
  if (timer.value) clearInterval(timer.value)
})
</script>

<style lang="scss" scoped>
.corpus-list {
  background: #fff;
  padding: 20px;
  border-radius: 12px;

  .list-toolbar {
    display: flex;
    flex-direction: column;
    gap: 12px;
    margin-bottom: 16px;

    .toolbar-left {
      display: flex;
      align-items: center;
      gap: 10px;
      flex-wrap: wrap;
    }
  }

  .pagination-wrapper {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-top: 16px;
  }

  .text-muted {
    color: #94a3b8;
  }

  .text-sm {
    font-size: 13px;
  }
}


.wave-container {
  border-radius: 12px;
  padding: 16px;
  min-height: 140px;
  position: relative;

  .wave {
    display: flex;
    align-items: flex-end;
    height: 80px;
    gap: 4px;
    justify-content: center;
  }

  .audio-container {
    width: 100%;
    margin: 10px 0;
  }
}
</style>