<template>
  <el-dialog :title="(modelType == 'add' ? '添加' : '编辑') + '音乐库'" width="1000px" :visible.sync="dialogVisible">
    <div class="brand-video-editor">
      <el-form :model="form" :rules="rules" ref="MusicLibraryForm">
        <div class="brand-video-editor__top">
          <div class="video-upload">
            <el-form-item prop="musicUrl" label="上传视频/音频文件:" required>
              <div class="upload-black">
                <!-- action必选参数, 上传的地址 -->
                <el-upload class="avatar-uploader el-upload--text" 
                  :action="action" 
                  drag
                  :show-file-list="false" 
                  :headers="{
                    'Authorization': 'Bearer ' + token
                  }"
                  :disabled="videoFlag"
                  accept="video/*,audio/*"
                  :on-success="handleVideoSuccess" 
                  :before-upload="beforeUploadVideo" 
                  :on-progress="uploadVideoProcess">
                  <div class="video-black__warp">
                    <div class="music--black" v-if="form.musicUrl && !videoFlag">
                      <span class="music--icon"><img src="../../assets/image/file-icon.svg" alt=""></span>
                      <span class="music--title">{{ form.fileName || '--' }}</span>
                      <span class="music--size">{{ form.size || '--' }}</span>
                      <el-tooltip
                        class="item"
                        effect="dark"
                        content="删除"
                        placement="bottom-end">
                          <i class="close el-icon-circle-close"
                          @click.stop="imgUploadDel()"></i>
                      </el-tooltip>
                    </div>
                    <p class="text-black" v-else-if="!form.musicUrl && !videoFlag">
                      <span class="upload-icon"><img src="../../assets/image/upload-icon.svg" alt=""></span>
                      <span class="_text_">选择文件或者拖拽上传视频/音频</span>
                      <span class="subtext">支持MP4、MP3文件，最大200MB</span>
                      <a href="javascript:;" class="file-btns">浏览文件</a>
                    </p>
                    <div class="progress-black" v-if="videoFlag">
                      <div class="progress--text">上传中...</div>
                      <el-progress color="#ae8877" :stroke-width="10" :percentage="videoUploadPercent" :show-text="false"></el-progress>
                    </div>
                    
                  </div>
                </el-upload>
              </div>
            </el-form-item>
          </div>
          <div class="type-black">
            <div class="type-black__ul">
              <ul>
                <li>
                  <el-form-item prop="parentId" label="选择现有音乐类型:">
                    <div class="type-black__select">
                      <el-select clearable v-model="form.parentId" placeholder="现有音乐类型">
                        <el-option
                          v-for="item in musicTypes"
                          :key="item.id"
                          :label="item.musicCategoryName"
                          :value="item.id">
                        </el-option>
                      </el-select>
                    </div>
                  </el-form-item>
                </li>
                <li>
                  <el-form-item prop="musicName" label="新增音乐名称:">
                    <div class="type-black__input">
                      <el-input v-model="form.musicName" clearable placeholder="音乐名称"></el-input>
                    </div>
                  </el-form-item>
                </li>
              </ul>
            </div>
          </div>
        </div>
        <div class="music-library-btns">
          <el-button type="primary" :disabled="videoFlag" class="music-library__a" :loading="comfirmLoading" @click="handleConfirm">更新音乐库</el-button>
        </div>
      </el-form>
    </div>
  </el-dialog>
</template>

<script>
import { api } from "@/api/api";
import { getToken } from '@/utils/auth'
import { addMusicConfigInfo, editMusicConfigInfo } from "@/api/musicLibraryManager";
export default {
  name: "MusicLibraryUpdater",
  components: {
    
  },
  computed: {
    token() {
      return getToken();
    }
  },
  data() {
    var checkMusicUrl = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请上传视频/音频文件'));
      } else {
        callback();
      }
    };
    return {
      action: api.fileUrl,
      form: {
        musicName: '',
        musicUrl: '',
        parentId: '',
        fileName: '',
        size: ''
      },
      modelType: 'add',
      dialogVisible: false,
      comfirmLoading: false,
      editId: '',
      videoFlag: false,
      videoUploadPercent: 0,
      musicTypes: [],
      rules: {
        musicName: [
          { required: true, message: "请输入音乐名称", trigger: "blur" }
        ],
        parentId: [
          { required: true, message: "请选择音乐类目", trigger: "change" }
        ],
        musicUrl: [
          { validator: checkMusicUrl, trigger: "change" }
        ]
      },
      progressTimer: null
    };
  },
  watch: {
    dialogVisible(val) {
      if (!val) {
        this.form = {
          musicName: '',
          musicUrl: '',
          parentId: '',
          fileName: '',
          size: ''
        }
        this.modelType =  'add';
        this.comfirmLoading = false;
        this.editId = '';
      }
    }
  },
  methods: {
    show(rows, type, musicOptions) {
      this.dialogVisible = true;
      this.comfirmLoading = false;
      this.modelType = type;
      this.musicTypes = musicOptions;
      if (type == 'edit') {
        this.editId = rows.id;
      }
      this.$nextTick(() => {
        this.form = type == 'edit' ? {
          musicName: rows.musicName,
          musicUrl: rows.musicUrl,
          parentId: rows.parentId,
          fileName: rows.fileName,
          size: rows.size
        } : {
          musicName: '',
          musicUrl: '',
          parentId: '',
          fileName: '',
          size: ''
        }
        this.$refs.MusicLibraryForm.resetFields()
      })
    },
    handleConfirm() {
      this.$refs.MusicLibraryForm.validate(valid => {
        if (valid) {
          this.comfirmLoading = true;
          const params = this.form;
          if (this.modelType == 'add') {
            addMusicConfigInfo(params).then(res =>{
              this.dialogVisible = false;
              if(res.code == 200){
                this.$message.success(res.msg || "操作成功");
                this.$emit("confirm");
              }
            }).finally(()=>{
              this.comfirmLoading = false;
            })
          } else {
            params.id = this.editId;
            editMusicConfigInfo(params).then(res =>{
              this.dialogVisible = false;
              if(res.code == 200){
                this.$message.success(res.msg || "操作成功");
                this.$emit("confirm");
              }
            }).finally(()=>{
              this.comfirmLoading = false;
            })
          }
          
        } else {
          return false;
        }
      });
    },
    beforeUploadVideo(file) {
      const isLt10M = file.size / 1024 / 1024 < 200;
      const allowedTypes = [
        'video/mp4', 'video/ogg', 'video/flv', 'video/avi', 'video/wmv', 'video/rmvb',
        'audio/mp3', 'audio/mpeg', 'audio/wav', 'audio/ogg', 'audio/x-m4a'
      ];
      if (!allowedTypes.includes(file.type)) {
        this.$message.error('请上传正确的视频或音频格式');
        return false;
      }
      if (!isLt10M) {
        this.$message.error('上传文件大小不能超过200MB哦!');
        return false;
      }
      this.progressTimer = setInterval(() => {
        if (this.videoUploadPercent < 93) {
          this.videoUploadPercent += 5;
        } else {
          clearInterval(this.progressTimer);
        }
      }, 200);
    },
    uploadVideoProcess(event, file, fileList) {
      this.videoFlag = true;
      // this.videoUploadPercent = file.percentage;
    },
    handleVideoSuccess(res, file) {
      clearInterval(this.progressTimer);
      this.videoFlag = false;
      this.videoUploadPercent = 0;
      this.$refs.MusicLibraryForm.clearValidate(['musicUrl']);
      if (res.code == 200) {
        this.form.fileName = res.data.fileName;
        this.form.size = res.data.size;
        this.form.musicUrl = res.data.url;
      } else {
        this.$message.error('上传失败，请重新上传！');
      }
    },
    imgUploadDel() {
      //删除
      this.$confirm("确定要删除吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        this.form.musicUrl = '';
        this.form.fileName = '';
        this.form.size = '';
        this.$notify({
          title: "成功",
          message: "删除成功",
          type: "success",
          duration: 3000
        });
      });
    }
  }
};
</script>

<style lang="scss" scoped>
  .brand-video-editor {
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    height: 100%;
    padding: 20px;

    /deep/ .el-form-item__label {
      color: #232323;
    }

    .brand-video-editor__top {
      display: flex;
      justify-content: space-between;
      gap: 3.6vw;
      align-items: stretch;

      .video-upload {
        flex: 1;
        max-width: 700px;
      }

      .video-black__warp {
        width: 100%;
        max-width: 70%;
        display: flex;
        justify-content: center;

        .progress-black {
          width: 100%;
          .progress--text {
            color: #232323;
          }
        }

        .music--black {
          position: relative;
          display: flex;
          flex-direction: column;
          align-items: center;
          width: 110px;

          .music--icon {
            width: 80px;

            img {
              display: block;
              max-width: 100%;
            }
          }
          .music--title {
            font-size: 14px;
            color: #232323;
            font-weight: bold;
            line-height: 1.5;
            margin-top: 10px;
            white-space: nowrap;
            overflow: hidden;
            max-width: 100%;
            text-overflow: ellipsis;
          }
          .music--size {
            font-size: 14px;
            font-weight: bold;
            color: #ae8877;
            line-height: 1.5;
          }
          .close {
            position: absolute;
            top: -20px;
            right: -20px;
            cursor: pointer;
            z-index: 9;
            color: red;
            background-color: #fff;
            font-size: 30px;
            border-radius: 50%;
            outline: none;
            width: 20px;
            height: 20px;
            line-height: 20px;
            font-size: 20px;
            color: #8c939d;
            display: block;
            text-align: center;
          }
        }
      }

      .upload-black {
        width: 100%;

        .avatar-uploader {
          display: block;
          width: 100%;
          height: 100%;

          /deep/ .el-upload {
            border: none;
            width: 100%;
            height: 100%;
            .el-upload-dragger {
              display: flex;
              width: 100%;
              height: 100%;
              justify-content: center;
              align-items: center;
              padding: 50px 0;
              border: 1px dashed #d9d9d9;
              border-radius: 10px;
              min-height: 280px;
            }
          }
        }
        .text-black {
          display: flex;
          flex-direction: column;
          align-items: center;
          margin: 0;
          gap: 10px;

          .upload-icon {
            width: 48px;
            height: 48px;

            img {
              display: block;
              width: 100%;
            }
          }
          ._text_ {
            font-size: 18px;
            color: #292D32;
            line-height: 1.5;
          }
          .subtext {
            font-size: 16px;
            color: #A9ACB4;
            line-height: 1.5;
          }

          a.file-btns {
            display: flex;
            font-size: 16px;
            justify-content: center;
            align-items: center;
            height: 40px;
            border-radius: 4px;
            border: 1px solid #CBD0DC;
            padding: 0 30px;
            color: #54575C;

            &:hover {
              background: #f8f8f8;
            }
          }
        }
      }

      .type-black {
        flex: 1;

        ul {
          padding: 0;
          margin: 0;
        }

        li {
          list-style: none;

          /deep/ .el-select {
            width: 100%;
          }
        }
        li + li {
          margin-top: 30px;
        }
      }
    }
    .music-library-btns {
      display: flex;
      align-items: center;
      justify-content: center;
      margin-top: 50px;

      /deep/ .music-library__a {
        font-size: 16px;
        background: #ae8877;
        color: #fff;
        padding: 15px 80px;
        border-radius: 4px;
      }
    }
  }
</style>
