import React from 'react';
import { Tree } from 'antd';

const TreeNode = Tree.TreeNode;

export default class PermTree extends React.Component {
	constructor(props) {
		super(props);
		const value = props.value || {};
		this.state = {
			expandedKeys: [],
			autoExpandParent: true,
			ids: value.ids,
		};
	}

	onExpand = (expandedKeys) => {
		console.log('onExpand', expandedKeys);
		// if not set autoExpandParent to false, if children expanded, parent can not collapse.
		// or, you can remove all expanded children keys.
		this.setState({
			expandedKeys,
			autoExpandParent: false,
		});
	};

	onCheck = (ids) => {
		if (!('value' in this.props)) {
			this.setState({ ids });
		}
		this.triggerChange({ ids });
	};

	triggerChange = (changedValue) => {
		// Should provide an event to pass value to Form.
		const onChange = this.props.onChange;
		if (onChange) {
			onChange(Object.assign({}, this.state, changedValue));
		}
	};
	componentWillReceiveProps(nextProps) {
		// Should be a controlled component.
		if ('value' in nextProps) {
			const value = nextProps.value;
			this.setState(value);
		}
	}

	renderTreeNodes = (data) => {
		return data.map((item) => {
			if (item.children) {
				return (
					<TreeNode title={item.title} key={item.key} dataRef={item}>
						{this.renderTreeNodes(item.children)}
					</TreeNode>
				);
			}
			return <TreeNode {...item} />;
		});
	};

	render() {
		return (
			<Tree
				checkable
				selectable={false}
				onExpand={this.onExpand}
				expandedKeys={this.state.expandedKeys}
				autoExpandParent={this.state.autoExpandParent}
				onCheck={this.onCheck}
				checkedKeys={this.state.ids}>
				{this.renderTreeNodes(this.props.all)}
			</Tree>
		);
	}
}