<template>
  <div class="upload-container">
    <el-button
      :style="{ background: color, borderColor: color }"
      icon="el-icon-upload"
      size="mini"
      type="primary"
      @click="uploadClick"
    >
      <!-- upload -->
      上传
    </el-button>
    <el-dialog :visible.sync="dialogVisible" :append-to-body="true">
      <el-upload
        :multiple="true"
        :headers="headers"
        :file-list="fileList"
        :show-file-list="true"
        :on-remove="handleRemove"
        :on-success="handleSuccess"
        :data="dataObj"
        class="editor-slide-upload"
        :action="action"
        list-type="picture-card"
      >
        <el-button size="small" type="primary">
          上传图片
        </el-button>
      </el-upload>
      <!-- action必选参数, 上传的地址 -->
      <el-upload
        class="avatar-uploader el-upload--text"
        :action="action"
        :data="dataObj"
        :headers="headers"
        :show-file-list="false"
        :on-success="handleVideoSuccess"
        :before-upload="beforeUploadVideo"
        :on-progress="uploadVideoProcess"
      >
        <video
          class="video-js"
          v-if="videoUrl != '' && videoFlag == false"
          controls
          autoplay="muted"
          preload="auto"
          poster="../../../assets/logo/microsoft.png">
        >
          <source :src="videoUrl" type="video/mp4" >
        </video>
        <i
          v-else-if="videoUrl == '' && videoFlag == false"
          class="el-icon-plus avatar-uploader-icon"
        >上传视频</i>
        <el-progress
          v-if="videoFlag == true"
          type="circle"
          :percentage="videoUploadPercent"
          style="margin-top: 30px"
        ></el-progress>
      </el-upload>
      <P class="text">请保证视频格式正确，且不超过10M</P>
      <el-button @click="dialogVisible = false">
        <!-- Cancel -->
        取消
      </el-button>
      <el-button type="primary" @click="handleSubmit">
        <!-- Confirm -->
        确认
      </el-button>
    </el-dialog>
  </div>
</template>

<script>
// import { getToken } from 'api/qiniu'
import db from '@/utils/localstorage'
export default {
  name: 'EditorSlideUpload',
  props: {
    color: {
      type: String,
      default: '#1890ff',
    },
  },
  data() {
    return {
      dialogVisible: false,
      listObj: {},
      fileList: [],
      action: `${process.env.VUE_APP_DEV_REQUEST_DOMAIN_PREFIX}/file/upload`,
      list: [],
      headers: {
        Authorization: '',
      },
      dataObj: {
        folderId: 1,
      },
      videoUrl: '',
      videoUploadPercent: 0,
      videoFlag: false,
    }
  },
  created() {
    this.headers.token = 'Bearer ' + db.get('TOKEN', '')
    this.headers.tenant = 'MDAwMA=='
  },
  methods: {
    uploadClick() {
      this.dialogVisible = true
      this.videoUrl = ''
    },
    handleVideoSuccess(response,fileList) {
      if(response.code == 0) {
        this.videoUrl = response.data.url
        this.videoFlag = false;       
      }else{
        this.$message.error('视频上传失败，请重新上传！');
      }
    },
    //验证视频格式和视频大小
    beforeUploadVideo(file) {
      // const isLt10M = file.size / 1024 / 1024  < 10;
      if (['video/mp4', 'video/ogg', 'video/flv','video/avi','video/wmv','video/rmvb'].indexOf(file.type) == -1) {
          this.$message.error('请上传正确的视频格式');
          return false;
      }
      // if (!isLt10M) {
      //     this.$message.error('上传视频大小不能超过10MB哦!');
      //     return false;
      // }
    },
    //上传进度条显示
    uploadVideoProcess(event, file, fileList){
        this.videoFlag = true;
        this.videoUploadPercent = Number(file.percentage.toFixed(0));
    },
    checkAllSuccess() {
      return Object.keys(this.listObj).every(
        (item) => this.listObj[item].hasSuccess
      )
    },
    handleSubmit() {
      // const arr = Object.keys(this.listObj).map(v => this.listObj[v])
      // if (!this.checkAllSuccess()) {
      //   this.$message('Please wait for all images to be uploaded successfully. If there is a network problem, please refresh the page and upload again!')
      //   return
      // }
      // if (!this.list.length) {
      //   this.$message('请上传图片')
      //   return
      // }
      let arr = this.list
      this.$emit('successCBK', arr,this.videoUrl)
      this.listObj = {}
      this.fileList = []
      this.list = []
      this.dialogVisible = false
    },
    handleSuccess(response, file) {
      console.log(response,'response')
      if (response.data.dataType.code == 'IMAGE') {
        this.list.push(response.data.url)
      }
      if (response.data.dataType.code == 'VIDEO') {
        this.videoUrl = response.data.url
      }
      const uid = file.uid
      const objKeyArr = Object.keys(this.listObj)
      for (let i = 0, len = objKeyArr.length; i < len; i++) {
        if (this.listObj[objKeyArr[i]].uid === uid) {
          this.listObj[objKeyArr[i]].url = response.files.file
          this.listObj[objKeyArr[i]].hasSuccess = true
          return
        }
      }
    },
    handleRemove(file) {
      const uid = file.uid
      const objKeyArr = Object.keys(this.listObj)
      for (let i = 0, len = objKeyArr.length; i < len; i++) {
        if (this.listObj[objKeyArr[i]].uid === uid) {
          delete this.listObj[objKeyArr[i]]
          return
        }
      }
    },
    beforeUpload(file) {
      const _self = this
      const _URL = window.URL || window.webkitURL
      const fileName = file.uid
      this.listObj[fileName] = {}
      return new Promise((resolve, reject) => {
        const img = new Image()
        img.src = _URL.createObjectURL(file)
        img.onload = function () {
          _self.listObj[fileName] = {
            hasSuccess: false,
            uid: file.uid,
            width: this.width,
            height: this.height,
          }
        }
        resolve(true)
      })
    },
  },
}
</script>

<style lang="scss" scoped>
.editor-slide-upload {
  margin-bottom: 20px;
  /deep/ .el-upload--picture-card {
    width: 100%;
  }
}
</style>
