<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="80px">
      <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="shelf">
        <el-select v-model="queryParams.shelf" placeholder="选择上架状态" clearable style="width: 150px">
          <el-option
            v-for="item in statusOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="选择权限" prop="vip">
        <el-select v-model="queryParams.vip" placeholder="选择权限" clearable style="width: 150px">
          <el-option
            v-for="item in permissionOptions"
            :key="item.label"
            :label="item.label"
            :value="item.value"
          />
        </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" style="width: 100%">
      <el-table-column label="序号" align="center" type="index" width="50" />
      <el-table-column label="混音名称" align="center" prop="name" min-width="150" :show-overflow-tooltip="true" />
<!--      <el-table-column label="作者" align="center" prop="author" :show-overflow-tooltip="true" />-->
      <el-table-column label="音乐场景" align="center" prop="musicScene" min-width="150">
        <template slot-scope="scope">
          <el-tag
            v-for="scene in getScenes(scope.row)"
            :key="scene.sceneId"
            type="primary"
            size="mini"
            style="margin-right: 5px; margin-bottom: 5px;"
          >
            {{ scene.scene }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="VIP权限" align="center" prop="vip" width="80">
        <template slot-scope="scope">
          <el-tag :type="scope.row.vip === '1' ? 'warning' : 'success'" size="mini">
            {{ scope.row.vip === '1' ? 'VIP' : '免费' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="标签" align="center" prop="label" min-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; margin-bottom: 5px;"
          >
            {{ tag }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="上架状态" align="center" prop="shelf" width="80">
        <template slot-scope="scope">
          <el-tag :type="scope.row.shelf === '1' ? 'success' : 'danger'" size="mini">
            {{ scope.row.shelf === '1' ? '上架' : '下架' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" min-width="140" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="100">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['playlist:remix:edit']"
          >编辑</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['playlist:remix: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="musicId" required>
          <el-button type="primary" @click="openMusicDialog">选择音乐</el-button>
          <span v-if="selectedMusicInfo" style="margin-left: 10px; color: #409EFF;">
            已选择: {{ selectedMusicInfo.name }} - {{ selectedMusicInfo.author }}
          </span>
        </el-form-item>
        <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="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="musicScenes" required>
          <el-select
            v-model="selectedScenes"
            multiple
            filterable
            placeholder="请选择音乐场景"
            style="width: 100%"
            @change="handleSceneChange">
            <el-option
              v-for="scene in availableScenes"
              :key="scene.sceneId"
              :label="scene.scene"
              :value="scene.sceneId">
            </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>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 音乐选择对话框 -->
    <el-dialog title="选择音乐" :visible.sync="musicDialogVisible" width="1000px" append-to-body>
      <el-form :model="musicQueryParams" ref="musicQueryForm" size="small" :inline="true" label-width="80px">
        <el-form-item label="音乐名称" prop="name">
          <el-input
            v-model="musicQueryParams.name"
            placeholder="请输入音乐名称"
            clearable
            style="width: 200px"
            @keyup.enter.native="handleMusicQuery"
          />
        </el-form-item>
        <el-form-item label="作者" prop="author">
          <el-input
            v-model="musicQueryParams.author"
            placeholder="请输入作者"
            clearable
            style="width: 200px"
            @keyup.enter.native="handleMusicQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleMusicQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetMusicQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <el-table
        v-loading="musicLoading"
        :data="musicTableData"
        @row-click="handleMusicRowClick"
        highlight-current-row
        style="width: 100%">
        <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="VIP权限" align="center" prop="vip" width="80">
          <template slot-scope="scope">
            <el-tag :type="scope.row.vip === 1 ? 'warning' : 'success'" size="mini">
              {{ 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="scope.row.shelf === 1 ? 'success' : 'danger'" size="mini">
              {{ scope.row.shelf === 1 ? '上架' : '下架' }}
            </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; margin-bottom: 5px;"
            >
              {{ tag }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" prop="createTime" width="120" />
        <el-table-column label="操作" align="center" width="80">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="primary"
              @click="selectMusic(scope.row)"
            >选择</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="musicTotal>0"
        :total="musicTotal"
        :page.sync="musicQueryParams.pageNum"
        :limit.sync="musicQueryParams.pageSize"
        @pagination="getMusicList"
      />

      <div slot="footer" class="dialog-footer">
        <el-button @click="musicDialogVisible = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listRemixSong, getRemixSong, delRemixSong, addRemixSong, updateRemixSong, getMusicList } from "@/api/playlist/remix";
import { listTags } from "@/api/playlist/tag";
import { listScene } from "@/api/playlist/scene";

export default {
  name: "RemixSong",
  data() {
    return {
      loading: true,
      showSearch: true,
      total: 0,
      playlistList: [],
      title: "",
      open: false,
      selectedTags: [], // 已选择的标签
      selectedScenes: [], // 已选择的场景
      availableScenes: [], // 可用的场景列表
      musicList: [],
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        shelf: null,
        vip: null,
        musicType: 'mixing'
      },
      form: {},
      rules: {
        musicId: [{ required: true, message: "请选择要混音的音乐", trigger: "change" }],
        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" }],
        imgAddr: [{ required: true, message: "音乐图片不能为空", trigger: "change" }],
        musicScenes: [{ required: true, message: "音乐场景不能为空", trigger: "change" }]
      },
      categoryOptions: [
        { label: '热门', value: '热门' },
        { label: '流行', value: '流行' },
        { label: '摇滚', value: '摇滚' },
        { label: '古典', value: '古典' },
        { label: '爵士', value: '爵士' }
      ],
      tagOptions: [],
      statusOptions: [
        { label: '下架', value: 0 },
        { label: '上架', value: 1 }
      ],
      permissionOptions: [
        { label: '免费', value: 2 },
        { label: 'VIP', value: 1 }
      ],
      selectedMusicInfo: null, // 用于存储选中的音乐信息
      musicDialogVisible: false, // 音乐选择对话框的可见性
      musicLoading: false, // 音乐列表加载状态
      musicTableData: [], // 音乐列表数据
      musicQueryParams: { // 音乐查询参数
        pageNum: 1,
        pageSize: 10,
        name: null,
        author: null
      },
      musicTotal: 0 // 音乐列表总条数
    };
  },
  created() {
    this.getList();
    this.getMusicListData();
  },
  methods: {
    getList() {
      this.loading = true;
      listRemixSong(this.queryParams).then(response => {
        this.playlistList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    getMusicListData() {
      getMusicList({}).then(response => {
        this.musicList = response.rows || [];
      });
    },
    // 获取音乐场景数据
    getScenes(row) {
      if (row.musicScene && row.musicScene.musicScenes && row.musicScene.musicScenes.length > 0) {
        return row.musicScene.musicScenes;
      }
      return [];
    },
    // 获取场景列表
    getSceneList() {
      // 调用场景列表接口
      listScene().then(response => {
        if (response.rows) {
          this.availableScenes = response.rows;
        } else {
          this.availableScenes = [];
        }
      }).catch(error => {
        console.error('获取场景列表失败:', error);
        this.availableScenes = [];
      });
    },
    // 获取标签列表
    getTagList() {
      listTags().then(response => {
        this.tagOptions = response.rows || [];
        // 如果正在编辑，解析已有的标签
        if (this.form.label) {
          this.parseTagsFromString(this.form.label);
        }
      });
    },
    // 处理标签选择变化
    handleTagsChange(value) {
      // 将标签ID数组转换为标签名称数组
      const selectedTagNames = value.map(id => {
        const tag = this.tagOptions.find(item => item.id === id);
        return tag ? tag.name : '';
      }).filter(name => name !== '');

      // 用分号连接并更新表单
      this.form.label = selectedTagNames.join(';');
    },
    // 从字符串解析标签
    parseTagsFromString(tagString) {
      if (!tagString) {
        this.selectedTags = [];
        return;
      }

      const tagNames = tagString.split(';');
      this.selectedTags = this.tagOptions
        .filter(tag => tagNames.includes(tag.name))
        .map(tag => tag.id);
    },
    // 处理场景选择变化
    handleSceneChange(selectedSceneIds) {
      this.selectedScenes = selectedSceneIds;
      // 将选中的场景ID转换为场景名称，用分号分隔
      const selectedSceneNames = selectedSceneIds.map(id => {
        const scene = this.availableScenes.find(scene => scene.sceneId === id);
        return scene ? scene.scene : '';
      }).filter(name => name);
      
      // 设置表单的musicScenes字段用于验证
      this.form.musicScenes = selectedSceneIds.length > 0 ? selectedSceneIds : null;
      
      if (this.form.musicScene) {
        this.form.musicScene.sceneIds = selectedSceneIds.join(',');
        this.form.musicScene.sceneNames = selectedSceneNames.join(';');
      } else {
        this.form.musicScene = {
          sceneIds: selectedSceneIds.join(','),
          sceneNames: selectedSceneNames.join(';')
        };
      }
    },
    // 从字符串解析场景
    parseSceneIdsFromString(sceneIdsString) {
      if (!sceneIdsString) {
        this.selectedScenes = [];
        return;
      }

      // 如果是逗号分隔的ID字符串，直接分割
      if (sceneIdsString.includes(',')) {
        this.selectedScenes = sceneIdsString.split(',');
      } else {
        // 如果是单个ID，转换为数组
        this.selectedScenes = [sceneIdsString];
      }
    },
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        musicId: null,
        name: null,
        author: null,
        vip: 2,
        shelf: 1,
        imgAddr: null,
        musicType: "mixing",
        label: null,
        musicScenes: null
      };
      this.selectedTags = [];
      this.selectedMusicInfo = null;
      this.resetForm("form");
    },
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    handleAdd() {
      this.reset();
      this.getTagList(); // 获取标签列表
      this.getSceneList(); // 获取场景列表
      this.open = true;
      this.title = "新增混音歌曲";
    },
    handleUpdate(row) {
      this.reset();
      this.getTagList(); // 获取标签列表
      this.getSceneList(); // 获取场景列表
      const id = row.musicId || this.ids; // 使用musicId而不是id
      getRemixSong(id).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);
          }
          
          // 回显选择音乐信息
          this.selectedMusicInfo = {
            musicId: this.form.musicId,
            name: this.form.name,
            author: this.form.author
          };
        } else {
          this.$modal.msgError("未找到混音歌曲信息");
          return;
        }

        // 解析已有的标签
        if (this.form.label && this.tagOptions.length > 0) {
          this.parseTagsFromString(this.form.label);
        }

        // 解析已有的场景
        if (this.form.musicScene && this.form.musicScene.sceneIds) {
          this.parseSceneIdsFromString(this.form.musicScene.sceneIds);
          // 设置musicScenes字段用于验证
          this.form.musicScenes = this.selectedScenes.length > 0 ? this.selectedScenes : null;
        }

        this.open = true;
        this.title = "编辑混音歌曲";
        
        // 确保在下一个tick中设置验证字段，因为场景数据可能还在加载中
        this.$nextTick(() => {
          if (this.selectedScenes.length > 0) {
            this.form.musicScenes = this.selectedScenes;
          }
        });
      }).catch(error => {
        this.$modal.msgError("获取混音歌曲信息失败");
        console.error("获取混音歌曲详情失败:", error);
      });
    },
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            // 构建编辑混音歌曲的数据
            const editMixMusicData = {
              id: this.form.id,
              musicId: this.form.musicId,
              sourceMusicId: this.form.musicScene ? this.form.musicScene.sourceMusicId : this.form.musicId,
              sceneIds: this.selectedScenes.join(','),
              sceneJson: JSON.stringify(this.selectedScenes.reduce((acc, sceneId, index) => {
                acc[sceneId] = index + 1;
                return acc;
              }, {})),
              // 添加其他表单字段
              name: this.form.name,
              author: this.form.author,
              vip: this.form.vip,
              shelf: this.form.shelf,
              imgAddr: this.form.imgAddr,
              musicType: this.form.musicType,
              label: this.form.label
            };
            
            updateRemixSong(editMixMusicData).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            // 构建新增混音歌曲的数据
            const mixMusicData = {
              musicId: this.form.musicId,
              sceneIds: this.selectedScenes.join(','),
              sceneJson: JSON.stringify(this.selectedScenes.reduce((acc, sceneId, index) => {
                acc[sceneId] = index + 1;
                return acc;
              }, {})),
              // 添加其他表单字段
              name: this.form.name,
              author: this.form.author,
              vip: this.form.vip,
              shelf: this.form.shelf,
              imgAddr: this.form.imgAddr,
              musicType: this.form.musicType,
              label: this.form.label
            };
            
            addRemixSong(mixMusicData).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 delRemixSong(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    openMusicDialog() {
      this.musicDialogVisible = true;
      this.getMusicList(); // 获取音乐列表
    },
    handleMusicQuery() {
      this.musicQueryParams.pageNum = 1;
      this.getMusicList();
    },
    resetMusicQuery() {
      this.resetForm("musicQueryForm");
      this.handleMusicQuery();
    },
    getMusicList() {
      this.musicLoading = true;
      getMusicList(this.musicQueryParams).then(response => {
        this.musicTableData = response.rows;
        this.musicTotal = response.total;
        this.musicLoading = false;
      }).catch(error => {
        console.error('获取音乐列表失败:', error);
        this.musicLoading = false;
      });
    },
    handleMusicRowClick(row) {
      this.selectMusic(row);
    },
    selectMusic(row) {
      this.form.musicId = row.musicId;
      this.selectedMusicInfo = row; // 更新已选择音乐信息
      this.musicDialogVisible = false; // 关闭音乐选择对话框
    }
  }
};
</script>

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