/**
 * @description 文件功能拓展： 增加上传 复制
 */
import {FileQuillWatch} from './FileQuillWatch.js'

export class FileExtend {
    /**
     * @param quill {Quill}富文本实例
     * @param config {Object} options
     * config  keys: action, headers, editForm start end error  size response
     */
    constructor(quill, config = {}) {
        this.id = Math.random()
        this.quill = quill
        this.quill.fileId = this.id
        this.config = config
        this.file = ''  // 要上传的文件
        this.fileURL = ''  // 文件地址
        let quillLoading
        if (this.config.loading) {
            quillLoading = document.querySelector('.quillLoading')
            if (quillLoading === null) {
                quillLoading = document.createElement('div')
                quillLoading.classList.add('quill-loading')
                quillLoading.classList.add('extend-upload-success')
                document.querySelector('.ql-container').appendChild(quillLoading)
            }
        }
        this.quillLoading = quillLoading
        quill.root.addEventListener('paste', this.pasteHandle.bind(this), false)
        quill.root.addEventListener('dropover', function (e) {
            e.preventDefault()
        }, false)
        FileQuillWatch.on(this.id, this)
    }

    /**
     * @description 粘贴
     * @param e
     */
    pasteHandle(e) {
        let clipboardData = e.clipboardData
        let i = 0
        let items, item, types

        if (clipboardData) {
            items = clipboardData.items;

            if (!items) {
                return;
            }
            item = items[0];
            types = clipboardData.types || [];

            for (; i < types.length; i++) {
                if (types[i] === 'Files') {
                    item = items[i];
                    break;
                }
            }
            if (item && item.kind === 'file' && !item.type.match(/^image\//i)) {
                this.file = item.getAsFile()
                let self = this
                // 如果文件限制大小
                if (self.config.size && self.file.size >= self.config.size * 1024 * 1024 && self.config.loading) {
                    self.quillLoading.classList.remove('extend-upload-success')
                    self.quillLoading.classList.add('extend-upload-warning-color')
                    self.quillLoading.innerHTML = '附件大小超过限制'
                    setTimeout(function () {
                        self.quillLoading.classList.remove('extend-upload-warning-color')
                        self.quillLoading.classList.add('extend-upload-success')
                    }, 1500)
                    return
                }
                this.uploadFile()
            }
        }
    }

    /**
     * @description 上传文件到服务器
     */
    uploadFile() {
        const self = this
        let quillLoading = self.quillLoading
        let config = self.config
        // 构造表单
        let formData = new FormData()
        formData.append(config.name, self.file)
        // 自定义修改表单
        if (config.editForm) {
            config.editForm(formData)
        }
        // 创建ajax请求
        let xhr = new XMLHttpRequest()
        xhr.open('post', config.action, true)
        // 如果有设置请求头

        if (config.headers) {
            config.headers(xhr)
        }
        if (config.change) {
            config.change(xhr, formData)
        }

        xhr.onload = function (e) {
            if (self.config.loading) {
                setTimeout(function () {
                    quillLoading.classList.add('extend-upload-success')
                }, 1000)
            }
            if (xhr.status === 200) {
                self.quill.root.innerHTML = self.quill.root.innerHTML.replace('[uploading...]', '')
                let res = JSON.parse(xhr.responseText)
                self.fileURL = config.response(res)
                self.insertFile()
            } else {
                self.quill.root.innerHTML = self.quill.root.innerHTML.replace('[uploading...]', '[upload error]')
            }
        }
        // 开始上传数据
        xhr.upload.onloadstart = function (e) {
            let length = (self.quill.getSelection() || {}).index || self.quill.getLength()
            self.quill.insertText(length, '[uploading...]', { 'color': 'red'}, true)
            if (self.config.loading) {
                quillLoading.classList.remove('extend-upload-success')
            }
            if (config.start) {
                config.start()
            }
        }
        // 上传过程
        xhr.upload.onprogress = function (e) {
            let complete = (e.loaded / e.total * 100 | 0) + '%'
            if (self.config.loading) {
                quillLoading.innerHTML = '已上传' + complete
            }
        }
        // 当发生网络异常的时候会触发，如果上传数据的过程还未结束
        xhr.upload.onerror = function (e) {
            self.quill.root.innerHTML = self.quill.root.innerHTML.replace('[uploading...]', '[upload error]')
            if (self.config.loading) {
                self.quillLoading.classList.add('extend-upload-warning-color')
                quillLoading.innerHTML = '网络异常，失败请重试'
                setTimeout(function () {
                    self.quillLoading.classList.remove('extend-upload-warning-color')
                    quillLoading.classList.add('extend-upload-success')
                }, 1500)
            }
            if (config.error) {
                config.error()
            }
        }
        // 上传数据完成（成功或者失败）时会触发
        xhr.upload.onloadend = function (e) {
            if (config.end) {
                config.end()
            }
        }
        xhr.send(formData)
    }

    /**
     * @description 往富文本编辑器插入图片
     */
    insertFile() {
        const self = this
        self.quill.blur()
        let length = (this.quill.getSelection() || {}).index || this.quill.getLength()
        self.quill.insertEmbed(length, 'link', {href:self.fileURL,innerText:this.file.name})
        self.quill.setSelection(length + 1)
    }
}

Quill.register('modules/FileExtend', FileExtend)