import React, { useEffect, useState } from 'react';
import { Form } from 'antd';
import BraftEditor from 'braft-editor';
import { useThrottleFn } from 'ahooks';
import { get } from 'lodash';
import 'braft-editor/dist/index.css';
import './style/index.less';

let lock = false;
export default ({
  propKey,
  config,
  node,
  onChange = () => {},
  width = '100%',
  height = 150,
  disableOnChange = false,
}) => {
  const { name, extra = {} } = config;
  const {
    onBlur,
    onTextChange = () => {},
    className = '',
    contentClassName = '',
  } = extra;
  const [editorState, setEditorState] = useState(null);
  const { run } = useThrottleFn(
    editorValue => {
      const value = editorValue.toHTML();
      setEditorState(editorValue);
      if (!disableOnChange) {
        onChange(name, value);
      }
      onTextChange(value);
    },
    { wait: 300 },
  );
  const handleEditorChange = editorValue => {
    if (!lock) {
      run(editorValue);
    }
  };
  const handleBlur = editorValue => {
    if (onBlur) {
      onBlur(editorValue.toHTML());
    }
  };
  const controls = extra.controls || [
    {
      key: 'bold',
      text: <b>加粗</b>,
    },
    'italic',
    'underline',
    'separator',
    'link',
    'text-indent',
    'line-height',
    'font-size',
  ];
  useEffect(() => {
    /** 因BraftEditor每次都重新渲染实例。(使用value会存在切换编辑组件误触发的问题),所以使用了lock, formValues更新的时候不触发onChange事件 */
    let text = '';
    if (propKey) {
      text = get(node, `${propKey}.${name}`);
    } else {
      text = get(node, `${name}`);
    }
    lock = true;
    setEditorState(BraftEditor.createEditorState(text));
    setTimeout(() => {
      lock = false;
    });
  }, [node]);
  return (
    <Form.Item noStyle>
      <BraftEditor
        contentStyle={{ width, height }}
        className={`bf-wrapper ${className}`}
        contentClassName={`bf-content ${contentClassName}`}
        controls={controls}
        value={editorState}
        onChange={handleEditorChange}
        onBlur={handleBlur}
      />
    </Form.Item>
  );
};
