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

class CheckGroup extends React.Component {

  static propTypes = {
    /**
     * 提供选项列表:数组中每个对象需要包含labelKey(默认是id),idKey(默认是label)
     */
    options: PropTypes.arrayOf(PropTypes.object), // 要展示的check列表
    /**
     * 列表状态改变时的回调函数
     */
    onChange: PropTypes.func, // 选中列表发生改变时的回调函数
    /**
     * 指定已选中的id列表
     */
    value: PropTypes.arrayOf(PropTypes.oneOfType([ // 已选中的id列表
      PropTypes.string,
      PropTypes.number,
      PropTypes.symbol,
    ])),
    /**
     * 作为id的属性名称
     */
    idKey: PropTypes.string, // 作为id的属性名称
    /**
     * 作为label的属性名称
     */
    labelKey: PropTypes.string, // 作为label的属性名称
    /**
     * 是否以inline方式展示
     */
    inline: PropTypes.bool, // 是否将checkbox展示为行为元素
    /**
     * 选择器自定义类名
     */
    className: PropTypes.string, // 选择器自定义className
  };

  static defaultProps = {
    value: [],
    idKey: 'id',
    labelKey: 'label',
    onChange: () => {
    },
    inline: true,
  };

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

  componentWillReceiveProps(nextProps) {
    const value = nextProps.value || [];
    this.setState({
      value: value.concat(),
    });
  }

  gethandleCheck = (id) => {
    return (isChecked) => {
      let checkList = this.state.value.concat();
      const index = checkList.indexOf(id);
      const { onChange } = this.props;

      if (isChecked && index === -1) {
        checkList.push(id);
      } else if (!isChecked && index > -1) {
        checkList.splice(index, 1);
      }

      this.setState({
        value: checkList,
      });

      if (typeof onChange === 'function') {
        onChange(checkList.concat());
      }
    };
  };

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

  render() {
    const {
      options,
      idKey,
      labelKey,
      inline,
      className,
    } = this.props;
    const { value } = this.state;


    return (
      <ul className={classnames('im-checkgroup', className)}>
        {options.map((option) => {
          const { disabled } = option;
          const label = option[labelKey];
          const id = option[idKey];

          return (
            <li
              className={classnames({
                'im-checkgroup-item': true,
                'im-checkgroup-item--inline': inline,
              })}
              key={id}
            >
              <Checkbox
                checked={value.indexOf(id) >= 0}
                disabled={disabled}
                onChange={this.gethandleCheck(id)}
              >
                {label}
              </Checkbox>
            </li>
          );
        })}
      </ul>
    );
  }
}


export default CheckGroup;

