import { PureComponent } from 'react'
import { TreeSelect } from 'antd'
const { TreeNode } = TreeSelect

class SelectEbookArticleTypeTree extends PureComponent {
	state = {
		value: undefined,
		treeData: [
			{ title: '分类', key: '000000000000', id: '000000000000', levelcode: '000000000000', value: '000000000000' }
		]
	}

	constructor(props) {
		super(props)
		this.state.value = props?.value
	}

	onChange = (value, label, extra) => {
		if (extra.key !== '000000000000') {
			const { selectedEbookArticleTypeTreeValue } = this.props
			selectedEbookArticleTypeTreeValue({key: value, label: label[0]})
			this.setState({ value: {label: label[0]} })
		}
	}

	onSelect = value => {

	}

	onTreeExpand = expandedKeys => {

	}

	updateTreeData(list, key, children) {
		return list.map(node => {
			if (node.key === key) {
				return {
					...node,
					key: node.id,
					value: node.value,
					children
				}
			} else if (node.children) {
				return {
					...node,
					key: node.id,
					value: node.value,
					children: this.updateTreeData(node.children, key, children)
				}
			}

			return node
		})
	}

	onLoadData = ({id, key, children}) => {
		const { dispatch } = this.props
		const params = {
			parentid: id
		}

		return new Promise((resolve) => {
			if (children) {
				resolve()
				return
			}

			dispatch({
				type: 'globaldata/get_proebookarticletypetree_by_parentid',
				payload: params,
				callback: (res) => {
					if(res.success === true) {
						// treeNode.props.dataRef.children = res.list
						this.setState({
							treeData: this.updateTreeData(this.state.treeData, key, res.list)
						})

						resolve()
					}
				}
			})
		})
	}

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

			return <TreeNode {...item} value={item.key} dataRef={item} title={item.title} key={item.key} />
		})

	render() {
		const { value } = this.props
		const { treeData } = this.state

		return (
			<TreeSelect
				showSearch
				value={value?.label}
				dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
				placeholder='请选择分类'
				treeDefaultExpandAll
				onSelect={this.onSelect}
				onChange={this.onChange}
				onTreeExpand={this.onTreeExpand}
				loadData={this.onLoadData}
				treeData={treeData}
			/>
		)
	}
}

export default SelectEbookArticleTypeTree
