<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="场景名称" prop="scene">
        <el-input
          v-model="queryParams.scene"
          placeholder="请输入场景名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </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="sceneList">
      <el-table-column label="序号" align="center" type="index" width="60" />
      <el-table-column label="场景名称" align="center" prop="scene" :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.scene, scope.row.sceneId)"
          >
            <i class="el-icon-download"></i> 下载
          </el-link>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="120" />
      <el-table-column label="更新时间" align="center" prop="updateTime" width="120" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除</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="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="场景名称" prop="scene">
          <el-input v-model="form.scene" placeholder="请输入场景名称" />
        </el-form-item>
        <el-form-item label="音乐文件" prop="musicAddr">
          <file-upload 
            v-model="form.musicAddr" 
            :limit="1" 
            :file-type="['mp3', 'wav', 'flac']" 
            action="/back/upload/music/file"
          />
        </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>
      <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 { listScene, getScene, delScene, addScene, updateScene } from "@/api/playlist/scene";
import { getImageUrl } from "@/utils/image";
import request from '@/utils/request';

export default {
  name: "Scene",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 场景音乐表格数据
      sceneList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        scene: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        scene: [
          { required: true, message: "场景名称不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    // 获取图片完整URL的方法
    getImageUrlMethod(imagePath) {
      return getImageUrl(imagePath);
    },
    /** 查询场景音乐列表 */
    getList() {
      this.loading = true;
      listScene(this.queryParams).then(response => {
        this.sceneList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        scene: null,
        musicAddr: null,
        imgAddr: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加场景音乐";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getScene(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改场景音乐";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateScene(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addScene(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 delScene(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    // 下载音乐文件
    downloadMusic(musicAddr, sceneName, sceneId) {
      if (!musicAddr) {
        this.$modal.msgError("音乐文件地址为空，无法下载");
        return;
      }
      
      // 构建下载URL，直接使用相对路径，让request自动处理baseUrl
      let downloadUrl = musicAddr;
      
      // 拼接sceneId参数
      if (!downloadUrl.includes('?')) {
        downloadUrl += '?musicId=' + sceneId;
      } else {
        downloadUrl += '&musicId=' + sceneId;
      }
      
      // 构建完整的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 = (sceneName || 'scene_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> 