import { ComponentClass } from 'react';
import Taro, { Component, Config } from '@tarojs/taro';
import { connect } from '@tarojs/redux';

import { View, Text, Input, Image, ScrollView } from '@tarojs/components';
import SearchIcon from '../../images/login/icon_search@2x.png';

import { fetchAllArea, Area } from '../../api/area';
import { UserState, updateUserInfo } from '../../store/rootReducers/userinfo';

import './SelectCampus.scss';
import { shareHandle } from '@/common/shareMethod';

type AreaList = Array<{
  firstPin: string;
  children: Array<Area>;
}>;

type PageStateProps = {
  userinfo: UserState;
};
type PageDispatchProps = {
  updateUserInfo: (e: UserState) => void;
};

type PageState = {
  pinList: Array<string>;
  campusList: AreaList;
  filterList: AreaList;
  filterName: string;
  showToast: boolean;
  localText: string;
  timer: number | undefined;
};

type IProps = PageStateProps & PageDispatchProps;
interface SelectCampus {
  props: IProps;
  state: PageState;
}

@connect(
  ({ userinfo }) => ({
    userinfo,
  }),
  dispatch => ({
    updateUserInfo(entity: UserState) {
      dispatch(updateUserInfo(entity));
    },
  }),
)
class SelectCampus extends Component {
  config: Config = {
    navigationBarTitleText: '检索学校',
  };

  constructor(props: IProps) {
    super(props);
    this.state = {
      filterName: '',
      pinList: [],
      campusList: [],
      filterList: [],
      showToast: false,
      localText: '',
      timer: undefined,
    };
  }
  onShareAppMessage = shareHandle;

  componentWillMount() {
    this.getList();
  }

  getList() {
    fetchAllArea()
      .then(res => {
        console.log(res);
        let initialList = [
          'A',
          'B',
          'C',
          'D',
          'E',
          'F',
          'G',
          'H',
          'I',
          'J',
          'K',
          'L',
          'M',
          'N',
          'O',
          'P',
          'Q',
          'R',
          'S',
          'T',
          'U',
          'V',
          'W',
          'X',
          'Y',
          'Z',
        ];
        let campusIndexArr: Array<string> = [];
        let campusList: AreaList = [];
        res.data.map((area: Area) => {
          let firstPin = area.initial;
          if (firstPin) {
            let index = campusIndexArr.indexOf(firstPin);
            if (index > -1) {
              campusList[index].children.push(area);
            } else {
              let index = initialList.indexOf(firstPin);
              campusIndexArr[index] = firstPin;
              campusList[index] = {
                firstPin: firstPin,
                children: [area],
              };
            }
          }
        });
        this.setState({
          campusList: campusList,
          filterList: campusList,
          pinList: campusIndexArr,
        });
      })
      .catch(err => {
        console.log(err);
      });
  }

  searchList() {
    let { filterName, campusList } = this.state;
    if (filterName) {
      const filterList = campusList.reduce((totalArr: AreaList, campusItem) => {
        let arr = campusItem.children.filter(
          i => i.areaName.indexOf(filterName) > -1,
        );
        if (arr.length > 0) {
          totalArr.push({
            firstPin: campusItem.firstPin,
            children: arr,
          });
        }
        return totalArr;
      }, []);
      this.setState({
        filterList: filterList,
      });
    } else {
      this.setState({
        filterList: campusList,
      });
    }
  }

  showToastHandle(text: string) {
    console.log(text);
    const { timer } = this.state;
    if (timer) {
      clearTimeout(timer);
    }
    const newTimer = setTimeout(() => {
      this.setState({
        showToast: false,
        localText: '',
      });
    }, 1000);
    this.setState({
      showToast: true,
      localText: text,
      timer: newTimer,
    });
  }

  bindCampus({ target: { dataset } }) {
    const { id, areaName }: Area = dataset.campus;

    this.props.updateUserInfo({
      areaId: id,
      areaName: areaName,
    });
    Taro.navigateBack();
  }

  render() {
    const {
      pinList,
      filterList,
      filterName,
      showToast,
      localText,
    } = this.state;
    return (
      <View className='Location topBr'>
        <View className='searchBox'>
          <Input
            className='br8 searchInput'
            value={filterName}
            onInput={({ detail: { value } }) =>
              this.setState({
                filterName: value.trim(),
              })
            }
            type='text'
            placeholder='请输入学校名称'
          />
          <View className='searchBtn' onClick={this.searchList}>
            <Image className='searchIcon' src={SearchIcon} />
            <Text>搜索</Text>
          </View>
        </View>
        <View className='infoBar'>
          {pinList.map(item =>
            item ? (
              <View
                key={item}
                className='infoItem'
                onClick={() => this.showToastHandle(item)}>
                {item}
              </View>
            ) : null,
          )}
        </View>
        <View className={showToast ? 'show br8 infoToast' : 'br8 infoToast'}>
          {localText}
        </View>
        <ScrollView
          scroll-y
          className='locationList'
          scrollIntoView={localText}
          scrollWithAnimation>
          {filterList.map(campusItem =>
            campusItem ? (
              <View key={campusItem.firstPin} className='locationArea'>
                <View id={campusItem.firstPin} className='locationTitle'>
                  {campusItem.firstPin}
                </View>
                {campusItem.children.map(campus => (
                  <View
                    key={campus.id}
                    className='locationItem'
                    data-campus={campus}
                    onClick={this.bindCampus}>
                    {campus.areaName}
                  </View>
                ))}
              </View>
            ) : null,
          )}
        </ScrollView>
      </View>
    );
  }
}

export default SelectCampus as ComponentClass;
