<!-- 音乐专辑 详情 -->
<template>
  <div class="app-container">
    <el-form class="form" :model="form" ref="form" :rules="rules" label-width="100px" :disabled="disabled">
      <el-form-item label="专辑名称：" prop="name">
        <el-input v-model="form.name" placeholder="请输入专辑名称" />
      </el-form-item>
      <el-form-item label="专辑介绍" prop="description">
        <el-input v-model="form.description" type="textarea" :autosize="{ minRows: 5, maxRows: 10 }" maxlength="300"
          show-word-limit placeholder="请输入专辑介绍" />
      </el-form-item>
      <el-form-item label="专辑类型：" prop="albumType">
        <el-select v-model="form.albumType" placeholder="请选择专辑类型">
          <el-option v-for="item in albumTypeOptions" :key="item.value" :value="item.value" :label="item.label" />
        </el-select>
      </el-form-item>
      <el-form-item label="资源平台：" prop="platformId">
        <el-select v-model="form.platformId" placeholder="请选择资源平台" :disabled="disabledPlatformId(form.platformId)">
          <el-option v-for="item in platformOptions" :key="item.value" :value="item.value" :label="item.label"
            :disabled="disabledJoinType(item.joinType)" />
        </el-select>
      </el-form-item>
      <el-form-item label="付费类型：" prop="payType">
        <el-select v-model="form.payType" placeholder="请选择付费类型">
          <el-option v-for="item in payTypeOptions" :key="item.value" :value="item.value" :label="item.label" />
        </el-select>
      </el-form-item>
      <el-form-item v-if="form.payType !== 1" label="原价：" prop="price">
        <el-input-number v-model="form.price" placeholder="请输入原价" :min="1" :precision="2" :controls="false" />
      </el-form-item>
      <el-form-item v-if="form.payType !== 1" label="折扣价：" prop="discount">
        <el-input-number v-model="form.discount" placeholder="请输入折扣价" :min="1" :precision="2" :controls="false" />
      </el-form-item>
      <el-form-item label="专辑封面：" prop="coverUrl">
        <Upload listType="picture-card" :url="form.coverUrl" @upload="upload($event, 'coverUrl')"
          :disabled="disabled" />
      </el-form-item>
      <el-form-item label="歌曲列表：" style="width: 100%">
        <el-button type="primary" icon="el-icon-plus" @click="getDialog">添加歌曲</el-button>
        <!-- 列表 -->
        <el-table :data="form.programList" v-loading="form_loading">
          <el-table-column label="ID" prop="id" align="center" />
          <el-table-column label="歌曲名称" prop="name" align="center" show-overflow-tooltip />
          <el-table-column label="歌手名称" prop="singerName" align="center" show-overflow-tooltip />
          <el-table-column label="播放时长" prop="playTime" align="center" />
          <el-table-column label="当前状态" prop="status" align="center" :formatter="statusFormatter" />
          <el-table-column label="序号" align="center">
            <template slot-scope="scope">
              <div v-if="currentEditIndex !== scope.$index">
                <span :style="{ marginRight: (!disabled || !canOrder) ? '0px' : '8px' }">
                  {{ (dialogForm.pageNum - 1) * dialogForm.pageSize + scope.$index + 1 }}
                </span>
                <svg-icon v-if="!disabled || !canOrder" icon-class="edit"
                  @click.native="handleEditClick(scope.row, scope.$index)" />
              </div>
              <el-input v-else v-model="editData.sortIndex" size="mini" style="width:60px;" type="number"
                @blur="onNumberBlur(scope.row, scope.$index)" placeholder="序号" ref="numberInput" />
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center">
            <template slot-scope="scope">
              <Audio :src="scope.row.progaramUrl" />
              <el-button type="delete" :disabled="disabled" @click="getDelete(scope.$index)">删除</el-button>

              <!-- 向上移动 -->
              <el-button type="text" icon="el-icon-caret-top" @click="getChange(true, scope.$index, scope.$index - 1)"
                :disabled="(scope.$index < 1 && !disabled) ||
                  disabledPlatformId(form.platformId)
                  " />

              <!-- 向下移动 -->
              <el-button type="text" icon="el-icon-caret-bottom"
                @click="getChange(false, scope.$index, scope.$index + 1)" :disabled="(scope.$index > form.programList.length - 2 && !disabled) ||
                  disabledPlatformId(form.platformId)
                  " />
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
    </el-form>
    <div class="form-btn">
      <el-button @click="cancel">取消</el-button>
      <el-button v-if="!disabled" type="primary" @click="getSubmit">确定</el-button>
    </div>

    <!-- 弹窗 -->
    <el-dialog :visible.sync="dialogVisible" title="添加歌曲" width="1100px">
      <el-form inline size="mini" style="width: 100%">
        <el-form-item label="歌曲名称：">
          <el-input v-model="dialogForm.name" placeholder="请输入歌曲名称" clearable />
        </el-form-item>
        <el-form-item label="歌手名称：">
          <el-input v-model="dialogForm.singerName" placeholder="请输入歌手名称" clearable />
        </el-form-item>
        <el-form-item label="资源平台：">
          <el-select v-model="dialogForm.platformId" placeholder="请选择资源平台">
            <el-option v-for="item in platformOptions.filter(
              (i) => !i.joinType.includes('1')
            )" :key="item.value" :value="item.value" :label="item.label" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="getSearch">搜索</el-button>
          <el-button icon="el-icon-refresh" @click="getRefresh">重置</el-button>
        </el-form-item>
      </el-form>
      <el-table :data="tableData" ref="multipleTable" :row-key="tableKey" v-loading="loading"
        @selection-change="handleSelectionChange">
        <el-table-column type="selection" align="center" key="selection" reserve-selection />

        <el-table-column label="ID" prop="id" align="center" />
        <el-table-column label="歌曲名称" prop="name" align="center" show-overflow-tooltip />
        <el-table-column label="歌手名称" prop="singerName" align="center" show-overflow-tooltip />
        <el-table-column label="播放时长" prop="playTime" align="center" />
        <!-- <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <el-button
              type="text"
              @click="getChecked(scope.row)"
              :disabled="
                form.programList.findIndex((i) => i.id === scope.row.id) === -1
                  ? false
                  : true
              "
            >
              选择
            </el-button>
          </template>
        </el-table-column> -->
      </el-table>
      <pagination v-show="total > 0" :total="total" :page.sync="dialogForm.pageNum" :limit.sync="dialogForm.pageSize"
        @pagination="getList" />
    </el-dialog>
  </div>
</template>

<script>
import { list } from "@/api/music/list";
import { detail, submit } from "@/api/music/menu";
import Audio from "@/components/Audio/index.vue";
import {
  albumTypeMixin,
  onOrOffMixin,
  payTypeMixin,
  platformMixin,
} from "@/mixin/index";
export default {
  name: "musicAlbumDetail",
  mixins: [platformMixin, onOrOffMixin, payTypeMixin, albumTypeMixin],
  components: {
    Audio,
  },
  data() {
    // 判断原价是否大于折扣价
    var checkPrice = (rule, value, callback) => {
      if (!value) {
        callback(new Error("请输入原价"));
      } else {
        if (this.form.discount && value <= this.form.discount) {
          callback(new Error("原价必须大于折扣价"));
        }
        callback();
      }
    };
    // 判断折扣价是否小于原价
    var checkDiscount = (rule, value, callback) => {
      if (this.form.price && value >= this.form.price) {
        callback(new Error("折扣价必须小于原价"));
      } else {
        callback();
      }
    };
    return {
      // 遮罩层
      form_loading: false,
      loading: false,
      // 表单
      form: {
        programList: [], // 歌曲列表
        status: 1,
        type: 1,
      },
      editData: {},
      currentEditIndex: -1,
      // 校验
      rules: {
        name: [
          {
            required: true,
            message: "请输入歌单名称",
            trigger: "blur",
          },
        ],
        description: [
          {
            required: true,
            message: "请输入歌单介绍",
            trigger: "blur",
          },
        ],
        albumType: [
          {
            required: true,
            message: "请选择专辑类型",
            trigger: "blur",
          },
        ],
        avatarNickName: [
          {
            required: true,
            message: "请输入歌单创建者名称",
            trigger: "blur",
          },
        ],
        platformId: [
          {
            required: true,
            message: "请选择资源平台",
            trigger: "change",
          },
        ],
        payType: [
          {
            required: true,
            message: "请选择付费类型",
            trigger: "change",
          },
        ],
        price: [
          {
            required: true,
            validator: checkPrice,
            trigger: "blur",
          },
        ],
        discount: [
          {
            validator: checkDiscount,
            trigger: "blur",
          },
        ],
        coverUrl: [
          {
            required: true,
            message: "请上传歌单封面",
            trigger: "change",
          },
        ],
        avatarNickHead: [
          {
            required: true,
            message: "请上传创建者头像",
            trigger: "change",
          },
        ],
      },
      // 弹窗
      dialogVisible: false,
      // 弹窗表单
      dialogForm: {
        pageNum: 1,
        pageSize: 10,
        status: 1,
        platformId: null,
      },
      // 总数据
      total: 0,
      // 弹窗列表
      tableData: [],
      // 只读
      disabled: false,
      // 是否已选
      disabledChecked: false,
      ///被选中数据是否加载完
      isLoad: false,
      ///是否可以调整顺序
      canOrder: true,
    };
  },
  mounted() {
    // 获取资源平台
    this.getPlatform({
      audioType: 15,
    });
    if (this.$route.query.id) {
      this.form.id = this.$route.query.id;
      this.disabled = Boolean(this.$route.query.disabled);
      this.getDetail();
    }
  },
  methods: {
    tableKey(row) {
      return row.id;
    },
    // 输入框失去焦点时隐藏
    onNumberBlur(row, index) {

      let newValue = Number(this.editData.sortIndex);
      const maxLen = this.form.programList.length;

      if (isNaN(newValue) || newValue === null || newValue === undefined) {
        console.log('序号未修改:', newValue);
        return;
      }
      if (newValue < 1) {
        this.$message.warning('序号必须大于0');
        this.currentEditIndex = -1;

        return;
      }
      if (newValue > maxLen) {
        // 超出就是最后一位
        newValue = maxLen
      }

      if (newValue === -1 || newValue === '') {
        // 新值为空时处理
        this.currentEditIndex = -1;
        console.log('序号未修改:', newValue);
        return
      }
      console.log('序号修改:', newValue, '当前索引:', index, this.currentEditIndex);

      // 计算目标下标
      const targetIndex = newValue - 1;
      if (targetIndex === index) {
        // this.currentEditIndex = -1;
        return;
      }
      // 交换两个元素
      // ...existing code...
      // 插入到目标位置，原本序号顺延
      const movingItem = this.form.programList.splice(index, 1)[0];
      this.form.programList.splice(targetIndex, 0, movingItem);
      // ...existing code...
      this.currentEditIndex = -1;
      this.$message.success("操作成功！");


    },
    // 点击编辑图标显示输入框
    handleEditClick(row, index) {
      if (this.disabled || !this.canOrder) {
        return;
      }
      this.editData = {
        sortIndex: row.index,
      };
      this.currentEditIndex = index;
      this.$nextTick(() => {
        this.$refs.numberInput.focus();
      });

    },
    handleSelectionChange(val) {
      if (this.isLoad) {
        if (this.form.programList.length == 0) {
          this.form.programList = JSON.parse(JSON.stringify(val));
        } else {
          ///查找dialogTableData里面有的
          var tempDialogHas = [];
          for (var i = 0; i < this.tableData.length; i++) {
            for (var j = 0; j < val.length; j++) {
              if (this.tableData[i].id === val[j].id) {
                tempDialogHas.push(this.tableData[i]);
                break;
              }
            }
          }

          ///查找dialogTableData里面没有的
          var tempDialogNot = [];
          if (tempDialogHas.length == 0) {
            tempDialogNot = JSON.parse(JSON.stringify(this.tableData));
          } else {
            for (var i = 0; i < this.tableData.length; i++) {
              var has = false;
              for (var j = 0; j < tempDialogHas.length; j++) {
                if (this.tableData[i].id === tempDialogHas[j].id) {
                  has = true;
                  break;
                }
              }
              if (!has) {
                tempDialogNot.push(this.tableData[i]);
              }
            }
          }

          ///减少val没有的
          if (tempDialogNot.length > 0) {
            for (var i = 0; i < tempDialogNot.length; i++) {
              for (var j = 0; j < this.form.programList.length; j++) {
                if (tempDialogNot[i].id === this.form.programList[j].id) {
                  this.form.programList.splice(j, 1);
                  break;
                }
              }
            }
          }

          ///添加adminPodCastProgramDetailResp没有的
          for (var i = 0; i < val.length; i++) {
            var isHas = false;
            for (var j = 0; j < this.form.programList.length; j++) {
              if (val[i].id === this.form.programList[j].id) {
                isHas = true;
                break;
              }
            }
            if (!isHas) {
              this.form.programList.push(val[i]);
            }
          }
        }
        this.form.programList = this.form.programList.filter((i) => i);
        this.$message.success("操作成功！");
      }
    },

    //是否展示排序
    // isShowSort() {
    //   if (this.form) {
    //     if (!disabledPlatformId(form.platformId)) {
    //       return ture;
    //     }
    //   }
    //   return false;
    // },

    // 排序
    getChange(top, index, laterIndex) {
      var row = this.form.programList[index];
      var laterRow = this.form.programList[laterIndex];
      if (top) {
        this.form.programList[index] = laterRow;
        this.form.programList[laterIndex] = row;
      } else {
        this.form.programList[laterIndex] = row;
        this.form.programList[index] = laterRow;
      }
      this.form.programList = this.form.programList.filter((i) => i);
    },

    // 详情
    getDetail() {
      this.form_loading = true;
      detail(this.form.id).then((res) => {
        if (res.code === 0) {
          this.form = res.data;
          ///qq音乐和喜马拉雅
          if (this.form.platformId == 6 || this.form.platformId == 12) {
            this.canOrder = false;
          }
          this.form_loading = false;
        }
      });
    },

    // 上传
    upload(e, key) {
      this.form[key] = e.file;
    },

    // 添加歌曲
    getDialog() {
      this.dialogVisible = true;
      this.dialogForm.platformId = this.platformOptions.filter(
        (i) => !i.joinType.includes("1")
      )[0].value;
      this.getList();
    },

    // 列表
    getList() {
      this.loading = true;
      list(this.dialogForm).then((res) => {
        if (res.code === 0) {
          this.tableData = res.data.records;
          this.total = res.data.total;
          this.loading = false;

          this.isLoad = false;
          this.$refs.multipleTable.clearSelection();
          if (this.form.programList.length > 0) {
            var temp = [];
            for (var i = 0; i < this.tableData.length; i++) {
              for (var j = 0; j < this.form.programList.length; j++) {
                if (this.form.programList[j].id === this.tableData[i].id) {
                  temp.push(this.tableData[i]);
                  break;
                }
              }
            }

            if (temp.length > 0) {
              temp.forEach((item) => {
                this.$refs.multipleTable.toggleRowSelection(item, true);
              });
            }
          }
          this.isLoad = true;
        }
      });
    },

    // 搜索
    getSearch() {
      this.dialogForm.pageNum = 1;
      this.getList();
    },

    // 重置
    getRefresh() {
      this.dialogForm = {
        pageNum: 1,
        pageSize: 10,
        status: 1,
        platformId: this.platformOptions[0].value,
      };
      this.getList();
    },

    // 选择
    getChecked(row) {
      this.form.programList.push({
        id: row.id,
        name: row.name,
        singerName: row.singerName,
        playTime: row.playTime,
        status: row.status,
        progaramUrl: row.progaramUrl,
      });
      this.$message.success("添加成功！");
    },

    // 删除已选歌曲
    getDelete(index) {
      this.form.programList.splice(index, 1);
    },

    // 确定
    getSubmit() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          if (this.form.programList) {
            let arr = [];
            this.form.programList.map((i) => {
              arr.push(i.id);
            });
            this.form.programList = arr;
          }
          this.form_loading = true;
          let title = this.form.id ? "编辑成功！" : "新增成功！";
          submit(this.form).then((res) => {
            if (res.code === 0) {
              this.$message.success(title);
              this.cancel();
            }
            // if (res.code === 0) {
            //   this.$message.success(`${title}`);
            //   if (!this.form.id) {
            //     this.cancel();
            //   } else {
            //     this.getDetail();
            //   }
            // }
          });
        } else {
          return false;
        }
      });
    },

    // 取消
    cancel() {
      this.$tab.closeOpenPage("/music/musicAlbum");
    },

    // 字典翻译
    statusFormatter(row) {
      return this.selectDictLabel(this.onOrOffOptions, row.status);
    },
  },
};
</script>

<style lang="scss" scoped>
.form {
  .el-form-item {
    width: 500px;
  }
}
</style>
