<template>
        <div id="sagaUploads">
            <div class="saga-upload-images">
                <div v-if="type != 'video'" class="point-view" v-for="(item,index) in imagesArr">
                    <div class="point-image">
                        <i v-if="!readOnly" class="el-icon-delete" @click="delImage(index,item)"></i>
                        <img @click="lookImg" :src="imageGetUrl + '&key=' +item.key" alt>
                    </div>
                    <p v-if="readOnly">{{ item.name }}</p>
                    <form-input v-else :label="''" @change="getName" :keys="index" :value="item.name" :width="10"></form-input>
                </div>
                <div v-if="type == 'video'" class="point-view" v-for="(item,index) in imagesArr">
                    <div class="point-image">
                        <i v-if="!readOnly" class="el-icon-delete" @click="delImage(index,item)"></i>
                        <video
                            width="100%"
                            height="100%;"
                            :src="imageGetUrl + '&key=' +item.key"
                            controls="controls"
                        >您的浏览器不支持 video 标签。
                        </video>
                    </div>
                    <p v-if="readOnly">{{ item.name }}</p>
                    <form-input v-else :label="''" @change="getName" :keys="index" :value="item.name"
                                :width="10"></form-input>
                </div>
                <div v-if="!readOnly" style="float:left;">
                    <el-upload
                        class="avatar-uploader"
                        :http-request="uploadAndSubmit"
                        :show-file-list="false"
                        :accept="accept"
                        action
                        drag
                        style="position: relative"
                    >
                        <i class="el-icon-plus avatar-uploader-icon"></i>
                    </el-upload>
                    <video style="display:none;" id="video" controls/>
                </div>
            </div>
            <details-dialog :title="'图片'" :iframeSrc="iframeSrc" :dialog="dialog" :setData="imagesArr"></details-dialog>
        </div>
    </template>


<script lang="ts">
import { Component, Prop, Vue, Watch } from "vue-property-decorator";
import tools from "@/utils/maintain";

@Component({
    name: 'uploadFiles'
})
export default class extends Vue {
    @Prop({ default: Array }) keysArr?: [] | undefined
    @Prop({ default: Boolean }) readOnly?: boolean
    @Prop({ default: Number }) isShow?: number
    @Prop() contextKey?: {} | ''
    @Prop() defined: null
    @Prop({ default: 'image/*' }) accept: null
    @Prop({ default: 'image' }) type: null
    @Prop({ default: Array }) videoPicArr?: []


    filesArr = [];
    baseUrl = "";
    imageGetUrl = "/image-service/common/image_get?systemId=dataPlatform";
    imageUploadUrl = "/image-service/common/image_upload?systemId=dataPlatform&secret=9e0891a7a8c8e885&overwrite=true";
    imagesArr = [];

    created() {
        this.imageFlag()
    }

    getName(name, index) {
        this.imagesArr[index].name = name
        if (this.isShow === 1) {
            let oFile = {}
            oFile[this.contextKey] = this.imagesArr
            this.$emit("change", oFile, this.defined, this.videoPicArr);

        } else {
            this.$emit("change", this.imagesArr, this.defined, this.videoPicArr);

        }
    }

    //判断是否为空
    imageFlag() {
        let type = typeof this.keysArr;
        if (type == "string") {
            this.imagesArr = [this.keysArr];
        } else {
            this.imagesArr = tools.copyArr(this.keysArr);
        }

        if (!this.keysArr) {
            this.imagesArr = [];
        }
    }

    //查看图片
    lookImg() {
        console.log(1)
        // this.dialog.details = true
        // this.iframeSrc = process.env.BASE_URL + ":8890/photo-View.html"
    }

    //删除图片
    delImage(i, key) {
        if (this.type == "video") {
            this.videoPicArr = this.videoPicArr.map(item => {
                if (item.key.substring(0, item.length - 3) == this.imagesArr[i].key.substring(0, this.imagesArr[i].length - 3)) {
                    return undefined
                } else {
                    return item
                }
            }).filter(p => p)
        }
        this.imagesArr.splice(i, 1);
        this.$emit("change", this.imagesArr, this.defined, this.videoPicArr);
    }

    //上传
    uploadAndSubmit(item, key) {
        // let form = document.forms["demoForm"];

        // if (form["file"].files.length > 0) {
        // 寻找表单域中的 <input type="file" ... /> 标签
        // let file = form["file"].files[0];

        let file = item.file;
        // try sending
        let reader = new FileReader();

        let vm = this;

        let fileType = file.name.split(".");
        let type = fileType[fileType.length - 1];
        let CreateTime = tools.formatDate(new Date(file.lastModified))

        let uploadKey = file.uid
        if (!!key) {
            uploadKey = key
        }

        reader.onloadstart = function () {
            // 这个事件在读取开始时触发
        };
        reader.onprogress = function (p) {
            // 这个事件在读取进行中定时触发
        };

        reader.onload = function () {
            // 这个事件在读取成功结束后触发
        };
        reader.onloadend = function () {
            // 这个事件在读取结束后，无论成功或者失败都会触发
            if (reader.error) {
            } else {
                // document.getElementById("bytesRead").textContent = file.size;
                // 构造 XMLHttpRequest 对象，发送文件 Binary 数据
                let xhr = new XMLHttpRequest();
                xhr.open(
                    /* method */
                    "POST",
                    /* target url */
                    vm.imageUploadUrl + "&key=" + uploadKey + "." + type
                    /*, async, default to true */
                );
                //xhr.overrideMimeType("application/octet-stream");
                xhr.send(reader.result);
                xhr.onreadystatechange = function () {
                    if (xhr.readyState == 4) {
                        if (xhr.status == 200) {
                            if (vm.type == 'image') {
                                vm.imagesArr.push({
                                    name: uploadKey + '',
                                    key: uploadKey + "." + type,
                                    systemId: "dataPlatform",
                                    type: "image",
                                    createTime: CreateTime
                                });
                            }
                            if (type == 'mp4') {
                                vm.imagesArr.push({
                                    name: uploadKey + '',
                                    key: uploadKey + "." + type,
                                    systemId: "dataPlatform",
                                    type: "video",
                                    createTime: CreateTime
                                });
                                vm.creatImg(vm.imageGetUrl + "&key=" + uploadKey + "." + type, uploadKey)
                            }
                            if (vm.type == "video" && type == "png") {
                                vm.videoPicArr.push({
                                    name: uploadKey + '',
                                    key: uploadKey + "." + type,
                                    systemId: "dataPlatform",
                                    type: "image_video",
                                    createTime: CreateTime
                                })
                            }
                            if (vm.isShow === 1) {
                                let oFile = {}
                                oFile[vm.contextKey] = vm.imagesArr
                                vm.$emit("change", oFile, vm.defined, vm.videoPicArr);
                            } else {
                                vm.$emit("change", vm.imagesArr, vm.defined, vm.videoPicArr);

                            }
                        }
                    }
                };
            }
        };
        reader.readAsArrayBuffer(file);
    }

    dataURLtoBlob(dataURI, type) {
        let binary = atob(dataURI.split(',')[1]);
        let array = [];
        for (let i = 0; i < binary.length; i++) {
            array.push(binary.charCodeAt(i));
        }
        return new Blob([new Uint8Array(array)], { type: type });
    }

    creatImg(reader, key) {
        let videoDom = document.getElementById('video');
        videoDom.src = reader;
        let vm = this
        videoDom.onloadeddata = function () {
            // 这里可以打印视频时长
            // 这里取得视频封面
            let canvas = document.createElement('canvas');
            canvas.width = 300;
            canvas.height = 300 * this.videoHeight / this.videoWidth;
            canvas.getContext('2d').drawImage(this, 0, 0, canvas.width, canvas.height);
            //将canvas的base64位图片转换成图片png的file
            let blob = vm.dataURLtoBlob(canvas.toDataURL('image/png'), "image/png")
            //将其转换成file对象
            let file = new File([blob], "video_image.png", { type: "image/png", lastModified: Date.now() })//blob转file
            vm.uploadAndSubmit({ file: file }, key)
        }
    }

    @Watch('keysArr', { immediate: true, deep: true })
    handleKeysArr() {
        this.imageFlag()
    }
}
</script>

<style scoped>

</style>
