import React from 'react';
import ReactQuill from 'react-quill';
import 'react-quill/dist/quill.snow.css';
import { uuid } from '../../services/Tools';

const modules = {
  toolbar: {
    container: [
      [{ header: '1' }, { header: '2' }],
      [
        'bold',
        'underline',
        'blockquote',
        // { color: ['red', 'green', 'blue', 'orange', 'violet', '#d0d1d2', 'black'] },
      ],
      [{ list: 'ordered' }, { list: 'bullet' }, { indent: '-1' }, { indent: '+1' }],
      // ['image'],
      // ['link', 'video'],
      // ['clean'],
    ],
    handlers: {},
  },
  clipboard: {
    // toggle to add extra line breaks when pasting HTML:
    matchVisual: false,
  },
};

const formats = [
  'header',
  'font',
  'size',
  'bold',
  'italic',
  'underline',
  'strike',
  'blockquote',
  'color',
  'list',
  'bullet',
  'indent',
  'link',
  'image',
  // 'video',
];
class Editor extends React.Component {
  constructor(props) {
    super(props);
    this.quillRef = null;
    this.state = {};
    this.loading = 0;
    this.modules = Object.assign({}, modules, props.modules);
    // console.log(this.modules);
    this.modules.toolbar.handlers.image = () => this.image();
    Object.keys(this.modules.toolbar.handlers).forEach(key => {
      const handler = this.modules.toolbar.handlers[key];
      this.modules.toolbar.handlers[key] = () => {
        handler(this.quillRef.getEditor());
      };
    });
    this.formats = Object.assign({}, formats, props.formats);
  }

  progress(data) {
    return done => {
      if (this.props.onProgress) this.props.onProgress(data);
      done();
    };
  }

  image() {
    const self = this;
    this.container = this.quillRef.editingArea;
    const quill = this.quillRef.getEditor();
    let fileInput = this.container.querySelector('input.ql-image[type=file]'); // fileInput

    if (fileInput == null) {
      fileInput = document.createElement('input');
      fileInput.setAttribute('type', 'file');
      fileInput.setAttribute('accept', 'image/png, image/gif, image/jpeg, image/bmp, image/x-icon');
      fileInput.classList.add('ql-image');
      fileInput.addEventListener('change', () => {
        if (fileInput.files != null && fileInput.files[0] != null) {
          // getSelection 选择当前光标位置咯 然后在下一个range.index用它自带的embed媒介插入方式插入你已经存储在阿里上的图片了
          const range = quill.getSelection(true);
          const file = fileInput.files[0];
          const suffix = file.name.substring(file.name.lastIndexOf('.')).toLowerCase();
          const name = uuid();
          self.props
            .onUpload(file, self.props.path, self.progress, `${self.props.path}/${name}${suffix}`)
            .then(data => {
              self.setState({ uploading: false, load: self.state.load + 1 });
              quill.insertEmbed(range.index, 'image', data.url || data);
              quill.setSelection(range.index + 1);
            })
            .catch(err => {
              self.setState({ uploading: false, load: self.state.load + 1 });
              if (self.props.onError) self.props.onError(err);
            });
        }
      });
    }
    fileInput.click();
  }

  render() {
    return (
      <div>
        <ReactQuill
          ref={el => {
            this.quillRef = el;
          }}
          style={this.props.style}
          theme={this.props.theme || 'snow'}
          onChange={(content, delta, source, editor) => {
            if (this.props.onChange) this.props.onChange(content, delta, source, editor);
          }}
          value={this.props.value || ''}
          modules={this.modules}
          formats={this.formats}
          placeholder={this.props.placeholder}
        />
      </div>
    );
  }
}


export default Editor;
