import Taro, { Component } from '@tarojs/taro';
import { connect } from '@tarojs/redux'
import * as actions from '@actions/city'
import { ScrollView } from '@tarojs/components';
import './index.scss'

import Search from '@components/search'

@connect(state => state.city, { ...actions })
export default class Index extends Component {

  config = {
    navigationBarTitleText: '选择城市'
  }

  state = {
    list: {},
    searchList: [],
    keywords: ''
  }

  componentWillMount() {
    this.initData()
  }

  initData() {
    const { cityList } = this.props
    const list = cityList.reduce((prev, cur) => {
      if (prev[cur.initial]) {
        prev[cur.initial].push(cur)
      } else {
        prev[cur.initial] = [cur]
      }

      return prev
    }, {})

    this.setState({
      list
    })
  }

  handleSelected(item) {
    this.props.dispatchCitySelected(item).then(res => {
      Taro.navigateBack({
        delta: 1
      })
    })
  }

  handleSearch = (keywords) => {
    const { cityList } = this.props

    const searchList = cityList.filter(item => (item.name.includes(keywords)))

    this.setState({
      searchList,
      keywords
    })
  }

  render() {
    const { curCity } = this.props
    const { searchList, list, keywords } = this.state
    const keys = Object.keys(list)

    return (
      <View className="city">
        <ScrollView
          style={{
            height: '100vh'
          }}
          scrollY>

          <View className="search-wrap">
            <Search placeholder="搜索意向城市" onInput={this.handleSearch} onSearch={this.handleSearch}></Search>
            {
              keywords && (
                <View className="search-list">
                  {
                    searchList.length > 0 ? (
                      searchList.map(item => (
                        <View key={item.id} className="list-item" onClick={this.handleSelected.bind(this, item)}>{item.name}</View>
                      ))
                    ) : <View className="empty">暂无结果</View>
                  }
                </View>
              )
            }
          </View>
          <View className="cur-city">
            <Text>当前城市：</Text>
            <Text>{curCity.name}</Text>
          </View>
          <View className="city-list">
            {
              keys.map(key => (
                <Block key={key}>
                  <View className="city-initial">{key}</View>
                  {
                    list[key].map(item => (
                      <View key={item.id} className="city-item" onClick={this.handleSelected.bind(this, item)}>{item.shortname}</View>
                    ))
                  }
                </Block>
              ))
            }
          </View>
        </ScrollView>
      </View>
    );
  }
}