import React, { Component } from 'react';
import { Input } from '@easyv/antd';
import styles from './EditableText.less';
import classNames from 'classnames';

interface IProps {
  text: string;
  className?: string;
  icon?: string;
  placeholder?: string;
  suffix?: string | React.ReactElement;
  doubleClick?: boolean;
  isMultiExport?: boolean;
  max?: number;
  onFocus?: () => void;
  onBlur?: () => void;
  onCommit: (value) => void;
}

interface IState {
  value: string;
  editable: boolean;
}

export default class EditableText extends Component<IProps, IState> {
  edit: Input | null;
  constructor(props) {
    super(props);
    this.state = {
      editable: false,
      value: this.props.text
    };
  }
  onEdit = (e) => {
    if (this.props.isMultiExport) {
      // 批量管理状态不允许修改
      return false;
    }
    e.stopPropagation();
    this.props.onFocus && this.props.onFocus();
    this.setState(
      {
        editable: true
      },
      () => this.edit?.focus()
    );
  };
  onChange = (value) => {
    const { max = 100 } = this.props;
    this.setState({
      value: value.length > max ? value.slice(0, max) : value
    });
  };
  UNSAFE_componentWillReceiveProps(nextProps) {
    if (nextProps.text !== this.props.text) {
      this.setState({
        value: nextProps.text
      });
    }
  }
  onCommit = () => {
    this.setState({
      editable: false
    });
    this.props.onBlur && this.props.onBlur();
    const newValue = this.state.value.trim();
    if (newValue !== this.props.text && newValue) {
      this.props.onCommit(newValue);
    } else {
      this.setState({
        value: this.props.text
      });
    }
  };
  onFocus = (e) => {
    e.target.select();
  };
  render() {
    const { className, icon, placeholder = '请输入大屏名称', suffix, doubleClick } = this.props;
    const { value, editable } = this.state;
    return (
      <div
        className={classNames(styles.title, className)}
        onClick={!doubleClick ? this.onEdit : undefined}
        onDoubleClick={doubleClick ? this.onEdit : undefined}>
        {icon}
        {editable ? (
          <Input
            className={styles.input}
            ref={(dom) => (this.edit = dom)}
            value={value}
            onChange={(d) => this.onChange(d.target.value)}
            placeholder={placeholder}
            onPressEnter={(e: any) => e.target.blur()}
            onBlur={this.onCommit}
            onFocus={this.onFocus}
          />
        ) : (
          <p className={styles.name} title={value}>
            {value}
          </p>
        )}
        <div className={styles.suffix}>{!editable ? suffix : null}</div>
      </div>
    );
  }
}
