<template>
  <div class="base_form">
    <div class="label">
      <Icon iconName="icondd" class="pre-tag" size="18"></Icon>
      <div class="label-text">{{ property.label }}</div>
    </div>
    <div class="flex-grow">
      <div class="upload" @click="upFile">
        <i class="iconfont iconsheyingjiluxiang"></i>&nbsp;&nbsp;上传视频
      </div>
      <ul class="list" v-if="locaVideos.length !== 0">
        <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="true" style="outline: none" :src="Vurl"></video>
      </div>
    </common-dialog>
  </div>
</template>

<script lang="ts">
// 进度条组件
import Progress from "../Progress.vue";
import {
  getLoginCode,
  GO_URLS,
  syCommonDialog as CommonDialog,
} from "cqk-sy-ui";
import { defineComponent, PropType } from "vue";
import { Property } from "../types2";
import { ElMessage, ElMessageBox } from "element-plus";
import Icon from "@/components/Icon/index.vue";
import { $ajax } from "@/service";
let xhr;
export default defineComponent({
  inject: ["showTip"],
  data() {
    return {
      hashList: [] as any[], // 用于存证的hash
      locaVideos: [] as any[], // 本地展示用
      Speed: { Result: "上传中", num: 0 },
      isFlag: true,
      showVideo: false,
      Vurl: "",
    };
  },
  props: {
    property: {
      type: Object as PropType<any>,
      required: true,
    },
    setPropertyValue: {
      type: Function,
      required: true,
    },
  },
  components: {
    //组件
    Progress,
    CommonDialog,
    Icon,
  },
  watch: {
    hashList: {
      handler(newV, oldV) {
        // this.property.value = newV;
        this.setPropertyValue(newV);
      },
      deep: true,
    },
  },
  created() {
    if (Array.isArray(this.property.value)) {
      // this.property.value = this.property.value.filter(
      //   (item) => item.value !== ""
      // );
      this.setPropertyValue(
        this.property.value.filter((item) => item.value !== "")
      );
    }
    if (this.property.value.length > 0 && this.isFlag) {
      this.isFlag = false;
      let hashes = [] as any;
      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 $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 as any).showTip(
        "此操作将永久删除该文件, 是否继续?",
        () => {
          if (xhr) {
            xhr.abort();
          }
          this.hashList.splice(index, 1);
          this.locaVideos.splice(index, 1);
          ElMessage({
            type: "success",
            message: "删除成功!",
          });
        },
        () => {
          ElMessage({
            type: "info",
            message: "已取消删除",
          });
        }
      );
    },
    //
    upFile() {
      (this.$refs as any).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) {
        ElMessage({
          message: "不可重复上传该视频文件",
          type: "warning",
        });
        return;
      }
      if (file.type && file.type.indexOf("video/") >= 0) {
        //限制文件大小
        if (file.size > 20971520) {
          ElMessage({
            message: "上传视频大小不可超过20M",
            type: "warning",
          });
          return;
        }
        this.UpladFile(file);
      } else {
        ElMessage({
          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; //请求失败
      // eslint-disable-next-line @typescript-eslint/no-this-alias
      const 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);
      ElMessage({
        type: "success",
        message: "上传成功!",
      });
      this.locaVideos[this.locaVideos.length - 1].url = JSON.parse(
        xhr.target.response
      ).data.url;
    },
    // 失败回调
    uploadFailed(xhr) {
      //上传失败
    },
  },
});
</script>
<style lang="scss" 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 {
  box-sizing: content-box;
  height: 44px;
  display: inline-block;
  width: 100px;
  flex-shrink: 0;
  cursor: pointer;
  color: #797d84;
  line-height: 44px;
  font-size: 14px;
  font-weight: 300;
  position: relative;
}
.pre-tag {
  position: absolute;
  left: -50px;
  top: 14px;
  display: none;
}
.label-text {
  text-overflow: ellipsis;
  white-space: nowrap;
  overflow: hidden;
}
.upload {
  box-sizing: content-box;
  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 {
  margin-right: 6px;
  float: left;
  color: rgba(51, 112, 255);
}
.list {
  margin: 0;
  margin-top: 20px;
  padding: 0;
  li {
    line-height: 40px;
    overflow: hidden;
  }
}
.left {
  float: right;
}
</style>
