<template>
  <div class="base_form">
    <div class="label">
      <img class="pre-tag" src="../../../assets/images/template/pre-tag.png" />
      <div class="label-text">{{ property.label }}</div>
    </div>
    <div>
      <div class="upload" @click="upFile">
        <i class="iconfont iconsheyingjiluxiang"></i>&nbsp;&nbsp;上传视频
      </div>
      <ul class="list">
        <li v-for="(item, index) in locaVideos" :key="index">
          <div class="video-file" @click="play(item)">
            <div class="svgbox">
              <i class="iconfont iconshipinwenjian"></i>
            </div>
            {{ item.name }}
          </div>
          <Progress
            class="left"
            :item="item"
            @termination="termination(index)"
          ></Progress>
        </li>
      </ul>
    </div>
    <input
      type="file"
      hidden
      ref="inputDom"
      accept="video/mp4"
      @change="fileChange"
    />
    <!-- 视频预览 -->
    <common-dialog v-if="showVideo" @closePopup="showVideo = false" showMask>
      <div>
        <video controls="controls" style="outline: none" :src="Vurl"></video>
      </div>
    </common-dialog>
  </div>
</template>

<script>
// 进度条组件
import { getLoginCode } from "@/plugins/storage";
import Progress from "../Progress.vue";
import { GO_URLS } from "@/config/URLS";
import CommonDialog from "@/components/CommonDialog.vue";
let xhr;
export default {
  data() {
    return {
      hashList: [], // 用于存证的hash
      locaVideos: [], // 本地展示用
      Speed: { Result: "上传中", num: 0 },
      isFlag: true,
      showVideo: false,
      Vurl: "",
    };
  },
  props: ["property"],
  components: {
    //组件
    Progress,
    CommonDialog,
  },
  watch: {
    hashList: {
      handler(newV, oldV) {
        this.property.value = newV;
      },
      deep: true,
    },
  },
  created() {
    // 数据回显
    if (Array.isArray(this.property.value)) {
      this.property.value = this.property.value.filter(
        (item) => item.value !== ""
      );
    }
    if (this.property.value.length > 0 && this.isFlag) {
      this.isFlag = false;
      let hashes = [];
      for (let index = 0; index < this.property.value.length; index++) {
        const element = this.property.value[index];
        if (element.value) {
          hashes.push(element.value);
        }
      }
      if (hashes.length === this.property.value.length) {
        this.getVideos(hashes);
      }
    }
  },

  methods: {
    play(item) {
      this.showVideo = true;
      this.Vurl = item.url;
    },
    // 获取已有数据
    async getVideos(hashes) {
      let res = await this.$ajax({
        type: "post",
        params: { hashes },
        url: GO_URLS.getFiles,
      });
      if (res) {
        this.locaVideos = [];
        this.hashList = [];
        for (let index = 0; index < res.data.files.length; index++) {
          const element = res.data.files[index];

          this.locaVideos.push({
            name: element.name,
            state: "上传成功",
            speed: 100,
            url: element.url,
          });
          this.hashList.push(element.hash);
        }
      }
    },
    // 删除当前视频||终止上传
    termination(index) {
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          if (xhr) {
            xhr.abort();
          }
          this.hashList.splice(index, 1);
          this.locaVideos.splice(index, 1);
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    //
    upFile() {
      this.$refs.inputDom.click();
    },
    // 视频上传
    fileChange(e) {
      const file = e.target.files[0];
      e.target.value = null; //清空值
      if (!file) return;
      // 限制相同文件的上传
      const state = this.locaVideos.some((item) => item.name === file.name);
      if (state) {
        this.$message({
          message: "不可重复上传该视频文件",
          type: "warning",
        });
        return;
      }
      if (file.type && file.type.indexOf("video/") >= 0) {
        //限制文件大小
        if (file.size > 20971520) {
          this.$message({
            message: "上传视频大小不可超过20M",
            type: "warning",
          });
          return;
        }
        this.UpladFile(file);
      } else {
        this.$message({
          message: "请上传视频文件",
          type: "warning",
        });
      }
    },
    // 请求拆分
    UpladFile(file) {
      const formData = new FormData();
      formData.append("file_data", file);
      var url = "";
      url = GO_URLS.upload + `?file_type=mp4`;
      xhr = new XMLHttpRequest();
      xhr.open("post", url, true);
      //设置请求头参数
      let token = "Bearer " + getLoginCode();
      xhr.setRequestHeader("Authorization", token);
      xhr.onload = this.uploadComplete; //请求完成、
      xhr.onerror = this.uploadFailed; //请求失败
      var that = this; // 防止xhr改变this指向
      xhr.upload.onprogress = function (event) {
        if (event.lengthComputable) {
          //  上传相同文件会进入这里
          const state = that.locaVideos.some((item) => item.name === file.name);
          if (state) {
            // 存在
            for (let index = 0; index < that.locaVideos.length; index++) {
              if (that.locaVideos[index].name === file.name) {
                that.locaVideos[index].speed =
                  (event.loaded / event.total) * 100;
              }
            }
            return;
          }

          that.locaVideos.push({
            name: file.name,
            state: "上传中",
            speed: (event.loaded / event.total) * 100,
          });
        }
      };

      xhr.send(formData);
    },
    // 请求完成
    uploadComplete(xhr) {
      //服务断接收完文件返回的结果
      this.hashList.push(JSON.parse(xhr.target.response).data.hash);
      this.$message({
        type: "success",
        message: "上传成功!",
      });
      this.locaVideos[this.locaVideos.length - 1].url = JSON.parse(
        xhr.target.response
      ).data.url;
    },
    // 失败回调
    uploadFailed(xhr) {
      //上传失败
    },
  },
};
</script>
<style lang="less" scoped>
.base_form {
  flex-shrink: 0;
  padding-left: 18px;
  font-size: 0;
  padding-top: 10px;
  padding-bottom: 10px;
  display: flex;
  justify-content: flex-start;
}
.label {
  display: inline-block;
  width: 150px;
  flex-shrink: 0;
  cursor: pointer;
  color: #797d84;
  line-height: 44px;
  font-size: 14px;
  font-weight: 300;
  position: relative;
}
.pre-tag {
  position: absolute;
  left: -30px;
  top: 14px;
  display: none;
}
.label-text {
  text-overflow: ellipsis;
  white-space: nowrap;
  overflow: hidden;
}
.upload {
  width: 151px;
  background: #f6f6f7;
  border-radius: 4px;
  border: 1px solid #dcdfe6;
  color: rgba(121, 125, 132, 1);
  line-height: 36px;
  text-align: center;
  font-size: 12px;
  cursor: pointer;
  i {
    vertical-align: bottom;
    color: #353535;
  }
}
.video-file {
  font-size: 14px;
  float: left;
  width: 380px;
  overflow: hidden; //超出的文本隐藏
  text-overflow: ellipsis; //溢出用省略号显示
  white-space: nowrap; //溢出不换行
  cursor: pointer;
}
video {
  max-height: 500px;
}
.svgbox {
  // font-size: 22px;
  margin-right: 6px;
  float: left;
  color: rgba(51, 112, 255);
}
.list {
  margin: 0;
  margin-top: 20px;
  padding: 0;
  li {
    line-height: 40px;
    width: 800px;
    overflow: hidden;
  }
}
.left {
  float: right;
}
</style>
