/**
 * 搜索页
 * @邠心vbe on 2021/04/12
 */
import React, { Component } from 'react';
import { View, Text, StyleSheet, TextInput, FlatList, Pressable, Linking, Image } from 'react-native';
import apiStation from '../../api/apiStation';
import TextRadius from '../../components/TextRadius';
import utils from '../../utils/utils';
import Provider from '../charge/Provider';
import { PageList } from '../Router';

export default class Search extends Component {
  constructor(props) {
    super(props);
    this.state = {
      isSearch: false,
      searchResult: [{id:0}]
    };
  }

  componentDidMount() {
    this.getGeoLocation();
  }

  getGeoLocation() {
    navigator.geolocation.getCurrentPosition(location => {
      let latlng = {
        lat: location.coords.latitude,
        lng: location.coords.longitude
      }
      this.searchStation(latlng);
    }, error => {
      console.warn("getGeoLocation", error);
    });
  }

  searchStation(latlng) {
    this.setState({
      isSearch: true
    });
    latlng.siteName = this.searchWorld
    apiStation.searchStation(latlng).then(res => {
      if (res.data.sites) {
        const list = [];
        res.data.sites.forEach(item => {
          list.push({
            id: item.sitePk,
            name: item.siteName,
            address: item.siteAddress,
            latitude: item.locationLatitude,
            longitude: item.locationLongitude,
            acConnector: item.acConnector,
            allConnector: item.allConnector,
            dcConnector: item.dcConnector,
            siteType: item.siteType,
            distance: utils.getDistance(item.distance),
            serviceProvider: item.serviceProvider
          });
        });
        this.setState({
          isSearch: false,
          searchResult: list
        });
      }
    }).catch(err => {
      console.log('err', err);
      this.setState({
        isSearch: false,
        searchResult: []
      });
    });
  }

  intoStation(info) {
    startPage(PageList.chargeDetail, {stationInfo: info, action: 'search'});
  }

  listItem = ({item, index, separators}) => {
    if (item.id) {
      return (
        <View 
          style={styles.itemView}
          key={index}>
          <Pressable
            style={styles.stationInfo}
            onPress={() => this.intoStation(item)}>
            <View style={styles.nameView}>
              <Text style={styles.stationName}>{item.name}</Text>
              { item.allConnector && item.allConnector.available > 0 &&
                <TextRadius style={[styles.infoStatus, styles.available]}>Available</TextRadius>
              }
            </View>
            <Provider providers={item.serviceProvider}/>
            <Text style={styles.stationAddress}>{item.address}</Text>
            <View style={styles.connectView}>
              <ConnectType {...item.acConnector}/>
              <ConnectType {...item.dcConnector}/>
            </View>
          </Pressable>
          <Pressable 
            style={styles.directView}
            onPress={() => {
              utils.directMaps(item.latitude, item.longitude, item.address);
            }}>
            <MaterialIcons
              name='directions'
              size={32}
              color={colorAccent}/>
            <Text style={styles.distanceText}>{item.distance}</Text>
          </Pressable>
        </View>
      );
    } else {
      return null;
    }
  }

  render() {
    return (
      <View style={styles.container}>
        <View style={styles.searchView}>
          <Feather
            name={'search'}
            size={20}
            color={'#999'}/>
          <TextInput
            style={styles.searchInput}
            autoFocus={true}
            maxLength={50}
            numberOfLines={1}
            returnKeyType={'search'}
            clearButtonMode={'while-editing'}
            placeholder='Search using location name or service provider'
            placeholderTextColor={textPlacehoder}
            onChangeText={text => {
              this.searchWorld = text;
            }}
            onSubmitEditing={() => {
              this.getGeoLocation();
            }}/>
        </View>
        { this.state.isSearch
        ? <View style={styles.searchingView}>
            <Image
              style={styles.seachingIcon}
              source={require('../../images/icon/loading.gif')}/>
          </View>
        : <FlatList
            style={styles.listView}
            data={this.state.searchResult}
            renderItem={this.listItem}
            keyExtractor={item => item.id}
            ListEmptyComponent={<Text style={styles.noResult}>No search result</Text>}
          />
        }
      </View>
    );
  }
}

export const ConnectType = ({type, available, all}) => {
  if (type) {
    return (
      <View style={styles.connectType}>
        <Text style={styles.typeLabel}>{type}</Text>
        <Text style={styles.typeContent}><Text style={styles.typeBold}>{available}</Text>/{all}</Text>
      </View>
    );
  } else {
    return null;
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: 'white'
  },
  searchView: {
    marginTop: 16,
    marginLeft: 16,
    marginRight: 16,
    marginBottom: 8,
    paddingLeft: 16,
    paddingRight: 16,
    borderRadius: 60,
    alignItems: 'center',
    flexDirection: 'row',
    backgroundColor: '#F5F5F5'
  },
  searchInput: {
    flex: 1,
    color: '#333',
    ...$padding(6, 8),
    fontSize: 15,
    marginLeft: 4,
  },
  searchingView: {
    padding: 16,
    alignItems: 'center'
  },
  seachingIcon: {
    width: 60,
    height: 60
  },
  noResult: {
    color: '#999',
    fontSize: 14,
    padding: 20,
    textAlign: 'center',
  },
  listView: {
    flex: 1
  },
  itemView: {
    alignItems: 'center',
    flexDirection: 'row',
    borderBottomWidth: 1,
    borderBottomColor: '#eee'
  },
  stationInfo: {
    flex: 1,
    padding: 16
  },
  nameView: {
    paddingTop: 3,
    alignItems: 'center',
    flexDirection: 'row'
  },
  stationName: {
    color: '#333',
    fontSize: 18,
    fontWeight: 'bold'
  },
  stationAddress: {
    color: '#666',
    fontSize: 14,
    paddingBottom: 8
  },
  infoStatus: {
    fontSize: 10,
    paddingTop: 3,
    paddingLeft: 8,
    paddingRight: 8,
    paddingBottom: 3,
    borderRadius: 5,
    marginLeft: 12,
  },
  selected: {
    color: '#333',
    backgroundColor: colorAccent
  },
  available: {
    color: 'white',
    backgroundColor: '#90DB0A'
  },
  unavailable: {
    color: '#999',
    fontSize: 10.5,
    paddingTop: 7,
    paddingLeft: 9,
    paddingRight: 9,
    paddingBottom: 7,
    backgroundColor: '#CCC'
  },
  connectView: {
    paddingTop: 4,
    paddingBottom: 4,
    alignItems: 'center',
    flexDirection: 'row'
  },
  connectType: {
    borderWidth: 1,
    borderColor: '#333',
    borderRadius: 3,
    marginRight: 16,
    alignItems: 'center',
    flexDirection: 'row',
  },
  typeLabel: {
    color: '#fff',
    fontSize: 12,
    paddingTop: 2,
    paddingLeft: 10,
    paddingRight: 10,
    paddingBottom: 2,
    backgroundColor: '#333'
  },
  typeContent: {
    color: '#333',
    fontSize: 12,
    paddingLeft: 10,
    paddingRight: 6,
  },
  typeBold: {
    fontSize: 14,
    fontWeight: 'bold'
  },
  directView: {
    zIndex: 1,
    paddingTop: 4,
    paddingRight: 16,
    alignItems: 'center'
  },
  distanceText: {
    color: '#333',
    fontSize: 12,
    paddingTop: 2
  },
});