import '@wangeditor/editor/dist/css/style.css' // 引入 css
import { shallowRef, onMounted, defineComponent, reactive, ref, watch, PropType } from 'vue'
import { createEditor, createToolbar } from '@wangeditor/editor'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import { NButton, NSpin } from 'naive-ui'
import styles from './index.module.less'
import dayjs from 'dayjs'
import { getUploadSign, onOnlyFileUpload } from '@/utils/oss-file-upload'

// type InsertFnType = (url: string, poster = '') => void

export default defineComponent({
  name: 'editor',
  props: {
    value: {
      type: String,
      default: ''
    },
    editorType: {
      type: String as PropType<'default' | 'simple'>,
      default: 'default'
    },
    placeholder: {
      type: String,
      default: '请输入内容...'
    },
    disabled: {
      type: Boolean,
      default: false
    },
    height: {
      // 编辑器内容高度
      type: Number,
      default: 300
    },
    bucketName: {
      type: String,
      default: 'gyt'
    },
    id: {
      type: String,
      default: ''
    },
    /** 去掉工具栏类型 */
    excludeKeys: {
      type: Array as PropType<any>,
      default: []
    }
  },
  emits: ['update:value'],
  setup(props, { slots, attrs, emit }) {
    const state = reactive({
      policy: '',
      signature: '',
      key: '',
      KSSAccessKeyId: '',
      acl: 'public-read',
      name: ''
    }) as any
    const idKey = props.id || new Date().getTime()
    const loading = ref(false)
    const ossUploadUrl = `https://${props.bucketName}.ks3-cn-beijing.ksyuncs.com/`
    const changeEditor = ref(false)
    // 编辑器实例，必须用 shallowRef
    const editor = shallowRef()
    const toolbar = shallowRef()
    const editorConfig = {
      placeholder: props.placeholder as any,
      onChange(editor: any) {
        const html = editor.getHtml()
        if (editor.isEmpty()) {
          emit('update:value', '')
        } else {
          emit('update:value', html)
          changeEditor.value = true
        }
        // 也可以同步到 <textarea>
      },
      MENU_CONF: [] as any
    }
    watch(
      () => props.value,
      (value: any) => {
        // console.log(value, 'value', changeEditor.value)
        if (!changeEditor.value) editor.value.setHtml(value)
      }
    )
    editorConfig.MENU_CONF['uploadImage'] = {
      // 自定义上传
      async customUpload(file: File, insertFn: any) {
        // file 即选中的文件
        // 自己实现上传，并得到图片 url alt href
        // 最后插入图片
        uploadFile(file, insertFn)
      }
    }

    editorConfig.MENU_CONF['uploadVideo'] = {
      // 自定义上传
      async customUpload(file: File, insertFn: any) {
        // file 即选中的文件
        // 自己实现上传，并得到图片 url alt href
        // 最后插入图片
        uploadFile(file, insertFn)
      }
    }

    const uploadFile = async (file: any, insertFn: any) => {
      try {
        loading.value = true
        const suffix = file.name.slice(file.name.lastIndexOf('.'))
        const months = dayjs().format('MM')
        const fileName = `${months}/${new Date().getTime() + suffix}`
        const obj = {
          filename: fileName,
          bucketName: props.bucketName,
          postData: {
            filename: fileName,
            acl: 'public-read',
            key: fileName,
            unknowValueField: []
          }
        }

        const { data } = await getUploadSign(obj)
        const fileParams = {
          policy: data.policy,
          signature: data.signature,
          key: fileName,
          acl: 'public-read',
          KSSAccessKeyId: data.kssAccessKeyId,
          name: fileName,
          file
        } as any
        const res = await onOnlyFileUpload(ossUploadUrl, fileParams)

        console.log(res, 'res')
        insertFn && insertFn(res)

        loading.value = false
      } catch {
        loading.value = false
      }
    }

    const toolbarConfig = {
      modalAppendToBody: true,
      excludeKeys: [
        'group-image',
        'group-video',
        'codeBlock',
        'fullScreen',
        'code',
        'insertLink',
        'todo',
        ...props.excludeKeys
      ],
      insertKeys: {
        index: 23,
        keys: ['uploadImage', 'uploadVideo']
      }
    }

    onMounted(() => {
      // console.log(props.value, '初始化编辑器的值', idKey)
      editor.value = createEditor({
        selector: `#editor-container${idKey}`,
        html: props.value || '<p></p>',
        config: editorConfig,
        mode: props.editorType //'default' // or 'simple'
      })

      toolbar.value = createToolbar({
        editor: editor.value,
        selector: `#toolbar-container${idKey}`,
        config: toolbarConfig,
        mode: 'default' // or 'simple'
      })
      if (props.disabled) {
        editor.value.disable()
      }
      editor.value.on('modalOrPanelShow', (modalOrPanel: any) => {
        if (modalOrPanel.type !== 'modal') return
        const { $elem } = modalOrPanel // modal element
        // console.log(modalOrPanel, 'modal')
        // 设置 modal 样式（定位、z-index）
        // 显示蒙层
        $elem[0].style.left = `50%`
        $elem[0].style.top = `50%`
        $elem[0].style.marginLeft = `-150px`
        $elem[0].style.marginTop = `-150px`
      })
    })

    // const onSave = () => {
    //   const config = toolbar.value.getConfig()
    //   // console.log(config)
    //   // editor.value.disable()
    // }
    return () => (
      <>
        <NSpin show={loading.value}>
          <div id={`editor—wrapper${idKey}`} class={[styles.editorWrapper, 'editorContainer']}>
            <div id={`toolbar-container${idKey}`}>{/* 工具栏 */}</div>
            <div id={`editor-container${idKey}`} style={{ height: props.height + 'px' }}>
              {/* 编辑器 */}
            </div>
          </div>
        </NSpin>
      </>
    )
  }
})
