import React from 'react';
import { Editor } from '@tinymce/tinymce-react';
// import tinymce from 'tinymce/tinymce';
import { uploadImg, keepLastIndex } from '@/utils'

class EditorInput extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      value: props.defaultContent,
    }
  }
  handleEditorChange = (content, editor) => {
    const { onChange } = this.props
    console.log('Content was updated:', content);
    onChange(content)
  }
  componentDidMount() {
    const { keys = '22' } = this.props
    tinymce.init({ selector: `#tinymce_${keys}` })
  }
  async resetImgSrc(str) {
    if (!str) return
    const { onChange } = this.props
    let newStr = str
    const imgReg = /<img.*?(?:>|\/>)/gi
    const srcReg = /src=[\'\"]?([^\'\"]*)[\'\"]?/i
    const imgArr = newStr.match(imgReg)
    imgArr && imgArr.map(async t => {
      const src = t.match(srcReg)
      if (src[1] && src[1].includes('data:image')) {
        const newImgUrl = await uploadImg(src[1])
        newStr = newStr.replace(src[1], newImgUrl)
        this.setState({
          value: newStr
        }, () => {
          const ifra = document.getElementById(`tinymce_${this.props.keys}_ifr`)
          keepLastIndex(ifra.contentWindow.document.getElementById(`tinymce`), ifra.contentWindow)
        })
      }
    })
  }

  componentWillReceiveProps(nextProps) {
    const { defaultContent } = this.props
    if(defaultContent !== nextProps.defaultContent) {
      this.setState({
        value: nextProps.defaultConten
      })
      this.resetImgSrc(nextProps.defaultContent)
    }
  }
  render() {
    const { keys = '22', height = '300px' } = this.props
    const { value } = this.state
    const editorObj = {
      auto_focus: false,
      language_url: require('./tinymce/langs/zh_CN.js'),
      language: 'zh_CN',
      // skin_url: require('./tinymce/skins/ui/oxide'), // 编辑器需要一个skin才能正常工作，所以要设置一个skin_url指向之前复制出来的skin文件
      height: height,
      browser_spellcheck: true, // 拼写检查
      branding: false, // 去水印
      elementpath: false, // 禁用编辑器底部的状态栏
      statusbar: false, // 隐藏编辑器底部的状态栏
      paste_data_images: true, // 允许粘贴图像
      images_file_types: 'jpeg,jpg,png,gif,bmp,webp',
      menubar: false, // 隐藏最上方menu
      default_link_target: "_blank", // 默认链接打开方式
      target_list:[
        {title: '新窗口', value: '_blank'}
      ],
      fontsize_formats: '14px 16px 18px 20px 24px 26px 28px 30px 32px 36px', // 字体大小
      file_picker_types: 'image',
      charmap_append: [
        [0x2615, 'morning coffee'],
        [0x2600, 'sun'],
        [0x2601, 'cloud'],
      ],
      images_upload_credentials: true,
      plugins: 'fullscreen lists table textcolor wordcount contextmenu codesample link imagetools charmap autolink paste', // 引入插件
      toolbar: 'fullscreen bold italic underline strikethrough | fontsizeselect | forecolor backcolor link codesample | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent table | undo redo | removeformat formatselect charmap paste',
      table_toolbar: 'tableprops | tableinsertrowbefore tableinsertrowafter tabledeleterow | tableinsertcolbefore tableinsertcolafter tabledeletecol | tablemergecells tablesplitcells',
      relative_urls: false,
      images_upload_url: 'http://star.xiaojukeji.com/upload/img.node',
      image_advtab: true,
      image_uploadtab: true,
      content_style: `
      p {
        font-size: 14px;
      }
    `,
      paste_preprocess: function(plugin, args) {
        if ( args.content.search(/<a\ href/g) > -1) {
          args.content = args.content.replace(/<a\ href/g, '<a target="_blank" href')
        }
      },
      images_upload_handler: (blobInfo, success, failure) => {
        //这里写你上传图片的方法
        console.log(11111, blobInfo, success, failure)
      }
    }

    return (
      <div className="editor">
        <Editor
          id={`tinymce_${keys}`}
          // key={keys}
          inline={false}
          // apiKey='官网上申请的key值'
          value={value}
          init={{ ...editorObj }}
          onEditorChange={(content, editor) => this.handleEditorChange(content, editor)}
          // onChange={(content, editor) => this.handleEditorChange(content, editor)}
        />
      </div>
    );
  }
}

export default EditorInput;