<template>
    <div class="upload-equipment-svg">
        <el-upload
            class="upload-svg"
            action="#"
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            :before-remove="beforeRemove"
            multiple
            drag
            :file-list="fileList"
            :show-file-list="false"
            :http-request="uploadSvg"
        >
            <div class="el-upload__text">将多个设备图标svg文件拖到此处，或<em>点击上传</em></div>
        </el-upload>
        <div class="file-list">
            <h1>svg文件名:键值</h1>
            <div class="file" v-for="file in fileList" :key="file.name">{{ file.svgName }} : {{ file.key }}</div>
        </div>
    </div>
</template>
<script>
/**
 * 上传设备svg图标页面
 */
import { imgServeUpload } from "@/api/imageservice";
export default {
    name: "icon",
    props: {},
    data() {
        return {
            fileList: [],
        };
    },
    components: {},
    beforeMount() {},
    mounted() {
        window.__svg = this;
    },
    methods: {
        // 上传svg文件
        uploadSvg(resData) {
            const { file } = resData;
            // eslint-disable-next-line @typescript-eslint/no-this-alias
            const that = this;
            const fileReader = new FileReader();
            fileReader.readAsDataURL(file); //读取图片
            // console.log(file);
            const ftype = file.type;
            const fname = file.name;
            const uploadKey = file.uid;
            const imgType = ftype.split(".")[ftype.length - 1];
            fileReader.addEventListener("load", function () {
                // 读取完成
                const res = fileReader.result;
                //将canvas的base64位图片转换成图片png的file
                const blob = that.dataURLtoBlob(res, ftype);
                //将其转换成file对象
                const file = new File([blob], fname, {
                    type: ftype,
                    lastModified: Date.now(),
                }); //blob转file

                // try sending
                const reader = new FileReader();
                const fileType = file.name.split(".");
                const imgType = fileType[fileType.length - 1];
                const CreateTime = that.formatDate(new Date(file.lastModified));
                reader.onloadend = function () {
                    // 这个事件在读取结束后，无论成功或者失败都会触发
                    // eslint-disable-next-line no-empty
                    if (reader.error) {
                    } else {
                        // 构造 XMLHttpRequest 对象，发送文件 Binary 数据
                        const xhr = new XMLHttpRequest();
                        xhr.open("POST", `${imgServeUpload}${uploadKey}.${imgType}`);
                        xhr.send(reader.result);
                        xhr.onreadystatechange = function () {
                            if (xhr.readyState == 4) {
                                if (xhr.status == 200) {
                                    const key = uploadKey + "." + imgType;
                                    console.log(key, fname);
                                    const svgName = fname.split(".svg")[0];
                                    that.fileList.push({ svgName, key });
                                    that.$message.success("上传成功!");
                                }
                            }
                        };
                    }
                };
                reader.readAsArrayBuffer(file);
            });
        },
        dataURLtoBlob(dataURI, type) {
            const binary = atob(dataURI.split(",")[1]);
            const array = [];
            for (let i = 0; i < binary.length; i++) {
                array.push(binary.charCodeAt(i));
            }
            return new Blob([new Uint8Array(array)], { type: type });
        },
        formatDate(now) {
            const year = now.getFullYear();
            const month = now.getMonth() + 1;
            const date = now.getDate();
            const hour = now.getHours();
            const minute = now.getMinutes();
            const second = now.getSeconds();
            return (
                year +
                "-" +
                month +
                "-" +
                (date > 10 ? date : "0" + date) +
                " " +
                hour +
                ":" +
                (minute > 10 ? minute : "0" + minute) +
                ":" +
                (second > 10 ? second : "0" + second)
            );
        },
        handleRemove(file, fileList) {
            console.log(file, fileList);
        },
        handlePreview(file) {
            console.log(file);
        },
        beforeRemove(file, fileList) {
            return this.$confirm(`确定移除 ${file.name}？`);
        },
    },
};
</script>
<style lang='less' scoped>
.upload-equipment-svg {
    width: 100%;
    height: 100%;
    padding: 50px;
    /deep/ .el-upload-dragger {
        display: flex;
        justify-content: center;
        align-items: center;
    }
    .file-list {
        margin-top: 10px;
        user-select: text !important;
        .file {
            user-select: text !important;
        }
    }
}
</style>