import React, { Component } from 'react';
import isEqual from 'lodash/isEqual';
import { PlusOutlined } from '@ant-design/icons';
import { Input, Button, Tag } from '@easyv/antd';
import { Tooltip } from '@easyv/react-gui';
import AceEditor from '@easyv/react-ace';
import styles from './FilterEditor.less';
import message from 'components/message';
import 'brace/theme/github';

class FilterEditor extends Component<
  {
    filter: any;
    onComplete: (config) => any;
    onPreview: (id, content) => any;
    onClose: () => any;
  },
  {
    callbackKeys: any;
    inputVisible: boolean;
    inputValue: string;
    filterContent: string;
  }
> {
  filterName: any;
  input: any;
  constructor(props) {
    super(props);
    const { filter = {} } = this.props;
    const { callbackKeys = [] } = filter;
    this.state = {
      callbackKeys,
      inputVisible: false,
      inputValue: '',
      filterContent: filter.content
    };
  }
  onComplete = () => {
    const { filter, onComplete } = this.props;
    const { callbackKeys, filterContent } = this.state;

    const filterName = this.filterName.value;
    if (!filterName) {
      message.error('过滤器名称必填');
      return;
    }

    if (!filterContent) {
      message.error('过滤器内容不能为空');
      return;
    }

    const param: any = {
      name: filterName,
      content: filterContent,
      callbackKeys
    };
    if (filter && filter.id) {
      param.id = filter.id;
    }

    onComplete(param);
  };

  onPreviewFilter = () => {
    const { filter = {}, onPreview } = this.props;
    const { filterContent } = this.state;
    onPreview(filter.id, filterContent);
  };

  handleInputChange = (e) => {
    this.setState({ inputValue: e.target.value });
  };

  handleInputConfirm = () => {
    const { inputValue } = this.state;
    let { callbackKeys } = this.state;
    if (inputValue && callbackKeys.indexOf(inputValue) === -1) {
      callbackKeys = [...callbackKeys, inputValue];
    }

    this.setState({
      callbackKeys,
      inputVisible: false,
      inputValue: ''
    });
  };

  showInput = () => {
    this.setState({ inputVisible: true }, () => this.input.focus());
  };

  handleClose = (removedTag) => {
    const callbackKeys = this.state.callbackKeys.filter((tag) => tag !== removedTag);
    this.setState({ callbackKeys });
  };

  UNSAFE_componentWillReceiveProps(nextProps) {
    const { filter = {} } = this.props;
    const { filter: nextFilter = {} } = nextProps;
    if (!isEqual(filter.callbackKeys, nextFilter.callbackKeys)) {
      this.setState({
        callbackKeys: nextFilter.callbackKeys || []
      });
    }
    if (!isEqual(filter.content, nextFilter.content)) {
      this.setState({
        filterContent: nextFilter.content || []
      });
    }
  }

  handleFilterContentChange = (value) => {
    this.setState({
      filterContent: value
    });
  };

  render() {
    const { filter = {}, onClose } = this.props;
    const { callbackKeys, inputVisible, inputValue, filterContent } = this.state;
    // const codeStart = 'function filter(data, callbackArgs) {';
    // const codeEnd = '}';

    return (
      <div className={styles.editor}>
        <div className={styles.field}>
          <span className={styles.label}>
            名称<i style={{ color: 'red' }}>*</i>
          </span>
          <Input style={{ flex: 1 }} defaultValue={filter.name} ref={(dom) => (this.filterName = dom)} />
        </div>
        <div className={styles.field}>
          <span className={styles.label}>回调字段</span>
          <div style={{ flex: 1 }}>
            {callbackKeys.map((tag) => {
              return (
                <Tag key={tag} closable={true} onClose={() => this.handleClose(tag)}>
                  {tag}
                </Tag>
              );
            })}
            {inputVisible && (
              <Input
                ref={(input) => (this.input = input)}
                type="text"
                size="small"
                style={{ width: 78, height: 22 }}
                value={inputValue}
                onChange={this.handleInputChange}
                onBlur={this.handleInputConfirm}
                onPressEnter={this.handleInputConfirm}
              />
            )}
            {!inputVisible && (
              <Tag onClick={this.showInput} style={{ background: '#fff', borderStyle: 'dashed' }}>
                <PlusOutlined /> 添加回调
              </Tag>
            )}
          </div>
        </div>
        <div className={styles.code}>
          <p className={styles.codeStart}>
            <span>
              {'function filter('}
              <Tooltip title="数据">data</Tooltip>,<Tooltip title="回调参数集"> callbackArgs</Tooltip>
              {'){'}
            </span>
          </p>
          <div className={styles.codeWrapper}>
            <AceEditor
              mode="javascript"
              theme="github"
              width="100%"
              height="100%"
              name="code"
              tabSize={2}
              value={filterContent}
              onChange={this.handleFilterContentChange}
              enableBasicAutocompletion={true}
              enableLiveAutocompletion={true}
              showGutter={true}
              editorProps={{ $blockScrolling: true }}
              setOptions={{
                wrap: true,
                useWorker: false
              }}
            />
          </div>
          <p className={styles.codeEnd}>{'}'}</p>
        </div>

        <div className={styles.actionArea}>
          <Button type="primary" onClick={this.onPreviewFilter}>
            预览
          </Button>
          <div>
            <Button onClick={onClose}>取消</Button>
            <Button type="primary" style={{ marginLeft: 16 }} onClick={this.onComplete}>
              完成
            </Button>
          </div>
        </div>
      </div>
    );
  }
}

export default FilterEditor;
