<template>
  <div class="upload-video">
    <div class="upload-box">
      <input
        class="upload-input"
        ref="chooseFile"
        type="file"
        @change="addFile"
        multiple
        accept=".mp4,.mpeg,.3gp,.avi"
      />
      <i class="iconfont icon-empty"></i>
      <p>点击或将文件拖拽到这里上传</p>
      <p class="gray-font">
        支持格式：mp4，mpeg，3gp，avi，宽高16:9或9:16，&lt;300M
      </p>
      <p class="gray-font">命名格式：推广书籍名称-需求方-文案</p>
    </div>
    <div class="upload-list">
      <div class="list-item" v-for="(item, index) in fileList" :key="index">
        <i class="iconfont icon-paper-clip"></i>
        <p>
          {{ item.name }}
          <i class="iconfont icon-guanbi" @click="deleteItem(index)"></i>
        </p>
      </div>
    </div>
    <p class="gray-font footer-num">已选择：{{ fileList.length }}/10</p>
  </div>
</template>

<script lang="ts">
import { defineComponent, reactive, toRefs, ref, watch, h } from "vue";
import { uploadVideo } from "@/api";
import { message, notification } from "ant-design-vue";
import { LoadingOutlined, CheckOutlined } from "@ant-design/icons-vue";
const UploadVideo = defineComponent({
  components: {},
  props: ["searchForm"],
  setup() {
    const formRef = ref();
    const state = reactive({
      fileList: ref<any[]>([]),
    });
    return { ...toRefs(state) };
  },
  mounted() {
    console.log("SEARCH", this.$props.searchForm);
  },
  methods: {
    // 选择视频后
    async addFile(event: any) {
      event.target.files.forEach((item: any) => {
        this.getVideoMsg(item).then((videoinfo: any) => {
          const { duration, height, width } = videoinfo;
          //获取到视频的时长,高度,宽度
          console.log(duration, height, width);
          // 校验文件是否已存在于fileList
          let flag = true;
          if (this.fileList.length > 0) {
            this.fileList.forEach((itm) => {
              if (itm.name === item.name) flag = false;
            });
          }
          if (!flag) return message.warning("文件已存在");
          // 校验文件尺寸比例大小
          if (this.fileList.length === 10)
            return message.warning("视频数量不能超过10");
          if (Number((item.size / 1024 / 1024).toFixed(2)) > 300)
            return message.warning(`视频：${item.name}大小超过了300M`);
          console.log("宽高", height / width, 16 / 9, 9 / 16);
          // if (
          //   item.height / item.width !== 16 / 9 &&
          //   item.height / item.width !== 9 / 16
          // )
          //   return message.warning(
          //     `视频：${item.name}宽高比例不符合要求比例，请修改后重新上传`
          //   );
          // 正则 /^[\u4E00-\u9FA5A-Za-z0-9]+(-|\/)[\u4E00-\u9FA5A-Za-z0-9]+(-|\/)[\u4E00-\u9FA5A-Za-z0-9]+$/  XX-XX-XX
          if (
            this.checkNumber(item.name) !== 2 &&
            this.checkNumber(item.name) !== 3
          )
            return message.warning(
              `视频：${item.name}不符合命名要求，请修改后重新上传`
            );
          this.fileList.push({
            file: item,
            name: item.name,
            percent: 0,
            materialSize: (item.size / 1024 / 1024).toFixed(2) + "MB",
            type: item.type.split("/")[0],
            duration: duration,
            height: height,
            width: width,
          });
        });
      });
      let inputFile: any = this.$refs.chooseFile;
      inputFile.value = "";
    },
    // 确定上传视频
    async onUploadVideo() {
      if (this.fileList.length === 0) return message.warning("请选择视频");
      this.$emit("close");
      // message.info("素材上传中...");
      const key = "start";
      notification.open({
        key,
        message: "状态提示",
        description: "素材上传中...",
        duration: 0,
        icon: h(LoadingOutlined, { style: "color: #108ee9" }),
      });
      let num = 0;
      if (this.fileList.length === 0) return message.error("请选择视频");
      this.fileList.forEach((item) => {
        let form: any = new FormData();
        form.append("is_public", this.$props.searchForm.is_public);
        form.append("video", item.file); //,item.name
        form.append("duration", item.duration);
        form.append("width", item.width);
        form.append("height", item.height);
        uploadVideo(form)
          .catch((err) => {
            console.log("ERR", err);
          })
          .finally(() => {
            num++;
            console.log(
              "NUM",
              num,
              this.fileList.length,
              num === this.fileList.length
            );
            if (num === this.fileList.length) {
              // message.success("素材上传完成")
              const key2 = "final";
              notification.open({
                key,
                message: "状态提示",
                description: "素材上传完成！",
                duration: 2,
                icon: h(CheckOutlined, { style: "color: greenyellow" }),
              });
            }
            this.$emit("getList");
          });
      });
    },
    // 获取视频宽高时长
    getVideoMsg(file: any) {
      return new Promise((resolve) => {
        let videoElement = document.createElement("video");
        videoElement.src = URL.createObjectURL(file);
        videoElement.addEventListener("loadedmetadata", function () {
          resolve({
            duration: videoElement.duration,
            height: videoElement.videoHeight,
            width: videoElement.videoWidth,
          });
        });
      });
    },
    // 删除item
    deleteItem(index: number) {
      this.fileList.splice(index, 1);
    },
    // 工具函数 返回-出现在字符串中的次数
    checkNumber(str: string) {
      let num = 0;
      str.split("").forEach((item: any) => {
        if (item === "-") {
          num++;
        }
      });
      return num;
    },
    clearList() {
      this.fileList = [];
    },
  },
});

export default UploadVideo;
</script>
<style lang="scss" scoped>
@import "@/assets/common-style/frame.scss";
.upload-video {
  width: 100%;
  padding: 0 10%;
  .gray-font {
    color: gray;
  }
  .upload-box {
    cursor: pointer;
    background: rgb(250, 250, 250);
    border: 2px dashed #39a4ff;
    border-radius: 6px;
    transition: all 0.3s;
    padding-bottom: 10px;
    position: relative;
    i {
      color: rgb(168, 167, 167);
      display: block;
      font-size: 60px;
    }
    i,
    p {
      text-align: center;
      transition: all 0.3s;
      color: #39a4ff;
    }
    // 选择文件
    .upload-input {
      position: absolute;
      display: block;
      width: 100%;
      height: 100%;
      opacity: 0;
      cursor: pointer;
    }
  }
  .upload-box:hover {
    i,
    p {
      color: #0829e6 !important;
    }
    border-color: #0829e6;
  }
  .upload-list {
    overflow: hidden;
    .list-item {
      margin-top: 10px;
      height: 24px;
      .icon-paper-clip {
        width: 14px;
        font-size: 12px;
        float: left;
        padding-top: 3px;
      }
      p {
        float: left;
        width: calc(100% - 14px);
        overflow: hidden;
        .icon-guanbi {
          display: block;
          float: right;
          font-size: 13px;
          cursor: pointer;
          &:hover {
            color: rgb(248, 10, 157);
          }
        }
      }
    }
  }
  .footer-num {
    position: relative;
    top: 56px;
  }
}
</style>
