/**
 * imui.Radio
 * @author moxhe
 * @date 2016-08-22
 */
import React from 'react';
import classnames from 'classnames';
import PropTypes from 'prop-types';
// @require '../style/index.scss'

export default class Radio extends React.Component {
  static propTypes = {
    /**
     * 是否选中
     */
    checked: PropTypes.bool,
    /**
     * 是否可用
     */
    disabled: PropTypes.bool,
    /**
     * radio的值
     */
    value: PropTypes.oneOfType([
      PropTypes.string,
      PropTypes.number,
    ]).isRequired,
    /**
     * 点击回调函数
     */
    onChange: PropTypes.func,
  };

  static defaultProps = {
    prefixCls: 'im-radio',
    iconCls: 'im-radio-icon',
    textCls: 'im-radio-text',
    checked: false,
    disabled: false,
  };

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

  componentWillReceiveProps(nextProps) {
    if (nextProps.checked !== this.props.checked) {
      this.setState({
        checked: nextProps.checked,
      });
    }
  }

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

    if (!onChange) {
      // 单独使用时
      if (!checked) {
        this.setState({ checked: true });
      }
    } else {
      onChange(value);
    }
  };

  render() {
    const {
      iconCls,
      prefixCls,
      textCls,
      className,
      disabled,
      children,
      style,
    } = this.props;

    const { checked } = this.state;

    const allCls = {
      [className]: !!className,
      [prefixCls]: true,
      [`${prefixCls}--checked`]: checked,
      [`${prefixCls}--disabled`]: disabled,
    };

    return (
      <label
        style={style}
        className={classnames(allCls)}
        onClick={this.onClick}
      >
        <i className={iconCls} />
        <span className={textCls}>
          {children}
        </span>
      </label>
    );
  }
}
