<template>
    <div>
         <el-upload
            class="uploadImg"
            style="display:none"
            action="#"
            :http-request="uploadFile"
            :before-upload="beforeUpload"
            :show-file-list="false"
            :multiple="multiple"
            :accept="uploadConfig.accept">
        </el-upload>
        <quill-editor
            ref="quillEditor"
            class="editor"
            v-model="content"
            :options="editorOption"
            @blur="onEditorBlur($event)"
            @focus="onEditorFocus($event)"
            @change="onEditorChange($event)"
            @ready="onEditorReady($event)">
        </quill-editor>
    </div>
</template>
<script>
import { quillEditor, Quill } from 'vue-quill-editor'
import store from '@/store/index.js'
import client from '@/assets/oss'
import ossConfig from '@/assets/ossConfig.js'
import { formatDate } from '@/assets/public'
import { Loading } from 'element-ui'
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'

export default {
    name: 'Editor',
    props: {
        value: {
            type: String
        },
        // 是否可以多选图片
        multiple: {
            type: Boolean,
            default: true
        },
        // 文件存储路径 必传
        filePath: {
            type: String,
            default: `${store.state.shcoolCode}/TestUpload`
        },
        ossCof: {
            type: Object,
            default: () => ({
                endpoint: 'oss-cn-shenzhen.aliyuncs.com',
                bucket: 'vschool-solution',
                region: 'oss-cn-shenzhen.aliyuncs.com'
            })
        }
    },
    data () {
        return {
            content: '',
            ossParams: {
                accessKeyId: '',
                accessKeySecret: '',
                stsToken: '',
                endpoint: this.ossCof.endpoint,
                bucket: this.ossCof.bucket,
                region: this.ossCof.region
            },
            uploadConfig: {
                accept: '.jpg,.jpeg,.png,.gif' // 可选 可上传的图片格式
            },
            editorOption: {
                modules: {
                    toolbar: {
                        container: [
                            ['bold', 'italic', 'underline', 'strike'], // 加粗 斜体 下划线 删除线
                            ['blockquote', 'code-block'], // 引用  代码块
                            [{ 'header': 1 }, { 'header': 2 }], // 1、2 级标题
                            [{ 'list': 'ordered' }, { 'list': 'bullet' }], // 有序、无序列表
                            [{ 'script': 'sub' }, { 'script': 'super' }], // 上标/下标
                            [{ 'indent': '-1' }, { 'indent': '+1' }], // 缩进
                            [{ 'direction': 'rtl' }], // 文本方向
                            // [{ 'size': ['small', false, 'large', 'huge'] }],  // 字体大小
                            [{'size': ['10px', '12px', '14px', '16px', '18px', '20px', '22px', '24px', '32px']}],
                            [{ 'header': [1, 2, 3, 4, 5, 6, false] }], // 标题
                            [{ 'font': [] }], // 字体种类
                            [{ 'color': [] }, { 'background': [] }], // 字体颜色、字体背景颜色
                            [{ 'align': [] }], // 对齐方式
                            ['clean'], // 清除文本格式
                            ['link', 'image', 'video'] // 链接、图片、视频
                        ],
                        handlers: {
                            image: value => {
                                if (value) {
                                    document.querySelector('.uploadImg input').click()
                                } else {
                                    this.quill.format('image', false)
                                }
                            }
                        }
                    }
                },
                theme: 'snow'
            }
        }
    },
    components: {
        quillEditor
    },
    methods: {
        onEditorBlur () {},
        onEditorFocus () {},
        onEditorReady () {},
        onEditorChange () {
            this.$emit('getEditorContent', this.content)
        },
        // 上传图片之前先获取sts秘钥
        beforeUpload (files) {
            return new Promise((resolve, reject) => {
                // getAliOssToken 获取OSS秘钥的接口地址
                this.$api.aliOssApi
                    .getToken()
                    .then(res => {
                        let data = res.data
                        if (data.Status) {
                            this.ossParams.accessKeyId = data.Data.AccessKeyId
                            this.ossParams.accessKeySecret = data.Data.AccessKeySecret
                            this.ossParams.stsToken = data.Data.SecurityToken
                            resolve(true)
                        } else {
                            this.$message.warning(data.ResponseError.LongMessage)
                            reject(false)
                        }
                    })
                    .catch(err => {
                        console.log(err)
                        reject(false)
                    })
            })
        },
        /**
         * 获取指定位数的随机数
         * @param {Number} n = [随机数的位数]
         **/
        randomNum (n) {
            var rnd = ''
            for (var i = 0; i < n; i++) {
                rnd += Math.floor(Math.random() * 10)
            }
            return rnd
        },
        // 上传文件
        uploadFile (fileParams) {
            let loadingInstance = null
            let file = fileParams.file,
                point = file.name.lastIndexOf('.'),
                suffix = file.name.substr(point), // 文件后缀名
                fileName = file.name.substr(0, point), // 去掉后缀名的文件名
                fileAliasName = `pc_file_${this.randomNum(10)}`,
                date = formatDate(new Date().getFullYear(), new Date().getMonth() + 1, new Date().getDate()).replace(/\-/g, ''),
                uid = file.uid,
                size = file.size // 单位B
            let storeAs = `${this.filePath}/${date}/${fileAliasName}_${uid}${suffix}`
            // 如果是单文件上传 则在相应的按钮处增加loading和上传进度，如果不是则全局增加loading没有进度
            let options = !this.multiple
                ? {
                    progress: p => {
                        this.mathProgress = Math.floor(p * 100)
                    }
                }
                : {}
            if (this.multiple) {
                loadingInstance = Loading.service({
                    lock: true,
                    text: '努力上传中',
                    spinner: 'el-icon-loading',
                    background: 'rgba(0, 0, 0, 0.7)'
                })
            }
            let ossClient = client(this.ossParams)
            ossClient
                .multipartUpload(storeAs, file, options)
                .then(result => {
                    // 下面是如果对返回结果再进行处理，根据项目需要
                    if (result.res && result.res.status === 200) {
                        let obj = {
                            objectKey: result.name,
                            filename: fileName,
                            filesize: size,
                            filesuffix: suffix,
                            fileUrl: `/${result.name}`
                        }
                        let quill = this.$refs.quillEditor.quill
                        // 获取光标所在位置
                        let index = quill.getSelection().index
                        let imgPath = `${ossConfig.bussinessFileBucket.domain}/${result.name}`
                        // 插入图片  res.info为服务器返回的图片地址
                        quill.insertEmbed(index, 'image', imgPath)
                        // 调整光标到最后
                        quill.setSelection(length + 1)
                    }
                    if (this.multiple) {
                        loadingInstance.close()
                    }
                }).catch(err => {
                    if (this.multiple) {
                        loadingInstance.close()
                    }
                })
        }
    },
    watch: {
        value (newVal, oldVal) {
            this.content = newVal
        }
    }
}
</script>
<style lang="less" scoped>
    @height: 400px;
    /deep/.editor{
        height: @height;
        .ql-container{
            height: calc(@height - 82px);
        }
    }
</style>
