import React, { useMemo, useState } from 'react'
import { DownOutlined } from '@ant-design/icons'
import { useSize,useDebounce } from 'ahooks';
import './MoreChoose.less'

const MoreChoose = (props) => {
	const { value, mode = 'multiple', options, onChange } = props
	const tipRef = React.createRef()
	const [isMore, setIsmore] = useState(false)
	const currentOptions = useMemo(() => {
		return [{ label: '全部', value: '' }, ...options]
	}, [options])
	const tipSize = useSize(tipRef);

	const boxHeight= useDebounce(tipSize?.height,{wait:500})

	const containerHeight = useMemo(() => {
		return isMore ? boxHeight + 'px' : '32px'
	}, [boxHeight, isMore])
	
	const click = (e) => {
		if (e === '') {
			onChange([])
		} else {
			if (mode === 'multiple') {
				const val = [...value]
				const exsitsIndex = val.findIndex(o => o === e)
				exsitsIndex === -1 ? val.push(e) : val.splice(exsitsIndex, 1)
				onChange(val)
			} else {
				onChange([e])
			}
		}
	}
	const changeMore = () => {
		setIsmore(!isMore)
	}


	return <div className={`MoreChoose`}>
		<div className='MoreChoose-container' style={{ height: containerHeight }}>
			{
				currentOptions.map(o => <span
					key={o.value}
					className={`MoreChoose-choose ${(o.value === '' && value.length === 0) || value.includes(o.value) ? 'active' : ''}`}
					onClick={click.bind(null, o.value)}
				>
					{o.label}
				</span>)
			}
		</div>
		<div className='MoreChoose-container-tip' ref={tipRef}>
			{
				currentOptions.map(o => <span
					key={o.value}
					className={`MoreChoose-choose`}
				>
					{o.label}
				</span>)
			}
		</div>
		{boxHeight > 42 ? <div className={`more-btn  ${isMore ? 'isMore' : ''}`} onClick={changeMore}>{isMore ? '收起' : '展开'}<DownOutlined className='icon' /></div>:null}
	</div>
}
export default MoreChoose