/**
 * 首页地图页
 * @邠心vbe on 2021/08/13
 */
import React, { Component } from 'react';
import { View, Text, Pressable, Image, StyleSheet, BackHandler, Linking } from 'react-native';
import apiBase from '../../api/apiBase';
import apiStation from '../../api/apiStation';
import Dialog from '../../components/Dialog';
import { Styles } from '../../components/Toolbar';
import MyStatusBar from '../../components/MyStatusBar';
import utils from '../../utils/utils';
import { PageList } from '../Router';
import { SettingUtil } from '../Settings';
import BottomSiteInfo from './maps/BottomSiteInfo';
import LocationPermission from './maps/LocationPermission';
import Maps from './maps/Maps';
import SearchTool from './maps/SearchTool';
import app from '../../../app.json'
import { i18nUtil } from '../../i18n';

export default class HomePage extends Component {
  constructor(props) {
    super(props);
    this.state = {
      region: {
        latitude: 1.3532623163977149,
        longitude: 103.87092316860532,
        latitudeDelta: 0.0922,
        longitudeDelta: 0.0421
      },
      mapReady: false,
      stationInfo: {},
      stopList: [],
      hasPermission: isIOS,
      permissionDenied: false
    };
    this.isHide = true;
    this.denied = true;
    this.backSeconds = 0;
    this.refreshTime = 0;
    this.settingInfo = {}
    this.viewIndex = -1;
    this.filter = {
      parkingFee: 'ALL',
      connectorType: ''
    };
  }

  componentDidMount() {
    const navigation = this.props.navigation;
    navigation.addListener('focus', () => {
      //toastShort('onResume')
      this.setState({
        stationInfo: {}
      });
      this.viewIndex = -1;
      SettingUtil.getSettings(set => {
        //console.log("获取设置信息", set);
        this.settingInfo = set;
        this.checkPermission2Geo();
      })
      this.isHide = false;
      //MyStatusBar.setStatusBarThemes(MyStatusBar.DARK_STYLE, colorLight);
    });

    navigation.addListener('blur', () => {
      //toastShort('onStop')
      this.isHide = true;
      //MyStatusBar.setStatusBarThemes(MyStatusBar.LIGHT_STYLE, colorPrimaryDark);
      setTimeout(() => {
        navigation.closeDrawer();
      }, 200);
    });
    
    /*navigation.addListener('beforeRemove', (e) => {
      if (isIOS) {
        e.preventDefault();
      } else {
        let time = new Date().getTime();
        if (time - this.backSeconds < 2000) {
          BackHandler.exitApp();
        } else {
          toastShort("Press the back button again to exit the program");
          this.backSeconds = time;
          e.preventDefault();
        }
      }
    });*/
    BackHandler.addEventListener('hardwareBackPress', this.toExit)
    this.isHide = false;
    //MyStatusBar.setStatusBarThemes(MyStatusBar.DARK_STYLE, colorLight);
    this.checkUpdateVersion();
  }

  componentWillUnmount() {
    /*console.log("componentWillUnmount")
    if (this.unsubscribe) {
      this.unsubscribe();
    }*/
    this.backSeconds = 0;
    BackHandler.removeEventListener("hardwareBackPress", this.toExit)
  }

  toExit = () => {
    //console.log("beforeRemove", this.isHide);
    if (!this.isHide) {
      if (isIOS) {
        //e.preventDefault();
      } else {
        let time = new Date().getTime();
        //console.log("beforeRemove2", time, this.backSeconds);
        if (time - this.backSeconds < 2000) {
          BackHandler.exitApp();
        } else {
          toastShort("Press the back button again to exit the program");
          this.backSeconds = time;
          //e.preventDefault();
        }
      }
      return true;
    }
  }

  checkUpdateVersion() {
    apiBase.checkUpdate().then(res => {
      if (res.data.versionCode > app.versionCode) {
        var desc =  JSON.parse(res.data?.versionDesc ?? "{}");
        if (desc) {
          const upLog = i18nUtil.analyzeLocaleData(desc);
          if (typeof upLog == "string") {
            this.showUpdateDialog({
              title: $t("home.versionUpdate"),
              message: $t("home.newVersionName") + res.data.versionName + "\n\n" + upLog,
              showCancel: !(res.data.force),
              ok: $t("home.updateNow"),
              cancel: $t("home.later"),
              callback: btn => {
                if (btn == Dialog.BUTTON_OK) {
                  //TODO 跳转到应用商店
                  const uri = isIOS
                  ? app.storeUrl.ios
                  : app.storeUrl.android
                  Linking.openURL(uri);
                }
              }
            })
          }
        }
      }
    }).catch(err => {

    })
  }

  showUpdateDialog(options) {
    if (Dialog.isShowing()) {
      setTimeout(() => {
        this.showUpdateDialog(options)
      }, 500);
      return;
    }
    Dialog.showDialog(options)
  }

  getPermission() {
    LocationPermission.requestPermission(hasPermission => {
      if (hasPermission) {
        this.setState({
          hasPermission: true
        });
        this.checkPermission2Geo();
      } else {
        this.noPermissionSite();
      }
    })
  }

  checkPermission2Geo(refresh) {
    if (this.state.hasPermission) {
      if (refresh) {
        //避免关闭自动移动地图后无法点击按钮移动地图
        this.state.stopList = []
      }
      this.infoGeoLocation();
    } else {
      LocationPermission.checkPermission((hasPermission, canRequestPermission) => {
        if (hasPermission) {
          this.setState({
            hasPermission: true
          });
          this.infoGeoLocation();
        } else {
          if (canRequestPermission) {
            if (this.denied) {
              this.denied = false;
              this.getPermission();
            } else {
              //避免多次请求
              this.denied = true;
              this.noPermissionSite();
            }
          } else {
            this.noPermissionSite();
          }
        }
      })
    }
  }

  noPermissionSite() {
    console.log("未获取权限也获取站点列表");
    this.setState({
      hasPermission: false,
      permissionDenied: true
    });
    let first = this.state.stopList.length == 0;//是否第一次加载
    this.getStationList(this.state.region, first);
  }

  /**
   * 获取定位数据
   * @param {*} again 
   */
  infoGeoLocation(again) {
    if (this.state.mapReady) {
      navigator.geolocation.getCurrentPosition(location => {
        let region = {
          latitude: location.coords.latitude,
          longitude: location.coords.longitude,
          latitudeDelta: 0.0922,
          longitudeDelta: 0.0421
        }
        //console.log("getGeoLocation", region);
        //if (this.state.stopList.length == 0) { //只加载一次
        let time = new Date().getTime();
        let interval = this.settingInfo.refreshInterval * 1000;//重复加载时间
        let first = this.state.stopList.length == 0;//是否第一次加载
        if (first || time - this.refreshTime > interval) { //一分钟(10秒)加载一次
          this.getStationList(region, first);
          this.refreshTime = time;
        } else if (this.settingInfo.moveMyLocation) {
          this.setState({
            region: region
          });
        }
      }, error => {
        console.info("getGeoLocation", error);
        if (!again) {
          setTimeout(() => {
            this.infoGeoLocation(true);
          }, 2000);
        }
      });
    }
  }

  findFilter(data) {
    this.filter = data;
    this.getStationList();
  }

  /**
   * 获取所有充电桩
   * @param {Location} region 当前位置
   * @param {boolean} first 是否初始化
   */
  getStationList(region, first) {
    if (!isIOS)
      Dialog.showProgressDialog();
    if (getUserId()) {
      this.filter.operaUserId = getUserId()
    }
    apiStation.getAllStation(this.filter).then(res => {
      if (!isIOS)
        Dialog.dismissLoading();
      if (res.data.sites) {
        const list = [];
        res.data.sites.forEach(item => {
          let available = false
          if (item.allConnector && item.allConnector.available) {
            available = true
          }
          list.push({
            id: item.sitePk,
            name: item.siteName,
            //address: item.siteAddress,
            available: available,
            siteType: item.siteType,
            latitude: item.locationLatitude,
            longitude: item.locationLongitude,
            favorite: item?.favorite ? true : false,
            upcoming: false
            /*acConnector: item.acConnector,
            allConnector: item.allConnector,
            dcConnector: item.dcConnector,
            distance: utils.getDistance(item.distance)*/
          });
        });
        this.setState({
          stopList: list
        });
        //this.viewChargeStation(list[0].id) //测试显示站点
        if (region && (this.settingInfo.moveMyLocation || first)) {
          setTimeout(() => {
            this.setState({
              region: region
            });
          }, 500);
        }
      }
    }).catch(err => {
      if (!isIOS)
        Dialog.dismissLoading();
      toastShort(err);
      this.setState({
        stopList: []
      });
    })
  }

  //点击Marker获取StaionInfo
  viewChargeStation(id) {
    //console.log('info', this.state.stopList[index]);
    //const stationInfo = this.state.stopList[index];
    if (app.modules.bookmarks) {
      for (let i = 0; i < this.state.stopList.length; i++) {
        let info = this.state.stopList[i];
        if (info.id == id) {
          this.viewIndex = i;
          break;
        }
      }
    }
    if (this.state.hasPermission) {
      navigator.geolocation.getCurrentPosition(location => {
        let region = {
          latitude: location.coords.latitude,
          longitude: location.coords.longitude,
          latitudeDelta: 0.0922,
          longitudeDelta: 0.0421
        }
        this.getStationInfo(id, region);
        /*if (this.settingInfo.alwaysLocation) {
          this.setState({
            region: region
          });
        }*/
      });
    } else {
      //无定位权限仍然显示
      this.getStationInfo(id, this.state.region);
    }
    //startPage(PageList.chargeDetail, {...this.state.stopList[index]});
  }

  getStationInfo(id, location) {
    apiStation.getStationRate({
      sitePk: id,
      lat: location?.latitude,
      lng: location?.longitude
    }).then(res => {
      if (res.data.sitePk) {
        var info = utils.getSiteInfo(res.data);
        this.setState({
          stationInfo: info
        });
      } else {
        this.setState({
          stationInfo: {}
        });
      }
    }).catch(err => {
      this.setState({
        stationInfo: {}
      });
      toastShort(err);
    });
  }

  favoriteSite() {
    if (this.state.stationInfo?.id) {
      Dialog.showProgressDialog();
      apiStation.bookmarkSite(this.state.stationInfo.id).then(res => {
        const info = {...this.state.stationInfo, favorite: !this.state.stationInfo.favorite}
        if (this.viewIndex >= 0) {
          const list = [...this.state.stopList]
          const inf = {...list[this.viewIndex], favorite: info.favorite};
          list[this.viewIndex] = inf;
          this.setState({
            stopList: list,
            stationInfo: info
          });
        } else {
          this.setState({
            stationInfo: info
          });
        }
      }).catch(err => {
        toastShort(err);
        console.log(err)
      }).finally(() => {
        Dialog.dismissLoading();
      })
    }
  }

  render() {
    return (
      <View style={ui.flex1}>
        <View style={Styles.toolbar}>
          <Pressable
            style={Styles.backIcon}
            android_ripple = {rippleLess}
            onPress={() => {
              this.props.navigation.toggleDrawer();
            }}>
            <EvilIcons name={'navicon'} size={28} color={colorPrimary} />
          </Pressable>
          <View style={styles.logoView}>
            <Image
              source={require('../../images/tool-logo.png')}
              style={Styles.logo}
              resizeMode="contain"
            />
          </View>
          {/* <Text style={ui.flex1}></Text> */}
          <Pressable
            style={Styles.backIcon}
            android_ripple = {rippleLess}
            onPress={() => startPage(PageList.scanqr, {actionDetail: true})}>
            <MaterialCommunityIcons
              name='line-scan'
              size={20}
              color={colorPrimary}
            />
          </Pressable>
        </View>
        <SearchTool
          count={this.state.stopList.length}
          mapReady={this.state.mapReady}
          onFilter={data => this.findFilter(data)}
          onLocation={() => this.checkPermission2Geo(true)}
          navigation={this.props.navigation}
        />
        <View style={styles.mapContent}>
          {/* this.state.hasPermission &&*/}
          <Maps.Maps3
            region={this.state.region}
            stopList={this.state.stopList}
            onMapReady={() => {
              this.setState({
                mapReady: true
              }, () => {
                this.checkPermission2Geo();
              });
            }}
            onMarkerPress={id => this.viewChargeStation(id)}
            showUserLocation={this.state.hasPermission && this.settingInfo.alwaysLocation}
          />
          <BottomSiteInfo
            stationInfo={this.state.stationInfo}
            onFavorite={() => this.favoriteSite()}
          />
          <LocationPermission.VIEW visible={this.state.permissionDenied}/>
        </View>
        <View style={styles.drawerLeftTouchView}></View>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  logoView: {
    /*left: 0,
    right: 0,
    bottom: 0,
    zIndex: 1,
    alignItems: 'center',
    position: 'absolute',*/
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center'
  },
  searchView: {
    ...$padding(8, 16, 16),
    backgroundColor: colorThemes
  },
  searchInput: {
    alignItems: 'center',
    borderWidth: 1,
    borderStyle: 'solid',
    borderRadius: 60,
    borderColor: colorAccent,
    flexDirection: 'row',
    paddingLeft: 16,
    paddingRight: 16,
    backgroundColor: 'rgba(255, 255, 255, 0.5)'
  },
  searchText: {
    flex: 1,
    color: '#444',
    padding: 8,
    fontSize: 15
  },
  drawerLeftTouchView: {
    top: 0,
    left: 0,
    bottom: 0,
    width: 4,
    zIndex: 5,
    position: 'absolute',
    backgroundColor: 'rgba(0,0,0,0)'
  },
  mapContent: {
    flex: 1,
    zIndex: 4,
    position: 'relative',
  }
})