import React, { Component } from 'react';
import { Form, Checkbox } from 'antd'

let defaultItemLabelName = 'label'
let defaultItemValueName = 'value'

class CheckBoxGroup extends Component {

	constructor(props) {
		super(props)
		this.valueMap = props.initialValueArray.slice(0) || []// 也要初始化antd form initialValue
		this.options = undefined;
	}
	handleChange = (index, value) => event => {
		this.valueMap[index] = event.target.checked ? value : ''
		this.props.onChange && this.props.onChange(this.valueMap)
	};
	componentWillReceiveProps(newProps, newContext) {
		if (newProps.initialValueArray && (!this.props.initialValueArray
			|| (newProps.initialValueArray.join('') !== this.props.initialValueArray.join('')))) {
			this.valueMap = newProps.initialValueArray.slice(0) || [];
		}
	}

	render() {
		const { options, itemLabelName, itemValueName, itemLabelFunction, itemValueFunction } = this.props;
		const newItemLabelName = itemLabelName || defaultItemLabelName
		const newItemValueName = itemValueName || defaultItemValueName
		this.options = options;
		return (
			<Form.Item>
				<Checkbox.Group>

				</Checkbox.Group>
				{options.map((option, index) => {
					const val = itemValueFunction ? itemValueFunction(option, index) : option[newItemValueName];
					return (<Checkbox key={index}
						checked={this.valueMap[index]}
						value={val}

						onChange={this.handleChange(index, val)}
						color="primary"
						classes={{
							root: this.props.classes.radio,
							checked: this.props.classes.checked
						}}
					>itemLabelFunction ? itemLabelFunction(option, index) : option[newItemLabelName]</Checkbox>)
				})
				}
			</Form.Item>
		);
	}
}


export default CheckBoxGroup;
