import React, { PureComponent } from 'react'
import { SearchBar } from 'antd-mobile'
import { withRouter } from 'react-router-dom'
import classnames from 'classnames';

import './search_header.scss'

class SearchHead extends PureComponent {
    
    state = {
        isFocus: false
    }

    returnPage = () => {
        this.props.history.go(-1)
    }

    componentDidMount() {
        this.refs.search.focus();
    }

    search = () => {
        this.storeKeyword()
        this.props.handleSearch()
    }

    storeKeyword = () => {
        let {searchHistory = [], value} = this.props
        value && localStorage.setItem('searchHistory', JSON.stringify([...searchHistory, value]))
    }

    changeFontColor = (isFocus) => {
        this.setState({
            isFocus
        });
    }

    render() {
        const { isFocus } = this.state;
        const cls = classnames('submit-btn', {'submit-btn--active': isFocus})
        return (
            <div className="search-head" style={this.props.style} ref={this.props.forwardedRef}>

                <div className="left" onClick={this.returnPage}>
                    <i className="iconfont iconiconfront-68"/>
                </div>

                <div className="center">
                    <SearchBar
                        value={this.props.value}
                        showCancelButton
                        cancelText={" "}
                        ref="search"
                        focus={true}
                        onChange={this.props.handleChange}
                        placeholder="搜索课程"
                        onFocus={() => this.changeFontColor(true)}
                        onBlur={() => this.changeFontColor(false)}
                        onSubmit={this.search}
                    />
                </div>
                <div className="right right-btn" onClick={this.search}>
                    <div className={cls}>搜索</div>
                </div>
            </div>
        )
    }
}

export default withRouter(SearchHead)