import { useState, useEffect } from 'react';
import Taro from '@tarojs/taro';
import withLayout from '@/layout';
import { ScrollView, View, Text, Block } from '@tarojs/components';
import '@/assets/css/iconfont.css';
import { queryCityList } from '@/services/common';
import { dispatchCitySelected } from '@/actions/city';
import { useSelector, useDispatch } from 'react-redux';
import Search from '@/components/search';
import './index.scss';

export default withLayout(() => {
  const city = useSelector((state) => state.city);
  const dispatch = useDispatch();
  const [list, setList] = useState({});
  const [searchList, setSearchList] = useState([]);
  const [keywords, setKeywords] = useState('');

  useEffect(() => {
    initData()
  }, [])

  function initData() {
    queryCityList().then((cityList) => {
      const t = cityList.reduce((prev, cur) => {
        if (prev[cur.initial]) {
          prev[cur.initial].push(cur)
        } else {
          prev[cur.initial] = [cur]
        }
        return prev
      }, {})

      setList(t)
    })
  }

  function handleSelected(item) {
    dispatchCitySelected(item)(dispatch).then(() => {
      Taro.navigateBack({
        delta: 1,
      })
    })
  }

  const handleSearch = (val) => {
    let t = []
    Object.keys(list).forEach((key) => {
      t = t.concat(list[key].filter((item) => item.name.includes(val)))
    })
    setSearchList(t)
    setKeywords(val)
  }

  const { curCity } = city
  const keys = Object.keys(list)
  return (
    <View className='city'>
      <ScrollView
        style={{
          height: '100vh',
        }}
        scrollY
      >
        <View className='search-wrap'>
          <Search
            placeholder='搜索意向城市'
            onInput={handleSearch}
            onSearch={handleSearch}
          ></Search>
        </View>

        <View className='cur-city'>
          <Text>
            <Text className='iconfont icon-dingwei'></Text>当前城市：
          </Text>
          <Text>{curCity?.name}</Text>
        </View>

        <View className='city-list'>
          {keywords && (
            <View className='search-list' style={{ marginTop: '20rpx' }}>
              {searchList.length > 0 ? (
                searchList.map((item) => (
                  <View
                    key={item.id}
                    className='list-item'
                    onClick={() => handleSelected(item)}
                  >
                    {item.name}
                  </View>
                ))
              ) : (
                <View className='empty'>暂无结果</View>
              )}
            </View>
          )}
          {!keywords &&
            keys.map((key) => (
              <Block key={key}>
                <View className='city-initial'>{key}</View>
                {list[key].map((item) => (
                  <View
                    key={item.id}
                    className='city-item'
                    onClick={() => handleSelected(item)}
                  >
                    {item.shortname}
                  </View>
                ))}
              </Block>
            ))}
        </View>
      </ScrollView>
    </View>
  );
});
