<template>
  <div class="brand-video-editor">
    <el-form :model="form" :rules="rules" ref="VideoEditorForm">
      <div class="brand-video-editor__top">
        <div class="video-upload">
          <el-form-item prop="videoUrl" label="上传视频文件:" required>
            <div class="upload-black">
              <!-- action必选参数, 上传的地址 -->
              <el-upload class="avatar-uploader el-upload--text" 
                :action="action" 
                drag
                multiple
                :show-file-list="false" 
                :headers="{
                  'Authorization': 'Bearer ' + token
                }"
                :limit="15"
                :disabled="videoFlag"
                accept="video/*,.mkv"
                :on-success="handleVideoSuccess" 
                :before-upload="beforeUploadVideo" 
                :on-progress="uploadVideoProcess">
                <div class="video-black__warp">
                  <div class="video--black" v-if="videoList.length && !videoFlag">
                    <ul class="video--black_ul">
                      <li class="video--black_item" v-for="acc in videoList" :key="acc.uid">
                        <span class="video--icon"><img src="../../assets/image/file-icon.svg" alt=""></span>
                        <span class="video--title">{{ acc.fileName || '--' }}</span>
                        <span class="video--size">{{ acc.size || '--' }}</span>
                        <el-tooltip
                          class="item"
                          effect="dark"
                          content="删除"
                          placement="bottom-end">
                            <i class="close el-icon-circle-close"
                            @click.stop="imgUploadDel(acc.uid)"></i>
                        </el-tooltip>
                      </li>
                    </ul>
                  </div>
                  <p class="text-black" v-else-if="!videoList.length && !videoFlag">
                    <span class="upload-icon"><img src="../../assets/image/upload-icon.svg" alt=""></span>
                    <span class="_text_">选择文件或者拖拽上传视频</span>
                    <span class="subtext">支持所有视频格式文件，最大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>
      <div class="brand-video-editor__b">
        <div class="type-black__left">
          <div class="type-black__ul">
            <ul>
              <li>
                <el-form-item label="选择剪辑类型:">
                  <div class="type-black__select">
                    <el-select v-model="form.shopConfigId" placeholder="请选择剪辑类型">
                      <el-option
                        v-for="item in shopConfigs"
                        :key="item.id"
                        :label="item.shopName"
                        :value="item.id">
                      </el-option>
                    </el-select>
                  </div>
                </el-form-item>
              </li>
              <li>
                <el-form-item prop="musicConfigId" label="选择现有音乐类型:">
                  <div class="type-black__select">
                    <el-select v-model="form.musicConfigId" 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>
            </ul>
          </div>
        </div>
        <div class="type-black__right">
          <div class="operate-black" style="display: flex;gap: 10vw;">
            <el-form-item prop="type" label="选择渠道:">
              <el-radio-group v-model="form.type" @input="handleType">
                <el-radio :label="0">国内</el-radio>
                <el-radio :label="1">海外</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item prop="processType" label="选择操作类型:">
              <el-radio-group v-model="form.processType">
                <el-radio :label="0">剪辑</el-radio>
                <el-radio :label="1">拼接</el-radio>
              </el-radio-group>
            </el-form-item>
          </div>
          <div class="ratio-black">
            <el-form-item prop="expandScale" label="设置放大倍数:">
              <el-slider v-model="form.expandScale" :min="1" :max="2" show-input :step="0.1" input-size="medium"></el-slider>
            </el-form-item>
          </div>
        </div>
      </div>
      <div class="video-editor-btns">
        <el-button type="primary" :disabled="videoFlag" class="video-editor__a" :loading="comfirmLoading" @click="handleConfirm">处理视频</el-button>
      </div>
    </el-form>
  </div>
</template>

<script>
import { api } from "@/api/api";
import { getToken } from '@/utils/auth'
import { fetchMusicConfigList } from "@/api/musicLibraryManager";
import { shopConfigInfoList } from "@/api/videoCoverManager";
import { addFashionShowVideo } from "@/api/video";
export default {
  name: "BrandVideoEditor",
  components: {
    
  },
  computed: {
    token() {
      return getToken();
    }
  },
  data() {
    return {
      action: api.fileUrl,
      comfirmLoading: false,
      form: {
        shopConfigId: '',
        musicConfigId: '',
        videoUrl: '',
        expandScale: 0,
        processType: 0,
        type: 0 // 平台类型 0:品牌 1:海外
      },
      uploadingCount: 0,
      videoFlag: false,
      videoUploadPercent: 0,
      videoList: [],
      shopConfigs: [],
      musicTypes: [],
      rules: {
        shopConfigId: [
          { required: true, message: "请选择剪辑类型", trigger: "change" }
        ],
        musicConfigId: [
          { required: true, message: "请选择音乐类型", trigger: "change" }
        ],
        videoUrl: [
          { validator: this.checkVideoUrl, trigger: "change" }
        ],
        type: [
          { required: true, message: "请选择渠道", trigger: "change" }
        ],
        processType: [
          { required: true, message: "请选择操作类型", trigger: "change" }
        ],
        expandScale: [
          { required: true, message: "请设置放大倍数", trigger: "change blur" }
        ]
      },
      progressTimer: null
    };
  },
  //页面创建的时候执行
  created() {
    this.getShopConfigs(0);
    this.getMusicCategory();
  },
  methods: {
    checkVideoUrl(rule, value, callback) {
      if (this.videoList.length === 0) {
        callback(new Error('请上传视频文件'));
      } else {
        callback();
      }
    },
    getShopConfigs(type) {
      const params = {
        type
      }
      shopConfigInfoList(params).then(res => {
        if (res.code == 200) {
          this.shopConfigs = res.data.rows;
        }
      });
    },
    getMusicCategory() {
      const params = {
        type: 0
      }
      fetchMusicConfigList(params).then(res => {
        if (res.code == 200) {
          this.musicTypes = res.data.rows;
        }
      });
    },
    handleConfirm() {
      this.$refs.VideoEditorForm.validate(valid => {
        if (valid) {
          const videoUrls = []
          this.videoList.forEach(acc => {
            videoUrls.push(acc.videoUrl)
          })
          // this.form.processType： 0 剪辑 1 拼接
          const list = this.form.processType == 0 ? this.videoList.map(acc => {
            return {
              "shopConfigId": this.form.shopConfigId,
              "musicConfigId": this.form.musicConfigId,
              "videoUrl": [acc.videoUrl],
              "expandScale": this.form.expandScale
            }
          }) : [{
            "shopConfigId": this.form.shopConfigId,
            "musicConfigId": this.form.musicConfigId,
            "videoUrl": videoUrls,
            "expandScale": this.form.expandScale
          }]
          const params = {
            list: list,
            processType: this.form.processType,
            type: this.form.type
          }
          this.comfirmLoading = true;
          addFashionShowVideo(params).then(res =>{
            if(res.code == 200){
              this.$message.success(res.msg || "操作成功");
              const visitedViews = this.$store.state.tagsView.visitedViews;
              const view = visitedViews.filter(acc => acc.name == 'brandVideoEditor')
              if (view.length) {
                this.$store.dispatch("tagsView/delView", view[0]);
              }
              this.$router.push({
                name: "catwalkVideoIndex"
              });
            }
          }).finally(()=>{
            this.comfirmLoading = false;
          })
        } else {
          return false;
        }
      });
    },
    beforeUploadVideo(file) {
      const isLt10M = file.size / 1024 / 1024 < 200;
      const allowedExtensions = ['mp4', 'webm', 'ogg', 'mkv', 'mov', 'avi', 'flv', 'wmv', 'rmvb', 'mpeg', 'm4v'];

      function isVideoFile(file) {
        const typeOk = file.type.startsWith('video/');
        const ext = file.name.split('.').pop().toLowerCase();
        const extOk = allowedExtensions.includes(ext);
        return typeOk || extOk;
      }
      if (!isVideoFile(file)) {
        this.$message.error('请上传正确的视频格式');
        return false;
      }
      if (!isLt10M) {
        this.$message.error('上传文件大小不能超过200MB哦!');
        return false;
      }
      // 启动上传动画（只启动一次）
      if (this.uploadingCount === 0) {
        this.videoFlag = true;
        this.videoUploadPercent = 0;
        this.progressTimer = setInterval(() => {
          if (this.videoUploadPercent < 93) {
            this.videoUploadPercent += 3;
          } else {
            clearInterval(this.progressTimer);
          }
        }, 500);
      }

      this.uploadingCount += 1;

      return true;
    },
    uploadVideoProcess(event, file, fileList) {
      this.videoFlag = true;
      // this.videoUploadPercent = file.percentage;
    },
    handleVideoSuccess(res, file) {
      if (res.code == 200) {
        this.videoList.push({
          fileName: res.data.fileName,
          size: res.data.size,
          videoUrl: res.data.url,
          uid: file.uid
        })
        this.form.videoUrl = res.data.url;
        this.$refs.VideoEditorForm.clearValidate(['videoUrl']);
      } else {
        this.$message.error('上传失败，请重新上传！');
      }
      // 每完成一个，-1
      this.uploadingCount -= 1;

      // 所有文件上传完成，重置 UI 状态
      if (this.uploadingCount === 0) {
        clearInterval(this.progressTimer);
        this.videoFlag = false;
        this.videoUploadPercent = 0;
      }
    },
    imgUploadDel(uid) {
      //删除
      this.$confirm("确定要删除吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        this.videoList.forEach((acc, index) => {
          if (acc.uid == uid) {
            this.videoList.splice(index, 1);
          }
        })
        if (this.videoList.length === 0) {
          this.form.videoUrl = '';
        }
        this.$notify({
          title: "成功",
          message: "删除成功",
          type: "success",
          duration: 3000
        });
      });
    },
    handleType(val) {
      this.form.shopConfigId = '';
      this.getShopConfigs(val);
    }
  }
};
</script>

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

    /deep/ .el-form-item__label {
      color: #232323;
      display: block;
      width: 100%;
      text-align: left;
      font-size: 16px;
      float: none;
    }

    .brand-video-editor__top {
      display: flex;

      .video-upload {
        flex: 1;
        max-width: 100%;
      }

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

        .progress-black {
          width: 100%;
          max-width: 400px;

          .progress--text {
            color: #232323;
          }
        }

        .video--black {
          position: relative;

          .video--black_ul {
            display: flex;
            gap: 50px;
            margin: 0;
            padding: 0;
            flex-wrap: wrap;
          }

          .video--black_item {
            position: relative;
            display: flex;
            flex-direction: column;
            align-items: center;
            width: 110px;
            list-style: none;
          }

          .video--icon {
            width: 80px;

            img {
              display: block;
              max-width: 100%;
            }
          }
          .video--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;
          }
          .video--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: 80px 0;
              border: 2px dashed #d9d9d9;
              border-radius: 10px;
              min-height: 300px;
            }
          }
        }
        .text-black {
          display: flex;
          flex-direction: column;
          align-items: center;
          margin: 0;
          gap: 10px;

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

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

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

            &:hover {
              background: #f8f8f8;
            }
          }
        }
      }
    }
    .brand-video-editor__b {
      display: flex;
      justify-content: space-between;
      gap: 3.6vw;
      align-items: stretch;
      .type-black__left {
        width: 26vw;
        flex: 0 0 26vw;

        ul {
          padding: 0;
          margin: 0;
        }

        li {
          list-style: none;

          /deep/ .el-select {
            width: 100%;
          }
        }
        li + li {
          margin-top: 30px;
        }
      }
      .type-black__right {
        flex: 1;
      }

      /deep/ .el-slider__runway,
      /deep/ .el-slider__bar {
        height: 10px;
      }
      /deep/ .el-slider__runway {
        border-radius: 20px;
      }
      /deep/ .el-slider__bar {
        border-top-left-radius: 20px;
        border-bottom-left-radius: 20px;
      }
      /deep/ .el-slider__button {
        width: 20px;
        height: 20px;
      }
      /deep/ .el-slider__input.el-input-number--medium {
        margin-top: 3px;
      }
    }
    .video-editor-btns {
      display: flex;
      align-items: center;
      justify-content: center;
      margin: 50px 0;

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