<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="name">
        <el-input
          v-model="queryParams.name"
          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"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['content:category:add']"
        >新增</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="categoryList" @selection-change="handleSelectionChange" style="width: 100%">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="分类ID" align="center" prop="categoryId" min-width="120" />
      <el-table-column label="分类名称" align="center" prop="name" min-width="150" />
      <el-table-column label="分类图片" align="center" prop="backImg" min-width="120">
        <template slot-scope="scope">
          <el-image 
            style="width: 50px; height: 50px"
            :src="getImageUrlMethod(scope.row.backImg)" 
            :preview-src-list="[getImageUrlMethod(scope.row.backImg)]"
            fit="cover">
          </el-image>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" min-width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" min-width="200">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-link"
            @click="handleBindMusic(scope.row)"
            v-hasPermi="['content:category:bind']"
          >绑定音乐</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['content:category:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['content:category: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="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="分类名称" prop="name" required>
          <el-input v-model="form.name" placeholder="请输入分类名称" />
        </el-form-item>
        <el-form-item label="分类图片" required>
          <el-upload
            action=""
            :auto-upload="false"
            :show-file-list="false"
            :on-change="handleImageChange"
            :before-upload="beforeImageUpload"
            class="avatar-uploader"
          >
            <img v-if="form.previewUrl" :src="form.previewUrl" class="avatar">
            <img v-else-if="form.backImg" :src="getImageUrlMethod(form.backImg)" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </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="bindMusicOpen" width="800px" append-to-body>
      <el-table 
        ref="musicTable"
        v-loading="musicLoading" 
        :data="musicList" 
        @selection-change="handleMusicSelectionChange"
        height="400"
      >
        <el-table-column type="selection" width="55" align="center" />
        <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="musicType" width="100">
          <template slot-scope="scope">
            <el-tag :type="scope.row.musicType === 'ordinary' ? 'primary' : 'success'" size="mini">
              {{ scope.row.musicType === 'ordinary' ? '普通歌曲' : '混音歌曲' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="权限" align="center" prop="vip" width="80">
          <template slot-scope="scope">
            <span>{{ scope.row.vip === 1 ? 'VIP' : '免费' }}</span>
          </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="warning"
              size="mini"
              style="margin-right: 5px;"
            >
              {{ tag }}
            </el-tag>
          </template>
        </el-table-column>
      </el-table>
      
      <pagination
        v-show="musicTotal>0"
        :total="musicTotal"
        :page.sync="musicQueryParams.pageNum"
        :limit.sync="musicQueryParams.pageSize"
        @pagination="handleMusicPagination"
      />
      
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitBindMusic" :loading="bindLoading">确 定</el-button>
        <el-button @click="bindMusicOpen = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listCategory, getCategory, delCategory, addCategory, updateCategory } from "@/api/content/category";
import { listMusic, bindMusicToCategory, getCategoryBoundMusic } from "@/api/content/music";
import { getImageUrl } from "@/utils/image.js";
import request from '@/utils/request';

export default {
  name: "Category",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 分类表格数据
      categoryList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name: [
          { required: true, message: "分类名称不能为空", trigger: "blur" }
        ]
      },
      // 绑定音乐相关
      bindMusicOpen: false,
      musicLoading: false,
      musicList: [],
      musicTotal: 0,
      selectedMusicIds: [],
      boundMusicIds: [], // 已绑定的音乐ID列表
      musicQueryParams: {
        pageNum: 1,
        pageSize: 10,
        musicType: null
      },
      bindLoading: false
    };
  },
  created() {
    this.getList();
  },
  methods: {
    // 获取图片完整URL的方法
    getImageUrlMethod(imagePath) {
      return getImageUrl(imagePath);
    },
    /** 查询分类列表 */
    getList() {
      this.loading = true;
      listCategory(this.queryParams).then(response => {
        this.categoryList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null,
        backImg: null,
        previewUrl: null,
        file: 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
      getCategory(id).then(response => {
        this.form = response.data;
        // 设置图片回显
        if (this.form.backImg) {
          this.form.previewUrl = this.getImageUrlMethod(this.form.backImg);
        }
        this.open = true;
        this.title = "修改分类";
      });
    },
    /** 提交按钮 */
    submitForm() {
      // 手动检查图片字段
      if (!this.form.id) {
        // 新增操作：必须上传图片
        if (!this.form.backImg) {
          this.$message.error('分类图片不能为空');
          return;
        }
      } else {
        // 编辑操作：如果有原图片或新图片都可以
        if (!this.form.backImg) {
          this.$message.error('分类图片不能为空');
          return;
        }
      }
      
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            // 编辑操作：使用backImg字段（上传后的地址）
            updateCategory(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addCategory(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 delCategory(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    // 图片选择处理
    handleImageChange(file) {
      // 保存文件对象用于提交
      this.form.file = file.raw;
      // 创建本地预览URL
      this.form.previewUrl = URL.createObjectURL(file.raw);
      
      // 上传图片到服务器
      this.uploadImage(file.raw);
      
      // 强制更新视图
      this.$forceUpdate();
    },
    // 上传图片到服务器
    uploadImage(file) {
      const formData = new FormData();
      formData.append('file', file);
      
      // 调用上传接口
      request({
        url: '/back/upload/config/file',
        method: 'post',
        data: formData,
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      }).then(response => {
        if (response.code === 200) {
          // 上传成功，保存返回的图片地址
          this.form.backImg = response.data;
          this.$message.success('图片上传成功');
        } else {
          this.$message.error('图片上传失败：' + response.msg);
        }
      }).catch(error => {
        console.error('图片上传失败:', error);
        this.$message.error('图片上传失败');
      });
    },
    // 图片上传前的处理
    beforeImageUpload(file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/gif';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error('上传图片只能是 JPG/PNG/GIF 格式!');
        return false;
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!');
        return false;
      }
      return true;
    },
    // 绑定音乐
    handleBindMusic(row) {
      this.musicQueryParams.categoryId = row.categoryId;
      this.selectedMusicIds = []; // 重置选中的音乐
      this.boundMusicIds = []; // 重置已绑定的音乐ID
      this.getBoundMusic(row.categoryId); // 先获取已绑定的音乐
      this.getMusicList();
      this.bindMusicOpen = true;
    },
    /** 获取分类已绑定的音乐 */
    getBoundMusic(categoryId) {
      getCategoryBoundMusic(categoryId).then(response => {
        // 假设返回的数据结构包含musicId字段
        if (response.data && Array.isArray(response.data)) {
          this.boundMusicIds = response.data.map(item => item.musicId || item.id);
        } else if (response.rows && Array.isArray(response.rows)) {
          this.boundMusicIds = response.rows.map(item => item.musicId || item.id);
        }
      }).catch(() => {
        this.boundMusicIds = [];
      });
    },
    /** 查询音乐列表 */
    getMusicList() {
      this.musicLoading = true;
      listMusic(this.musicQueryParams).then(response => {
        this.musicList = response.rows;
        this.musicTotal = response.total;
        this.musicLoading = false;
        // 在数据加载完成后，设置默认勾选
        this.$nextTick(() => {
          this.setDefaultSelection();
        });
      }).catch(() => {
        this.musicLoading = false;
      });
    },
    /** 设置默认勾选已绑定的音乐 */
    setDefaultSelection() {
      if (this.$refs.musicTable && this.boundMusicIds.length > 0) {
        this.musicList.forEach((row, index) => {
          if (this.boundMusicIds.includes(row.musicId)) {
            this.$refs.musicTable.toggleRowSelection(row, true);
          }
        });
      }
    },
    // 音乐多选框选中数据
    handleMusicSelectionChange(selection) {
      this.selectedMusicIds = selection.map(item => item.musicId);
    },
    /** 提交绑定音乐 */
    submitBindMusic() {
      if (!this.selectedMusicIds || this.selectedMusicIds.length === 0) {
        this.$message.warning('请选择要绑定的音乐');
        return;
      }
      this.bindLoading = true;
      bindMusicToCategory(this.musicQueryParams.categoryId, this.selectedMusicIds).then(response => {
        this.$modal.msgSuccess("音乐绑定成功");
        this.bindMusicOpen = false;
        this.bindLoading = false;
        this.getList(); // 刷新分类列表
      }).catch(() => {
        this.bindLoading = false;
        // 失败时不关闭弹窗，只提示错误
        this.$message.error('绑定失败，请重试');
      });
    },
    /** 音乐分页 */
    handleMusicPagination(val) {
      this.musicQueryParams.pageNum = val.pageNum;
      this.musicQueryParams.pageSize = val.pageSize;
      this.getMusicList();
    }
  }
};
</script>

<style scoped>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
}
.avatar {
  width: 100px;
  height: 100px;
  display: block;
}
</style> 