/**
 * imui.Checkbox
 * @author riverhan
 * @date 2016-9-7
 */
import React from 'react';
import classnames from 'classnames';
import PropTypes from 'prop-types';
// @require '../style/index.scss'

class Checkbox extends React.Component {
  static propTypes = {
    /**
     * 是否选中
     */
    checked: PropTypes.bool,
    /**
     * 是否允许勾选
     */
    disabled: PropTypes.bool,
    /**
     * 改变选中状态时回调
     */
    onChange: PropTypes.func,
    /**
     * 选择器自定义类名
     */
    className: PropTypes.string,
  };

  state = {
    checked: this.props.checked,
  };

  componentWillReceiveProps(nextProps) {
    const { checked } = nextProps;

    if (checked !== undefined) { // 没有显式地传bool值过来时不重置state
      this.setState({
        checked: nextProps.checked,
      });
    }
  }

  onClick = (event) => {
    const { onChange, disabled } = this.props;
    const { checked } = this.state;

    if (disabled) {
      return;
    }

    this.setState({
      checked: !checked,
    });

    if (onChange) {
      onChange(!checked);
    }

    event.stopPropagation();
  };

  getValue = () => {
    return this.state.checked;
  }

  render() {
    const { children, disabled, className, style } = this.props;
    const { checked } = this.state;
    return (
      <span
        className={classnames({
          'im-checkbox': true,
          checked,
          disabled,
        }, className)}
        onClick={this.onClick}
        style={style}
      >
        <i className="im-checkbox-icon" />
        <span>
          {children}
        </span>
      </span>
    );
  }
}


export default Checkbox;

