import Taro from '@tarojs/taro'
import { View, Input } from '@tarojs/components'
import { AtIcon } from 'taro-ui'

import classNames from 'classnames'
import PropTypes, { InferProps } from 'prop-types'
import CtsComponent from '../../common/component'
import { CommonEvent } from '@tarojs/components/types/common'
import { CtsSearchInputProps, CtsSearchInputState } from 'types/search-input'

/**
 * 搜索输入框组件
 */
export default class CtsSearchInput extends CtsComponent<CtsSearchInputProps, CtsSearchInputState> {
	// static options = {
  //   addGlobalClass: true
	// }

	public static defaultProps: CtsSearchInputProps
  public static propTypes: InferProps<CtsSearchInputProps>

  public constructor(props: CtsSearchInputProps) {
    super(props)
		this.state = {
			inputVal: ''
		}
	}
	
	public componentWillReceiveProps(props: CtsSearchInputProps): void {
		this.setState({ inputVal: props.value })
	}

	// 改变绑定的值
	private changeVal(e: CommonEvent): void {
		this.setState({
			inputVal: e.detail.value
		})
	}

	// 清空input里面的值
	private clear(): void {
		this.setState({
			inputVal: ''
		}, () => {
			this.props.search('')
		})
	}

	// 搜索事件
	private searchBtn(): void {
		this.props.search(this.state.inputVal.trim())
	}

	public render(): JSX.Element {
		let { inputVal } = this.state
		const { className, placeholder, autoFocus, disabled, onFocus } = this.props
		return (
			<View className={classNames('search-input', className)}>
				<AtIcon className='icon' value='search' size='16' color='#C7C7C7'></AtIcon>
				<Input
					className='input-content'
					disabled={disabled}
					value={inputVal}
					onInput={this.changeVal.bind(this)}
					autoFocus={autoFocus}
					onConfirm={this.searchBtn.bind(this)}
					onFocus={onFocus}
					maxLength={30}
					placeholder={placeholder}
					type='text'
				/>
				{
					inputVal &&
					<AtIcon className='icon clear' onClick={this.clear.bind(this, 'inputVal')} value='close-circle' size='16' color='#C7C7C7'></AtIcon>
				}
			</View>
		)
	}
}

CtsSearchInput.defaultProps = {
	value: '',
	placeholder: '',
	disabled: false,
	autoFocus: false,
	search() { },
	onFocus() { }
}

CtsSearchInput.propTypes = {
	value: PropTypes.string,
	placeholder: PropTypes.string,
	disabled: PropTypes.bool,
	autoFocus: PropTypes.bool,
	search: PropTypes.func,
	onFocus: PropTypes.func
}
