/**
 * Created by baoyinghai on 3/28/17.
 */
import React from 'react';
import { Icon, Input } from '../../../components/mxa';
import { addToolTips } from '../../../components/tooltip';
import { renderFormComp } from '../detail/displayComp';
import { getValueByKey } from '../../utils/MapUtils';
import { addClassName, removeClassName } from '../../utils/DOMUtils';
import createRules from '../detail/formValidator';

export default class EditableCell extends React.Component {
  state = {
    value: this.props.value,
    editable: false,
  };

  handleChange = e => {
    const value = getValueByKey(e, e, 'target', 'value');
    this.setState({ value });
  };

  _formApiAdapter = () => {
    const { getCurrentRecord } = this.props;
    return {
      getFieldsValue: () => {
        return getCurrentRecord();
      },
      getFieldValue: key => {
        return getCurrentRecord()[key];
      },
      validateFields: () => true
    };
  };

  _executeValidate = (rules = [], value) => {
    let errorMsg = [];
    rules.forEach(item => {
      if (item && item.required) {
        if (value === undefined || value === '' || value === null) {
          errorMsg.push(item.message);
        }
      } else if (item && item.validator && typeof item.validator === 'function') {
        item.validator({}, value, errors => {
          errorMsg = errorMsg.concat(errors);
        });
      }
    });
    if (errorMsg.length > 0) {
      console.error(errorMsg);
      /* eslint-disable */
      const editableCell = this.refs.editableCell;
      addClassName(editableCell.firstChild, 'editable-cell-error');
      addToolTips(editableCell, errorMsg[0].message);
      return false;
    }
    return true;
  };

  check = e => {
    e.stopPropagation();
    const { fieldContent } = this.props;
    const rules = createRules(fieldContent, this._formApiAdapter());
    if (this._executeValidate(rules, this.state.value) && this.props.onChange) {
      if (this.props.onChange(this.state.value)) {
        this.setState({ editable: false });
      }
    }
    console.log('fail');
  };

  edit = e => {
    e.stopPropagation();
    /* eslint-disable */
    this.setState({ editable: true });
  };

  _renderEditComp = () => {
    const { fieldContent } = this.props;
    const compRenderFunc = renderFormComp(fieldContent);
    return React.cloneElement(compRenderFunc({ record: fieldContent, props: {} }), { onChange: this.handleChange, value: this.state.value });
  };

  render() {
    const { value, editable } = this.state;
    const { fieldContent, renderColumn } = this.props;
    return (
      <div className="editable-cell" onClick={e => editable && e.stopPropagation()}>
        {
          editable ?
            <div ref="editableCell" className="editable-cell-input-wrapper">
              {this._renderEditComp()}
              <Icon
                type="check"
                className="editable-cell-icon-check"
                onClick={this.check}
              />
            </div>
            :
              <div className="editable-cell-text-wrapper">
                {renderColumn(value, fieldContent)}
                <Icon
                  type="edit"
                  className="editable-cell-icon"
                  onClick={this.edit}
                />
              </div>
        }
      </div>
    );
  }
}
