/**
 * Created by baoyinghai on 12/7/16.
 */
import React from 'react';
import { autobind } from 'core-decorators';
import staticDisplay from './StaticDisplay';
import ValidateTypes from '../../formValidator/validateTypes';
import { VIEW, EDIT } from '../../constant';
import { Input } from '../../../../../components/mxa';

class TextArea extends React.Component {

  constructor(porps) {
    super(porps);
    this.state = {
      len: (this.props.value && this.props.value.length) || 0,
      value: this.props.value,
    };
  }

  componentWillReceiveProps(next) {
    if (next.value !== this.state.value) {
      this.state.value = next.value;
      this.state.len = (next.value && next.value.length) || 0;
    }
  }

  @autobind
  _onChange(e) {
    const { onChange } = this.props;
    this.setState({ len: e.target.value.length, value: e.target.value });
    onChange && onChange(e.target.value);
  }

  render() {
    return (
      <div>
        <Input value={this.state.value} type="textarea" disabled={this.props.disabled} rows={4} onChange={this._onChange} />
        <div className="text-area-length">
          {this.props.length && (<span style={this.state.len > this.props.length ? { color: '#f50' } : {}}>{ this.state.len + '/' + this.props.length}</span>)}
        </div>
      </div>
    );
  }
}

const compRender = config => {
  const { record, props } = config;
  const formValidate = record.formValidates && record.formValidates.filter(item => item.validateType === ValidateTypes.ISSTRING)[0];
  const length = (formValidate && formValidate.length) || record.length;
  return (<TextArea disabled={record.isReadonly || (props.isModalInputMappingItem && props.isLeadInto && props.modalInputIsReadonly)} length={length} />);
};

export default {
  [VIEW]: staticDisplay,
  [EDIT]: compRender
};
