<template>
    <div class="tinymce-editor">
        <editors v-model="myValue" :init="init" :disabled="disabled" @onClick="onClick" @onChange="onChange"> </editors>
    </div>
</template>

<script>

import Editors from '@tinymce/tinymce-vue'
import tinymce from 'tinymce/tinymce'
import 'tinymce/themes/silver/theme'
import 'tinymce/plugins/image'
import 'tinymce/plugins/link'
import 'tinymce/plugins/media'
import 'tinymce/plugins/table'
import 'tinymce/plugins/lists'
import 'tinymce/plugins/contextmenu'
import 'tinymce/plugins/wordcount'
import 'tinymce/plugins/colorpicker'
import 'tinymce/plugins/textcolor'
import 'tinymce/plugins/fullscreen'
var COS = require('cos-js-sdk-v5')
var cos = new COS({
    SecretId: 'AKIDE6IpMi8fJQRCg1iuWzFajjRs43kbbets',
    SecretKey: 'tXzuwMfplTTK3c9GFUyETilasvQfePu9',
})
export default {
    components: {
        Editors,
    },
    props: {
        value: {
            type: String,
            required: false,
        },
        triggerChange: {
            type: Boolean,
            default: false,
            required: false,
        },
        disabled: {
            type: Boolean,
            default: false,
        },
        plugins: {
            type: [String, Array],
            default: 'paste lists image link media table textcolor wordcount contextmenu fullscreen',
        },
        toolbar: {
            type: [String, Array],
            default: '',
            branding: false,
        },
    },
    data() {
        return {
            //初始化配置
            init: {
                selector: '#tinydemo',
                language_url: '/tinymce/langs/zh_CN.js',
                language: 'zh_CN',
                skin_url: '/tinymce/skins/lightgray',
                height: 300,
                plugins: ['paste'],
                toolbar: this.toolbar,
                branding: true,
                menubar: false,
                toolbar_drawer: true,
                paste_data_images: true,
                images_upload_credentials: true,
                //  解决截图，不走图片上传问题
                urlconverter_callback: (url, node, onSave, name) => {
                    if (node === 'img' && url.startsWith('blob:')) {
                        // Do some custom URL conversion
                        // console.log('urlConverter:', url, node, onSave, name)
                        tinymce.activeEditor && tinymce.activeEditor.uploadImages()
                    }
                    // Return new URL
                    return url
                },
                images_upload_handler: (blobInfo, success) => {
                    this.cosUpload(blobInfo, success)
                    // let formData = new FormData()
                    // formData.append('file', blobInfo.blob(), blobInfo.filename())
                    // formData.append('biz', 'jeditor')
                    // formData.append('jeditor', '1')

                    // uploadAction(window._CONFIG['domianURL'] + '/sys/common/upload', formData).then((res) => {
                    //     console.log(res)
                    //     if (res.success) {
                    //         if (res.message == 'local') {
                    //             const img = 'data:image/jpeg;base64,' + blobInfo.base64()
                    //             success(img)
                    //         } else {
                    //             let img = getFileAccessHttpUrl(res.message)
                    //             success(img)
                    //         }
                    //     }
                    // })
                },
            },
            myValue: this.value,
        }
    },
    mounted() {
        tinymce.init(this.init)
    },
    methods: {
        onClick(e) {
            this.$emit('onClick', e, tinymce)
        },
        //可以添加一些自己的自定义事件，如清空内容
        clear() {
            this.myValue = ''
        },
        onChange(e) {},

        cosUpload(blobInfo, success) {
            console.log(success)
            this.$nextTick(() => {
                var that = this
                let date = new Date()
                let y = date.getFullYear()
                let MM = date.getMonth() + 1
                MM = MM < 10 ? '0' + MM : MM
                let d = date.getDate()
                d = d < 10 ? '0' + d : d
                var timeElse = new Date().getTime()
                var arr = blobInfo.filename().split('.')

                var str = ''
                for (let i = 0; i < arr.length; i++) {
                    if (i == arr.length - 1) {
                    } else {
                        if (i == arr.length - 2) {
                            str += arr[i]
                        } else {
                            str += arr[i] + '.'
                        }
                    }
                }
                // console.log(str + '-' + timeElse + '.' + arr[arr.length - 1])
                cos.putObject(
                    {
                        Bucket: 'media-1301855440',
                        /* 必须 */
                        Region: 'ap-chongqing',
                        /* 存储桶所在地域，必须字段 */
                        Key: 'video/' + y + '-' + MM + '-' + d + '/' + str + '-' + timeElse + '.jpg',
                        /* 必须 */
                        StorageClass: 'STANDARD',
                        Body: blobInfo.blob(), // 上传文件对象
                        onProgress: function (progressData) {
                            //进度条方法
                        },
                        onTaskReady: function (tid) {
                            // console.log('onTaskReady', tid);
                        },
                        onTaskStart: function (info) {
                            //开始上传
                            // console.log('onTaskStart', info);
                        },
                    },
                    function (err, data) {
                        console.log(err, data)
                        if (err) {
                            that.$message.error('上传失败!!!' + err)
                            return
                        } else {
                            var img = '//' + data.Location
                            success(img)
                        }
                    }
                )
            })
        },
    },
    watch: {
        value(newValue) {
            this.myValue = newValue == null ? '' : newValue
        },
        myValue(newValue) {
            console.log(newValue)
            console.log(tinymce.editors['tinydemo'])
            // tinymce.editors['tinydemo'].getContent()
            if (this.triggerChange) {
                this.$emit('change', newValue)
            } else {
                this.$emit('input', newValue)
            }
        },
    },
}
</script>
<style scoped></style>
