<template>
  <div class='app-container'>
    <!-- 搜索 -->
    <el-form inline>
      <el-form-item label="音频ID：">
        <el-input v-model="data.form.id" placeholder="请输入音频ID" clearable />
      </el-form-item>
      <el-form-item label="音频名称：">
        <el-input v-model="data.form.name" placeholder="请输入音频名称" clearable />
      </el-form-item>
      <el-form-item label="音频分类：">
        <el-select v-model="data.form.sceneId" placeholder="请选择音频分类" clearable>
          <el-option v-for="item in audioClassData.options" :key="item.id" :value="item.id" :label="item.name" />
        </el-select>
      </el-form-item>
      <el-form-item label="当前状态：">
        <el-select v-model="data.form.status" placeholder="请选择当前状态" clearable>
          <el-option v-for="item in sys_change_status" :key="item.value" :value="item.value" :label="item.label" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="getSearch">搜索</el-button>
        <el-button icon="Refresh" @click="getRefresh">重置</el-button>
        <el-button type="primary" plain icon="Plus" @click="getDialog()"
          v-hasPermi="['content:list:add']">新增</el-button>
      </el-form-item>
    </el-form>
    <!-- 列表 -->
    <el-table :data="data.tableData" v-loading="loading">
      <el-table-column label="音频ID" prop="id" align="center" />
      <el-table-column label="音频名称" prop="name" align="center" />
      <el-table-column label="时长" align="center">
        <template #default="scope">
          {{ playTime(scope.row.playTime) }}
        </template>
      </el-table-column>
      <el-table-column label="音频分类" prop="sceneId" align="center" :formatter="sceneFormatter" />
      <el-table-column label="当前状态" prop="status" align="center">
        <template #default="scope">
          <dict-tag :options="sys_change_status" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="更新时间" prop="updateTime" align="center" />
      <el-table-column label="操作" align="center">
        <template #default="scope">
          <el-button type="primary" link :icon="scope.row.play ? 'VideoPause' : 'VideoPlay'"
            @click="getPlay(scope.row)" />
          <el-button type="primary" link @click="getDialog(scope.row.id, '编辑')"
            v-hasPermi="['content:list:edit']">编辑</el-button>
          <el-button v-if="scope.row.status === 1" type="primary" link @click="getChange(scope.row.id, '上架', 0)"
            v-hasPermi="['content:list:on']">上架</el-button>
          <el-button v-else type="primary" link @click="getChange(scope.row.id, '下架', 1)"
            v-hasPermi="['content:list:off']">下架</el-button>
          <el-button type="danger" link @click="getDelete(scope.row)"
            v-hasPermi="['content:list:delete']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total > 0" :total="total" v-model:page="data.form.pageNum" v-model:limit="data.form.pageSize"
      @pagination="getList" />
    <!-- 弹窗 -->
    <el-dialog v-model="dialogVisible" :title="title" width="500" :before-close="getClose">
      <el-form ref="dialogForm" :model="data.dialogForm" :rules="data.rules" label-width="100px">
        <el-form-item label="上传音频：" prop="list" v-if="title === '编辑' ? false : true">
          <CustomUpload ref="customUpload" :url="`${baseUrl}/radio/tProgram/mp3/upload`" showFileList multiple
            @upload="upload" style="width: 100%" />
        </el-form-item>
        <el-form-item label="音频名称：" prop="name" v-else>
          <el-input v-model="data.dialogForm.name" disabled />
        </el-form-item>
        <el-form-item label="音频分类：" prop="sceneId">
          <el-select v-model="data.dialogForm.sceneId" placeholder="请选择音频分类" clearable>
            <el-option v-for="item in audioClassData.options" :key="item.id" :value="item.id" :label="item.name" />
            <el-option label="无" :value="data.dialogForm.sceneId"
              v-if="data.dialogForm.sceneId && !audioClassData.options.some(i => i.id === data.dialogForm.sceneId)" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="getClose">取消</el-button>
        <el-button type="primary" @click="getSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { list, detail, submit, change } from '@/api/content/list'
import { useAudioClass } from '@/hooks/index.js'
import { onUnmounted } from 'vue';

const { proxy } = getCurrentInstance();
const { sys_change_status } = proxy.useDict("sys_change_status")
const { audioClassData, getAudioClass } = useAudioClass()
getAudioClass()
const baseUrl = ref(import.meta.env.VITE_APP_BASE_API)

// 遮罩层
const loading = ref(false)

const data = reactive({
  // 表单
  form: {
    pageNum: 1,
    pageSize: 10
  },
  // 列表
  tableData: [],
  // 校验
  rules: {
    list: [{
      required: true, message: '请上传音频', trigger: 'change'
    }],
    sceneId: [{
      required: true, message: '请选择音频分类', trigger: 'change'
    }]
  },
  // 弹窗表单
  dialogForm: {
    list: [],
    sceneId: ''
  }
})
// 总数据
const total = ref(0)

// 列表
function getList() {
  loading.value = true
  list(data.form).then(res => {
    if (res.code === 0) {
      data.tableData = res.data.records
      total.value = res.data.total
      loading.value = false
    }
  })
}
getList()

// 搜索
function getSearch() {
  data.form.pageNum = 1
  getList()
}

// 重置
function getRefresh() {
  data.form = {
    pageNum: 1,
    pageSize: 10
  }
  getList()
}

// 弹窗
const dialogVisible = ref(false)
// 弹窗标题
const title = ref(undefined)
// 打开弹窗
function getDialog(id, key) {
  dialogVisible.value = true
  title.value = '新增'
  if (id) {
    getDetail(id)
  }
}

// 详情
function getDetail(id) {
  title.value = '编辑'
  detail({ id: id }).then(res => {
    if (res.code === 0) {
      data.dialogForm = res.data
    }
  })
}

// 上传
function upload(file) {
  data.dialogForm.list = file
}

// 提交
function getSubmit() {
  proxy.$refs['dialogForm'].validate(valid => {
    if (valid) {
      let list = []
      if (!data.dialogForm.id) {
        data.dialogForm.list.map(i => {
          i['sceneId'] = data.dialogForm.sceneId
        })
        delete data.dialogForm.sceneId
        list = data.dialogForm.list
      } else {
        list.push(data.dialogForm)
      }
      submit(list).then(res => {
        if (res.code === 0) {
          proxy.$modal.msgSuccess("提交成功！")
          getClose()
          getList()
        }
      })
    } else {
      return false
    }
  })
}

// 取消
function getClose() {
  dialogVisible.value = false
  data.dialogForm = {}
  proxy.$refs.dialogForm.resetFields()
  if (title.value === '新增') {
    proxy.$refs.customUpload.onRefresh()
  }
}

// 上下架
function getChange(id, key, status) {
  change({
    ids: id,
    status: status
  }).then(res => {
    if (res.code === 0) {
      proxy.$modal.msgSuccess(`${key}成功！`)
      getList()
    }
  })
}

// 删除
function getDelete(row) {
  proxy.$modal.confirm(`是否删除音频名称为：${row.name}的数据?`).then(() => {
    change({
      ids: row.id,
      status: row.status,
      delFlag: 2
    }).then(res => {
      if (res.code === 0) {
        proxy.$modal.msgSuccess('删除成功！')
        getList()
      }
    })
  })
}

// 播放
const audio = new Audio()
const lastId = ref('')
const getPlay = (e) => {
  data.tableData.map(i => i.play = false)
  audio.pause()
  if (lastId.value !== e.id && !e.play) {
    audio.src = e.playUrl
    audio.play()
    e.play = true
    lastId.value = e.id
  } else {
    lastId.value = ''
  }
}

// 字典
function sceneFormatter(row) {
  let e = audioClassData.options.find(i => i.id === row.sceneId)
  return e ? e.name : '无'
}

onUnmounted(() => {
  audio.pause()
})
</script>