import React from 'react';
import Textarea from '../../components/Textarea';
import TextArea from 'antd/lib/input/TextArea';
import { Icon } from '../../components/icons';
import { findDOMNode } from 'react-dom';
import { Button, Drawer } from 'antd';
import { autobind, isMobile, ucFirst } from '../../utils/helper';
import { FormItem, FormControlProps, FormBaseControl } from './Item';

/**
 * TextArea 多行文本输入框。
 * 文档：https://baidu.gitee.io/amis/docs/components/form/textarea
 */
export interface TextareaControlSchema extends FormBaseControl {
  /**
   * 指定为多行文本输入框
   */
  type: 'textarea';

  /**
   * 最大行数
   */
  maxRows?: number;

  /**
   * 最小行数
   */
  minRows?: number;

  /**
   * 是否只读
   */
  readOnly?: boolean;

  /**
   * 边框模式，全边框，还是半边框，或者没边框。
   */
  borderMode?: 'full' | 'half' | 'none';

  /**
   * 限制文字最大个数
   */
  maxLength?: number;

  /**
   * 是否显示计数
   */
  showCounter?: boolean;
}

export interface TextAreaProps extends FormControlProps {
  placeholder?: string;
  minRows?: number;
  maxRows?: number;
}
interface TextareaState {
  focused: boolean,
  openTextarea: boolean,
}
export default class TextAreaControl extends React.Component<
  TextAreaProps, TextareaState
> {
  static defaultProps: Partial<TextAreaProps> = {
    minRows: 3,
    maxRows: 20,
    trimContents: true
  };

  state: TextareaState = {
    focused: false,
    openTextarea: false
  };

  input?: HTMLInputElement;
  inputRef = (ref: any) => (this.input = findDOMNode(ref) as HTMLInputElement);

  focus() {
    if (!this.input) {
      return;
    }

    this.setState(
      {
        focused: true
      },
      () => {
        if (!this.input) {
          return;
        }

        this.input.focus();

        // 光标放到最后
        const len = this.input.value.length;
        len && this.input.setSelectionRange(len, len);
      }
    );
  }

  @autobind
  handleChange(e: React.ChangeEvent<any>) {
    const { onChange } = this.props;
    let value = e.currentTarget.value;
    if (typeof value === 'string') {
      value = value.replaceAll('\n', '\r\n')
    }
    onChange(value);
  }

  @autobind
  handleFocus(e: React.FocusEvent<HTMLTextAreaElement>) {
    const { onFocus } = this.props;
    this.setState(
      {
        focused: true
      },
      () => {
        onFocus && onFocus(e);
      }
    );
  }

  @autobind
  handleBlur(e: React.FocusEvent<HTMLTextAreaElement>) {
    const { onBlur, trimContents, value, onChange } = this.props;

    this.setState(
      {
        focused: false
      },
      () => {
        if (trimContents && value && typeof value === 'string') {
          onChange(value.trim());
        }

        onBlur && onBlur(e);
      }
    );
  }

  render() {
    const {
      className,
      classPrefix: ns,
      value,
      placeholder,
      disabled,
      minRows,
      maxRows,
      readOnly,
      name,
      borderMode,
      classnames: cx,
      maxLength,
      env,
      isDetail,
      showCounter
    } = this.props;

    const original = typeof value === 'undefined' || value === null
      ? ''
      : typeof value === 'string'
        ? value
        : JSON.stringify(value)

    const { openTextarea } = this.state;
    const counter = showCounter ? original.length : 0;

    return (
      <div
        className={cx(
          `TextareaControl`,
          {
            [`TextareaControl--border${ucFirst(borderMode)}`]: borderMode,
            [`TextareaControl-borderNone`]: isDetail,
            'is-focused': this.state.focused,
            'is-readOnly': readOnly
          },
          className
        )}
      >
        {
          isMobile() ? <>
            <div
              className={cx('TextareaControl-TextArea', !original?.length && 'TextAreaControl-notReadOnly')}
              onClick={() => { this.setState({ openTextarea: true }) }}>
              <div className={cx('TextareaControl-TextArea-original')}>
                {original?.length ? original : !readOnly ? placeholder : '-'}
              </div>
              {!readOnly && <a className={cx('Table-expandBtn')} style={{ minWidth: 10 }} >
                <Icon icon="right-arrow-bold" className="icon" />
              </a>}
            </div>
            {<Drawer
              visible={openTextarea}
              width="100%"
              className="textarea-drawer"
              closeIcon={<Icon icon='title-left' className="icon" style={{ width: '16px', height: '16px' }} />}
              onClose={() => this.setState({ openTextarea: false })}
              destroyOnClose
              mask={false}
              getContainer={env.getModalContainer}
              zIndex={1011}
              title={(!readOnly ? '修改' : '') + this.props.label}
              footer={<div className='textarea-drawer-footer'>
                <Button type="primary" onClick={() => this.setState({ openTextarea: false })}>
                  完成
                </Button>
              </div>}
              extra={
                <Button
                  danger
                  size='small'
                  type="text"></Button>
              }
            >
              <TextArea
                style={{ height: '50%', resize: 'none' }}
                onChange={this.handleChange}
                placeholder={placeholder}
                name={name}
                showCount={showCounter}
                bordered={false}
                maxLength={maxLength}
                className={readOnly ? 'disabled' : ''}
                readOnly={readOnly}
                value={original}
                disabled={disabled}
                onKeyDown={(e) => e.stopPropagation()}
                onFocus={this.handleFocus}
                onBlur={this.handleBlur}
                autoCorrect="off"
                spellCheck="false"
              />
            </Drawer>}
          </>
            :
            <>
              <Textarea
                autoComplete="off"
                ref={this.inputRef}
                name={name}
                disabled={disabled}
                value={original}
                placeholder={placeholder}
                autoCorrect="off"
                spellCheck="false"
                readOnly={readOnly}
                minRows={minRows || undefined}
                maxRows={maxRows || undefined}
                onChange={this.handleChange}
                onFocus={this.handleFocus}
                onBlur={this.handleBlur}
                maxLength={maxLength}
                onKeyDown={(e) => e.stopPropagation()}
                style={{ resize: 'vertical' }}
              />
              {showCounter ? (
                <span
                  className={cx(
                    'TextareaControl-counter',
                    counter === 0 ? 'is-empty' : ''
                  )}
                >
                  {`${counter}${typeof maxLength === 'number' && maxLength ? `/${maxLength}` : ''}`}
                </span>
              ) : null}
            </>
        }

      </div>
    );
  }
}

@FormItem({
  type: 'textarea'
})
export class TextAreaControlRenderer extends TextAreaControl { }
