/**
 * imui.RadioGroup
 * @author moxhe
 * @date 2016-08-22
 */

import React from 'react';
import classnames from 'classnames';
import PropTypes from 'prop-types';
import Radio from './Radio';
// @require '../style/index.scss'

export default class RadioGroup extends React.Component {
  static propTypes = {
    /**
     * 排布类型是否选择inline样式
     */
    inline: PropTypes.bool,
    /**
     * 是否可用
     */
    disabled: PropTypes.bool,
    /**
     * 值改变时触发的回调函数
     */
    onChange: PropTypes.func,
    /**
     * 当前值
     */
    value: PropTypes.oneOfType([
      PropTypes.string,
      PropTypes.number
    ])
  };

  static defaultProps = {
    prefixCls: 'im-radio-group',
    defaultValue: null,
    inline: true
  };

  constructor(props) {
    super(props);
    let value = props.value;
    if (value === undefined) {
      value = props.defaultValue;
    }
    this.state = { value };
  }

  componentWillReceiveProps(nextProps) {
    const { value } = this.state;
    const nextValue = nextProps.value;

    if (nextValue !== undefined && value !== nextValue) {
      this.setState({
        value: nextValue
      });
    }
  }

  getValue = () => {
    return this.state.value || this.props.defaultValue;
  };

  setValue = (nextValue) => {
    if (this.state.value !== nextValue) {
      // 保证组件本身状态
      this.setState({
        value: nextValue
      });

      if (this.props.onChange) {
        this.props.onChange(nextValue);
      }
    }
  };

  render() {
    const { value } = this.state;
    const {
      className,
      prefixCls,
      inline,
      disabled,
      ...others
    } = this.props;
    delete others.defaultValue;

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

    // 需保证Radio为直接子组件
    const children = React.Children.map(this.props.children, (radio) => {
      if (radio && (radio.type === Radio) && radio.props) {
        const keyProps = {};

        if (!('key' in radio) && typeof radio.props.value === 'string') {
          keyProps.key = radio.props.value;
        }

        return React.cloneElement(radio, {
          ...keyProps,
          ...radio.props,
          onChange: this.setValue,
          // 通过对子组件Radio来实现默认值无效
          checked: radio.props.value === value,
          disabled: radio.props.disabled || disabled
        });
      }

      return radio;
    });

    return (
      <div {...others} className={classnames(allCls)}>{children}</div>
    );
  }
}
