<template>
    <el-form-item class="image-item" :label="label" :rules="requireRule(required, label)" :prop="prop">
        <el-upload
            action=""
            :fileList="fileList"
            :httpRequest="httpRequest"
            :onChange="handleChange"
            accept="video/mp4, video/ogg, video/flv,video/avi,video/wmv,video/rmvb"
            :onRemove="handleRemove"
            :on-preview="handlePictureCardPreview"
            :before-upload="beforeUpload"
            :class="{'is-disabled': fileList.length >= limit || disabled}"
            listType="picture-card" 
            :multiple="false">
            <i class="el-icon-video-camera" style="font-size:60px;margin-top:40px;"></i>
            <div slot="file" slot-scope="{file}">
                <video class="el-upload-list__item-thumbnail" :src="file.url" alt=""></video>
                <span class="el-upload-list__item-status-label">
                    <i class="el-icon-upload-success el-icon-check"></i>
                </span>
                <span class="el-upload-list__item-actions">
                    <span class="el-upload-list__item-preview" @click="handlePictureCardPreview(file)">
                        <i class="el-icon-video-play"></i>
                    </span>
                    <span class="el-upload-list__item-delete" @click="handleRemove1(file)" v-if="!disabled">
                        <i class="el-icon-delete"></i>
                    </span>
                </span>
            </div>
            <!-- <div slot="file" slot-scope="{file}" v-else>
                <el-progress type="circle" :percentage="percentageNumber" :status="progressstatus" :width="70" :show-text="false" style="left:100px;"></el-progress>
            </div> -->
        </el-upload>
      
        <el-dialog :visible.sync="dialogVisible" :modal="false" style="text-align: center;">
                <video
                :src="dialogImageUrl"
                controls
                autoplay
                class="video"
                width="800"
                height="450"
            ></video>
        </el-dialog>
    </el-form-item>
</template>

<script>
import mixin from './mixin'
import {join} from 'lodash'
import { uploadOSS } from './oss'

// 通过字符串获取文件列表
const extractFiles = value => {
    if (!value || value.trim() === '') {
        return []
    }
    return value.split(',').map(url => ({uid: url, url, status: 'success'}))
}
// 将图片路径合并到一个字符串
const extractUrls = fileList => {
    return join(fileList.map(file => file.url), ',')
}

/**
 * 图片选择组件
 */
export default {
  mixins: [mixin],
  props: {
    limit: {
      type: Number,
      default: 1
    }
  },
  data(){
    return {
      fileList: extractFiles(),
      dialogVisible: false,
      dialogImageUrl: '',
      successFlag:true,
      progressstatus:"",
      percentageNumber:0,
    }
  },
  created(){
      this.$watch(() => this.$parent.model[this.prop], (value, oldValue) => {
          if (value && !oldValue) {
              this.fileList = extractFiles(value)
          }
    }, {immediate: true}) 
  },
  methods: {
        httpRequest({file}){
                const prom =  new Promise((resolve, reject) => {
                    uploadOSS(file,0).then(res => {
                        this.successFlag = 'true'
                    let target = null
                    for (let i = 0; i < this.fileList.length; i++) {
                        const element = this.fileList[i]
                        if (element.uid === file.uid) {
                            target = i
                            break
                        }
                    }
                    if (target === null) {
                        this.$message.warning('文件上传异常')
                        return
                    }
                    if (res){
                        this.fileList[target].url = res
                        setTimeout(() => this.$parent.clearValidate(), 600)
                    } else {
                        this.fileList.splice(target, 1)
                        this.$message.warning('上传失败, 请重新上传')
                    }
                    this.$parent.model[this.prop] = extractUrls(this.fileList)
                    resolve()
                })
            })
                prom.abort = () => {}
                return prom
        },
        beforeUpload(file){
            if (parseInt(file.size) > parseInt('52428800')) {
                this.$message.warning('文件大小不能超过50MB,请重新选择')
            return false
            }
        //   let url = URL.createObjectURL(file);
        //   let audioElement = new Audio(url);
        //   let time = audioElement.duration; 
        //   debugger
          return true
        },
        handleRemove(file, fileList){
            this.fileList = fileList
            this.$parent.model[this.prop] = extractUrls(this.fileList)
            setTimeout(() => this.$parent.validateField(this.prop), 500)
        },
        handleRemove1(file){
            this.fileList.splice(this.fileList.findIndex(e => e.url === file.url), 1)
            this.$parent.model[this.prop] = extractUrls(this.fileList)
            this.successFlag = false
            this.progressstatus=""
            this.percentageNumber=0
            setTimeout(() => this.$parent.validateField(this.prop), 500)
        },
        handleChange(file, fileList) {
            this.fileList = fileList
            setTimeout(() => this.$parent.validateField(this.prop), 500)
        },
        handlePictureCardPreview(file) {
            this.dialogImageUrl = file.url;
            this.dialogVisible = true;
        },
        // slice(file) {
        //     let i = 0;
        //     let start = 0;
        //     const MB = 1024 * 1024;
        //     let fileList=[]
        //     while (true) {
        //         // 这里规定 1MB/片 最后一片 < 1MB
        //         const end = start + MB;
        //         const blob = file.slice(start, end);
        //         fileList.push(blob);

        //         if (blob.size<MB) break;
        //         start = end;
        //     }
        //     return fileList;
        // },
        // async batchUpload(file) {
        //     this.successFlag=false
        //     const slicer = this.slice(file);
        //     let md5= new Date().getTime();
        //     let i=1;
        //     let number = 100/slicer.length;
        //     for(const slice of slicer) {
        //         let res = await uploadTest(slice,file.name,md5,i,slicer.length);
        //         this.percentageNumber = this.percentageNumber+number;
        //         if(res.filePath){
        //             this.progressstatus='success'
        //             return res
        //         }
        //         i++;
        //     }
        // },
    }
}
</script>

<style>
.image-item .is-disabled .el-upload--picture-card{
  display: none !important;
}
.image-item{
    height: 146px;
}
.image-item .el-upload-list__item {
    transition: none !important;
}
</style>
