/**
 * Created by baoyinghai on 6/28/17.
 */
import React from 'react';
import './index.less';
import lib from './lib';
// import { Input } from '../../../mxa';

export default class Form extends React.Component {

  constructor(props) {
    super(props);
    const { dataSource = {} } = this.props;
    this.state = {
      ...dataSource
    };
  }

  componentWillReceiveProps(nextProps) {
    // TODO: filter
    const { dataSource = {} } = nextProps;
    this.setState(
      ...dataSource
    );
  }

  _getComp = cType => {
    return cType ? lib[cType] : lib.INPUT;
  };

  _renderFormItem = dataSource => {
    const d = this.state;
    const { fieldDesc } = this.props;
    const Comp = this._getComp(fieldDesc.cType);
    return Object.keys(dataSource).map(key => (
      <div className="form-item-wrapper">
        <span className="form-item-required">*</span>
        <span className="form-item-label">{fieldDesc[key].desc || key}</span>
        <Comp className="form-item-input" value={d[key]} onChange={e => this._onChange(e, key)} onBlur={e => this._onBlur(e, key)} />
        <span className="form-item-error">error</span>
      </div>
    ));
  };

  _onChange = (e, key) => {
    // TODO: 做校验
    this.setState({
      [key]: e.target.value
    });
  };

  _onBlur = (e, key) => {
    const { dispatch, _getDataPath } = this.props;
    // TODO: 做校验
    dispatch && dispatch(_getDataPath(key), e.target.value);
  };

  render() {
    const { dataSource = {} } = this.props;
    return (
      <div>
        {this._renderFormItem(dataSource)}
      </div>
    );
  }
}
