<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="120px">
      <el-form-item label="音乐名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入音乐名称查找"
          clearable
          style="width: 200px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="作者" prop="author">
        <el-input
          v-model="queryParams.author"
          placeholder="请输入作者查找"
          clearable
          style="width: 150px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="VIP权限" prop="vip">
        <el-select v-model="queryParams.vip" placeholder="选择VIP权限" clearable style="width: 150px">
          <el-option label="免费" :value="2" />
          <el-option label="VIP" :value="1" />
        </el-select>
      </el-form-item>
      <el-form-item label="上架状态" prop="shelf">
        <el-select v-model="queryParams.shelf" placeholder="选择上架状态" clearable style="width: 150px">
          <el-option label="上架" :value="1" />
          <el-option label="下架" :value="2" />
        </el-select>
      </el-form-item>
      <el-form-item label="音乐类型" prop="musicType">
        <el-select v-model="queryParams.musicType" placeholder="选择音乐类型" clearable style="width: 150px">
          <el-option label="普通歌曲" value="ordinary" />
          <el-option label="混音歌曲" value="mixing" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd">新增歌曲</el-button>
      </el-form-item>
    </el-form>

    <el-table v-loading="loading" :data="playlistList">
      <el-table-column label="序号" align="center" type="index" width="60" />
      <el-table-column label="音乐名称" align="center" prop="name" :show-overflow-tooltip="true" />
      <el-table-column label="作者" align="center" prop="author" :show-overflow-tooltip="true" />
      <el-table-column label="音乐图片" align="center" prop="imgAddr" width="120">
        <template slot-scope="scope">
          <el-image
            v-if="scope.row.imgAddr"
            style="width: 60px; height: 60px"
            :src="getImageUrlMethod(scope.row.imgAddr)"
            :preview-src-list="[getImageUrlMethod(scope.row.imgAddr)]"
            fit="cover"
          >
            <div slot="error" class="image-slot">
              <i class="el-icon-picture-outline"></i>
            </div>
          </el-image>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="音乐地址" align="center" prop="musicAddr" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <el-link 
            v-if="scope.row.musicAddr" 
            type="primary" 
            :underline="false"
            @click="downloadMusic(scope.row.musicAddr, scope.row.name, scope.row.musicId)"
          >
            <i class="el-icon-download"></i> 下载
          </el-link>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="VIP权限" align="center" prop="vip" width="80">
        <template slot-scope="scope">
          <el-tag :type="parseInt(scope.row.vip) === 1 ? 'warning' : 'success'" size="mini">
            {{ parseInt(scope.row.vip) === 1 ? 'VIP' : '免费' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="上架状态" align="center" prop="shelf" width="80">
        <template slot-scope="scope">
          <el-tag :type="parseInt(scope.row.shelf) === 1 ? 'success' : 'danger'" size="mini">
            {{ parseInt(scope.row.shelf) === 1 ? '上架' : '下架' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="音乐类型" align="center" prop="musicType" width="100">
        <template slot-scope="scope">
          <el-tag :type="scope.row.musicType === 'ordinary' ? 'primary' : 'warning'" size="mini">
            {{ scope.row.musicType === 'ordinary' ? '普通歌曲' : '混音歌曲' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="标签" align="center" prop="label" width="150">
        <template slot-scope="scope">
          <el-tag
            v-for="tag in scope.row.label ? scope.row.label.split(';') : []"
            :key="tag"
            type="info"
            size="mini"
            style="margin-right: 5px;"
          >
            {{ tag }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="120" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="120">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['playlist:normal:edit']"
          >编辑</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['playlist:normal:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改普通歌曲对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="音乐名称" prop="name" required>
          <el-input v-model="form.name" placeholder="请输入音乐名称" />
        </el-form-item>
        <el-form-item label="作者" prop="author" required>
          <el-input v-model="form.author" placeholder="请输入作者" />
        </el-form-item>
        <el-form-item label="VIP权限" prop="vip" required>
          <el-select v-model="form.vip" placeholder="请选择VIP权限" style="width: 100%">
            <el-option label="免费" :value="2" />
            <el-option label="VIP" :value="1" />
          </el-select>
        </el-form-item>
        <el-form-item label="上架状态" prop="shelf" required>
          <el-select v-model="form.shelf" placeholder="请选择上架状态" style="width: 100%">
            <el-option label="上架" :value="1" />
            <el-option label="下架" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="音乐类型" prop="musicType" required>
          <el-select v-model="form.musicType" placeholder="请选择音乐类型" style="width: 100%">
            <el-option label="普通歌曲" value="ordinary" />
            <el-option label="混音歌曲" value="mixing" />
          </el-select>
        </el-form-item>
        <el-form-item label="标签" prop="label">
          <el-select
            v-model="selectedTags"
            multiple
            filterable
            placeholder="请选择标签"
            style="width: 100%"
            @change="handleTagsChange">
            <el-option
              v-for="item in tagOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="音乐图片" prop="imgAddr">
          <image-upload
            v-model="form.imgAddr"
            :limit="1"
            :file-type="['jpg', 'jpeg', 'png', 'gif']"
            action="/back/upload/musicImg/file"
          />
        </el-form-item>
        <el-form-item label="音乐文件" prop="musicAddr">
          <div v-if="form.musicAddr" style="margin-bottom: 10px;">
            <el-link 
              type="primary" 
              :underline="false"
              @click="downloadMusic(form.musicAddr, form.name, form.musicId)"
            >
              <i class="el-icon-download"></i> 下载当前音乐文件
            </el-link>
          </div>
          <file-upload
            v-model="form.musicAddr"
            :limit="1"
            :file-type="['mp3', 'wav', 'flac']"
            action="/back/upload/music/file"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listNormalSong, getNormalSong, delNormalSong, addNormalSong, updateNormalSong } from "@/api/playlist/normal";
import { listTags } from "@/api/playlist/tag";
import { getImageUrl } from "@/utils/image";
import request from '@/utils/request';

export default {
  name: "Normal",
  data() {
    return {
      loading: true,
      showSearch: true,
      total: 0,
      playlistList: [],
      title: "",
      open: false,
      tagOptions: [], // 标签选项列表
      selectedTags: [], // 已选择的标签
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        author: null,
        vip: null,
        shelf: null,
        musicType: 'ordinary'
      },
      form: {},
      rules: {
        name: [
          { required: true, message: "音乐名称不能为空", trigger: "blur" }
        ],
        author: [
          { required: true, message: "作者不能为空", trigger: "blur" }
        ],
        vip: [
          { required: true, message: "VIP权限不能为空", trigger: "change" }
        ],
        shelf: [
          { required: true, message: "上架状态不能为空", trigger: "change" }
        ],
        musicType: [
          { required: true, message: "音乐类型不能为空", trigger: "change" }
        ]
      }
    };
  },
  created() {
    this.getList();
    this.getTagOptions();
  },
  methods: {
    // 获取图片完整URL的方法
    getImageUrlMethod(imagePath) {
      return getImageUrl(imagePath);
    },
    /** 查询普通歌曲列表 */
    getList() {
      this.loading = true;
      listNormalSong(this.queryParams).then(response => {
        this.playlistList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 获取标签选项
    getTagOptions() {
      listTags().then(response => {
        this.tagOptions = response.rows || [];
      });
    },
    // 标签选择变化处理
    handleTagsChange(selectedTagIds) {
      this.selectedTags = selectedTagIds;
      // 将选中的标签ID转换为标签名称，用分号分隔
      const selectedTagNames = selectedTagIds.map(id => {
        const tag = this.tagOptions.find(tag => tag.id === id);
        return tag ? tag.name : '';
      }).filter(name => name);
      this.form.label = selectedTagNames.join(';');
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        musicId: null,
        name: null,
        author: null,
        vip: 2,
        shelf: 1,
        imgAddr: null,
        musicAddr: null,
        musicType: "ordinary",
        label: null
      };
      this.selectedTags = [];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      // 重置后保持musicType为ordinary
      this.queryParams.musicType = 'ordinary';
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加普通歌曲";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const musicId = row.musicId || this.ids
      getNormalSong(musicId).then(response => {
        // 处理接口返回的数据结构，从rows数组中获取第一个元素
        if (response.rows && response.rows.length > 0) {
          this.form = response.rows[0];
          
          // 处理VIP权限字段，将字符串转换为数字
          if (this.form.vip !== null && this.form.vip !== undefined) {
            this.form.vip = parseInt(this.form.vip);
          }
          
          // 处理上架状态字段，将字符串转换为数字
          if (this.form.shelf !== null && this.form.shelf !== undefined) {
            this.form.shelf = parseInt(this.form.shelf);
          }
        } else {
          this.$modal.msgError("未找到歌曲信息");
          return;
        }
        // 处理标签选择
        if (this.form.label) {
          const tagNames = this.form.label.split(';');
          this.selectedTags = tagNames.map(name => {
            const tag = this.tagOptions.find(tag => tag.name === name);
            return tag ? tag.id : null;
          }).filter(id => id);
        }
        this.open = true;
        this.title = "修改普通歌曲";
      }).catch(error => {
        this.$modal.msgError("获取歌曲信息失败");
        console.error("获取歌曲详情失败:", error);
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateNormalSong(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addNormalSong(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除普通歌曲编号为"' + ids + '"的数据项？').then(function() {
        return delNormalSong(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    // 下载音乐文件
    downloadMusic(musicAddr, musicName, musicId) {
      if (!musicAddr) {
        this.$modal.msgError("音乐文件地址为空，无法下载");
        return;
      }
      
      // 构建下载URL，直接使用相对路径，让request自动处理baseUrl
      let downloadUrl = musicAddr;
      
      // 拼接musicId参数
      if (!downloadUrl.includes('?')) {
        downloadUrl += '?musicId=' + musicId;
      } else {
        downloadUrl += '&musicId=' + musicId;
      }
      
      // 构建完整的URL
      if (!musicAddr.startsWith('http://') && !musicAddr.startsWith('https://')) {
        downloadUrl = process.env.VUE_APP_BASE_API + downloadUrl;
      }
      
      // 使用fetch API下载文件，确保正确处理二进制数据
      this.$message.info("正在下载音乐文件...");
      
      fetch(downloadUrl, {
        method: 'GET',
        headers: {
          'Authorization': 'Bearer ' + this.$store.getters.token
        }
      })
      .then(response => {
        if (!response.ok) {
          throw new Error('下载失败');
        }
        return response.blob();
      })
      .then(blob => {
        
        // 从URL中提取文件扩展名
        let fileExtension = '';
        if (musicAddr) {
          const urlParts = musicAddr.split('.');
          if (urlParts.length > 1) {
            fileExtension = '.' + urlParts[urlParts.length - 1].split('?')[0]; // 移除查询参数
          }
        }
        
        // 如果没有扩展名，默认使用.mp3
        if (!fileExtension || fileExtension === '.') {
          fileExtension = '.mp3';
        }
        
        // 构建下载文件名
        const downloadFileName = (musicName || 'music') + fileExtension;
        
        // 创建下载链接
        const url = window.URL.createObjectURL(blob);
        const link = document.createElement('a');
        link.href = url;
        link.download = downloadFileName;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        
        // 释放URL对象
        window.URL.revokeObjectURL(url);
        
        this.$modal.msgSuccess(`音乐文件下载完成: ${downloadFileName}`);
      })
      .catch(error => {
        console.error('下载失败:', error);
        this.$modal.msgError("下载失败，请重试");
      });
    }
  }
};
</script>

<style scoped>
.el-tag {
  border-radius: 12px;
}
</style>
