import Taro, { Component } from '@tarojs/taro'
import { View, Map } from '@tarojs/components'
import { arrToObj, strTrim } from '@utils'

import './search.scss'

class Index extends Component {

  constructor (props) {
    super(props)
    this.state = {
      keyWord: '',
      searchList: [],
      hotList: [],
      isCloseIconShow: false,
      timer: null,
      historySearch: [],
    }
  }

  config = {
    navigationBarTitleText: '搜索',
  }

  componentWillMount () {
    this.getDtl()
    this.setState({
      historySearch: Taro.getStorageSync('APP_historySearch') || []
    })
  }

  getDtl = () => {
    // Taro.api.house.apiranklist().then(res => {
    //   this.setState({
    //     hotList: res.estate_click_rank || []
    //   })
    // })
    Taro.api.house.apiindexsearchkeyword().then(res => {
      this.setState({
        hotList: res || []
      })
    })
  }

  componentDidShow () { }

  componentDidHide () { }

  renderSearch () {
    const searchImg = require('@img/images/icon_g_search.png')
    const closeIcon = require('@img/icon_g_close.png')
    const { isCloseIconShow, keyWord } = this.state
    return (
      <View className="l-search-show">
        <View className="it-input">
          <View className="l-search-box">
            <Image src={searchImg} className="lsb-icon" />
            <View className="lsb-main">
              <Input className="lsb-input" focus value={keyWord} placeholder="请输入楼盘名称" onInput={this.changeInput.bind(this)} onFocus={this.focusInput.bind(this)}/>
            </View>
            {
              isCloseIconShow
              &&
              <Image src={closeIcon} className="lsb-clear" onClick={this.clearHandle.bind(this)} />
            }
          </View>
        </View>
        <View className="it-text" onClick={this.backPageHandle.bind(this)}>取消</View>
      </View>
    )
  }
  clearHandle () {
    this.setState({
      keyWord: '',
      isCloseIconShow: false,
      historySearch: Taro.getStorageSync('APP_historySearch') || []
    })
  }
  backPageHandle () {
    Taro.navigateBack({
      delta: 1
    })
  }
  focusInput (e) {
    
  }
  handleFormSearch (val) {
    let isCloseIconShow = false
    if (val) {
      isCloseIconShow = true
    } else {
      isCloseIconShow = false
    }
    this.setState({
      isCloseIconShow,
      keyWord: val
    }, () => {
      if (val) {
        let historySearch = Taro.getStorageSync('APP_historySearch') || []
        historySearch.unshift(val)
        const newObj = new Set(historySearch)
        historySearch = Array.from(newObj)
        if (historySearch.length > 10) historySearch.splice(10, 1)
        Taro.setStorageSync('APP_historySearch', historySearch)
        this.setState({
          historySearch
        })
        this.getList()
      }
    })
  }
  changeInput (e) {
    const { timer } = this.state
    const val = strTrim(e.target.value)
    if (timer) {
      clearTimeout(timer)
    }
    let timerNew = setTimeout(() => {
      this.handleFormSearch(val)
    }, 1000)
    this.setState({
      timer: timerNew
    })
  }

  getList () {
    const { keyWord } = this.state
    Taro.api.house.apiindexsearch({estate_name: keyWord}).then(res => {
      this.setState({
        searchList: res.list || []
      })
    })
  }

  renderSearchList () {
    const { searchList, keyWord } = this.state
    const itemLists = searchList.map((item, index) => {
      const keyWordIndex = item.estate_name.indexOf(keyWord)
      const namePrev = strTrim(item.estate_name.substring(0, keyWordIndex))
      const nameNext = item.estate_name.substring(keyWordIndex + keyWord.length, item.estate_name.length)
      return (
        <Navigator url={'/pagesHouse/indexDtl?id=' + item.estate_id + '&fromViews=search'} className="sl-item" key={index}>
          <View className="sl-p1">{namePrev}<View className="t">{keyWord}</View>{nameNext}</View>
          <View className="sl-p2">{item.address}</View>
          <View className="sl-r1">{item.estate_tag}</View>
          <View className="sl-r2">{item.price_range}/㎡</View>
        </Navigator>
      )
    })
    return (
      <View className="search-list">
        {itemLists}
      </View>
    )
  }

  renderMore () {
    const { hotList } = this.state
    const delIcon = require('@img/icon_g_del.png')
    const { historySearch } = this.state
    return (
      <View>
        {
          historySearch.length > 0
          &&
          <View className="search-item">
            <View className="si-title">历史搜索</View>
            <View className="si-clear" onClick={this.delHistoryHandle.bind(this)}>
              <Image src={delIcon} className="icon" />
              删除记录</View>
            <View className="si-content">
              {
                historySearch.map((key, ki) => {
                  return (
                    <View className="si-op" onClick={this.oldKeyHandle.bind(this, key)} key={ki}>{key}</View>
                  )
                })
              }
            </View>
          </View>
        }
        <View className="search-item">
          <View className="si-title">大家都在搜</View>
          <View className="si-content">
            {
              hotList.map((key, ki) => {
                return (
                  <View className="si-op" onClick={this.oldKeyHandle.bind(this, key.estate_name)} key={ki}>{key.estate_name}</View>
                )
              })
            }
          </View>
        </View>
      </View>
    )
  }
  oldKeyHandle (keyWord) {
    this.handleFormSearch(keyWord)
  }
  delHistoryHandle () {
    let that = this
    Taro.$msgConfirm('确定清除历史搜索记录吗？', () => {
      Taro.removeStorage({
        key: 'APP_historySearch',
        success: function (res) {
          Taro.$msg('清除成功~')
          that.setState({
            historySearch: []
          })
        }
      })
    })
  }

  render () {
    const { isCloseIconShow } = this.state
    return (
      <View className="l-box">
        {this.renderSearch()}
        {
          isCloseIconShow
          ?
          this.renderSearchList()
          :
          this.renderMore()
        }
      </View>
    )
  }
}

export default Index
