<template>
  <div class="music-management-container">
    <vab-query-form>
      <vab-query-form-left-panel :span="12">
        <el-button icon="el-icon-plus" type="primary" @click="handleEdit">添加</el-button>
        <el-button icon="el-icon-delete" type="danger" @click="handleDelete">批量删除</el-button>
      </vab-query-form-left-panel>
      <vab-query-form-right-panel :span="12">
        <el-form :inline="true" :model="queryForm" @submit.native.prevent>
          <el-form-item>
            <el-select v-model="queryForm.scene" clearable placeholder="请选择场景" @change="queryData">
              <el-option v-for="item in sceneList" :key="item.scene" :label="item.sceneName" :value="item.scene" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-input v-model.trim="queryForm.keyword" clearable placeholder="请输入查询条件" />
          </el-form-item>
          <el-form-item>
            <el-button icon="el-icon-search" type="primary" @click="queryData">查询</el-button>
          </el-form-item>
        </el-form>
      </vab-query-form-right-panel>
    </vab-query-form>

    <el-table v-loading="listLoading" :data="list" :element-loading-text="elementLoadingText" @selection-change="setSelectRows">
      <el-table-column align="center" show-overflow-tooltip type="selection" width="55" />
      <el-table-column align="center" label="排序" prop="sort" sortable width="100" />

      <el-table-column align="center" label="音乐名称" prop="name" show-overflow-tooltip />

      <el-table-column align="center" label="场景" show-overflow-tooltip>
        <template #default="{ row }">
          {{ getSceneName(row.scene) }}
        </template>
      </el-table-column>

      <el-table-column align="center" label="试听" width="300">
        <template slot-scope="scope">
          <audio controls :src="scope.row.musicUrl" style="width: 250px; height: 40px"></audio>
        </template>
      </el-table-column>

      <el-table-column align="center" label="标签" prop="tag" show-overflow-tooltip />

      <el-table-column align="center" label="状态" prop="isEnabled" width="100">
        <template #default="{ row }">
          <el-switch active-color="#13ce66" inactive-color="#ff4949" :value="row.isEnabled" @change="handleToggleEnable(row, $event)" />
        </template>
      </el-table-column>

      <el-table-column align="center" fixed="right" label="操作" width="200">
        <template slot-scope="scope">
          <el-button type="text" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button :disabled="!scope.row.isEnabled || isFirstEnabled(scope.row)" type="text" @click="handleMoveUp(scope.row)">
            上移
          </el-button>
          <el-button :disabled="!scope.row.isEnabled || isLastEnabled(scope.row)" type="text" @click="handleMoveDown(scope.row)">
            下移
          </el-button>
          <el-button type="text" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      background
      :current-page="queryForm.pageNo"
      :layout="layout"
      :page-size="queryForm.pageSize"
      :total="total"
      @current-change="handleCurrentChange"
      @size-change="handleSizeChange"
    />
    <edit ref="edit" @fetch-data="fetchData" />
  </div>
</template>

<script>
  import { doDelete, getList, toggleEnable, doMoveUp, doMoveDown } from '@/api/spring/blessing/music/index'
  import { getAll as getAllScenes } from '@/api/spring/blessing/scene'
  import Edit from './components/AppManagementEdit'

  export default {
    name: 'MusicManagement',
    components: { Edit },
    data() {
      return {
        list: [],
        listLoading: true,
        layout: 'total, sizes, prev, pager, next, jumper',
        total: 0,
        selectRows: [],
        elementLoadingText: '正在加载...',
        queryForm: {
          pageNo: 1,
          pageSize: 10,
          keyword: '',
          scene: '',
        },
        sceneList: [],
      }
    },
    created() {
      this.fetchSceneList()
      this.fetchData()
    },
    methods: {
      setSelectRows(val) {
        this.selectRows = val
      },
      handleEdit(row) {
        if (row && row.id) {
          this.$refs['edit'].showEdit(row)
        } else {
          this.$refs['edit'].showEdit()
        }
      },
      handleDelete(row) {
        if (row && row.id) {
          this.$baseConfirm('你确定要删除当前项吗', null, async () => {
            try {
              const { msg } = await doDelete({ ids: [row.id] })
              this.$baseMessage(msg, 'success')
              this.fetchData()
            } catch (error) {
              console.error(error)
            }
          })
        } else {
          if (this.selectRows.length > 0) {
            const ids = this.selectRows.map((item) => item.id)
            this.$baseConfirm('你确定要删除选中项吗', null, async () => {
              try {
                const { msg } = await doDelete({ ids })
                this.$baseMessage(msg, 'success')
                this.fetchData()
              } catch (error) {
                console.error(error)
              }
            })
          } else {
            this.$baseMessage('未选中任何行', 'error')
            return false
          }
        }
      },
      handleSizeChange(val) {
        this.queryForm.pageSize = val
        this.fetchData()
      },
      handleCurrentChange(val) {
        this.queryForm.pageNo = val
        this.fetchData()
      },
      queryData() {
        this.queryForm.pageNo = 1
        this.fetchData()
      },
      async fetchData() {
        this.listLoading = true
        try {
          const { data } = await getList(this.queryForm)
          this.list = data.list
          this.total = data.totalCount
        } catch (error) {
          console.error(error)
        } finally {
          this.listLoading = false
        }
      },
      async handleToggleEnable(row, value) {
        this.$baseConfirm(`你确定要${value ? '启用' : '禁用'}当前项吗`, null, async () => {
          try {
            const { msg } = await toggleEnable(row.id, value)
            this.$baseMessage(msg, 'success')
            this.fetchData()
          } catch (error) {
            console.error(error)
          }
        })
      },
      async handleMoveUp(row) {
        try {
          const { msg } = await doMoveUp(row.id)
          this.$baseMessage(msg, 'success')
          this.fetchData()
        } catch (error) {
          console.error(error)
        }
      },
      async handleMoveDown(row) {
        try {
          const { msg } = await doMoveDown(row.id)
          this.$baseMessage(msg, 'success')
          this.fetchData()
        } catch (error) {
          console.error(error)
        }
      },
      isFirstEnabled(row) {
        const enabledList = this.list.filter((item) => item.isEnabled)
        return enabledList.length > 0 && enabledList[0].id === row.id
      },
      isLastEnabled(row) {
        const enabledList = this.list.filter((item) => item.isEnabled)
        return enabledList.length > 0 && enabledList[enabledList.length - 1].id === row.id
      },
      async fetchSceneList() {
        try {
          const { data } = await getAllScenes()
          this.sceneList = data || []
        } catch (error) {
          console.error(error)
        }
      },
      getSceneName(scene) {
        if (!scene) return '通用'
        const found = this.sceneList.find((item) => item.scene === scene)
        return found ? found.sceneName : scene
      },
    },
  }
</script>

<style scoped>
  .music-management-container {
    padding: 20px;
  }
</style>
