/** * 首页地图页 * @邠心vbe on 2021/08/13 */ import React, { Component } from 'react'; import { View, Text, Pressable, Image, StyleSheet, BackHandler, Linking } from 'react-native'; import {check, request, openSettings, PERMISSIONS, RESULTS} from 'react-native-permissions'; import apiBase from '../../api/apiBase'; import apiStation from '../../api/apiStation'; import Dialog from '../../components/Dialog'; import { Styles } from '../../components/Toolbar'; import utils from '../../utils/utils'; import { PageList } from '../Router'; import { SettingUtil } from '../Settings'; import BottomSiteInfo from './maps/BottomSiteInfo'; import Maps from './maps/Maps'; import SearchTool from './maps/SearchTool'; import app from '../../../app.json' 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 }; this.isHide = true; this.denied = true; this.backSeconds = 0; this.refreshTime = 0; this.settingInfo = {} //this.unsubscribe = null; this.filter = { parkingFee: 'ALL', connectorType: '' }; } componentDidMount() { console.log("componentDidMount") const navigation = this.props.navigation; navigation.addListener('focus', () => { //toastShort('onResume') this.setState({ stationInfo: {} }); SettingUtil.getSettings(set => { console.log("获取设置信息", set); this.settingInfo = set; this.checkPermission2Geo(); }) console.log("focus"); this.isHide = false; }); navigation.addListener('blur', () => { //toastShort('onStop') this.isHide = true; setTimeout(() => { navigation.closeDrawer(); }, 200); }); /*this.unsubscribe = navigation.addListener('beforeRemove', (e) => { this.toExit(e); });*/ BackHandler.addEventListener('hardwareBackPress', this.toExit) this.isHide = false; this.checkUpdateVersion(); } /*componentDidUpdate() { console.log("componentDidUpdate", this.unsubscribe); if (!this.unsubscribe) { this.unsubscribe = this.props.navigation.addListener('beforeRemove', (e) => { this.toExit(e); }); } }*/ 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 && typeof desc.en == "string") { Dialog.showDialog({ title: "Version Update", message: "New Version: " + res.data.versionName + "\n\n" + desc.en, showCancel: !(res.data.force), ok: "UPDATE NOW", cancel: "LATER", callback: btn => { if (btn == Dialog.BUTTON_OK) { //TODO 跳转到应用商店 const uri = isIOS ? 'itms-appss://apps.apple.com/app/id1664718768' : 'market://details?id=com.strides.chargeco' Linking.openURL(uri); } } }) } } }).catch(err => { }) } getPermission() { request( isIOS ? PERMISSIONS.IOS.LOCATION_WHEN_IN_USE : PERMISSIONS.ANDROID.ACCESS_FINE_LOCATION) .then(res => { console.log('getPermission', res) this.setState({ hasPermission: true }); this.checkPermission2Geo(); }).catch(err => { console.info('getPermission', err) }); } checkPermission2Geo(refresh) { if (this.state.hasPermission) { if (refresh) { //避免关闭自动移动地图后无法点击按钮移动地图 this.state.stopList = [] } this.infoGeoLocation(); return; } check( isIOS ? PERMISSIONS.IOS.LOCATION_WHEN_IN_USE : PERMISSIONS.ANDROID.ACCESS_FINE_LOCATION) .then(res => { //console.log('checkPermission2Geo', res); switch (res) { case RESULTS.UNAVAILABLE: console.log('此功能不可用(在此设备上/在此上下文中)'); if (isIOS) { this.setState({ hasPermission: true }); this.infoGeoLocation(); } break; case RESULTS.DENIED: console.log('权限未被请求/被拒绝,但可以请求'); if (this.denied) { this.denied = false; this.getPermission(); } else { this.denied = true; } break; case RESULTS.LIMITED: console.log('权限是有限的:有些操作是可能的'); this.setState({ hasPermission: true }); this.infoGeoLocation(); break; case RESULTS.GRANTED: console.log('许可被授予'); this.setState({ hasPermission: true }); this.infoGeoLocation(); break; case RESULTS.BLOCKED: console.log('权限被拒绝,不再可请求'); Dialog.showDialog({ title: 'Error', message: 'Can not get charge station, Please grant location permissions.', ok: 'SETTING', callback: btn => { if (btn == Dialog.BUTTON_OK) { console.log('ok'); openSettings().catch(() => console.warn('cannot open settings')); } } }); //toastShort('Save to gallery failed'); break; } }).catch(err => { console.log('checkPermission2Geo-error', err); }); } /** * 获取定位数据 * @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.alwaysLocation) { 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('Loading...'); 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, /*acConnector: item.acConnector, allConnector: item.allConnector, dcConnector: item.dcConnector, distance: utils.getDistance(item.distance)*/ }); }); this.setState({ stopList: list }); if (region && (this.settingInfo.alwaysLocation || first)) { setTimeout(() => { this.setState({ region: region }); }, 500); } } }).catch(err => { if (!isIOS) Dialog.dismissLoading(); toastShort(err); this.setState({ stopList: [] }); }) } //点击Marker获取StaionInfo viewChargeStation(id, index) { //console.log('info', this.state.stopList[index]); //const stationInfo = this.state.stopList[index]; navigator.geolocation.getCurrentPosition(location => { let params = { lat: location.coords.latitude, lng: location.coords.longitude, sitePk: id//stationInfo.id } apiStation.getStationRate(params).then(res => { if (res.data.sitePk) { var info = utils.getSiteInfo(res.data); this.setState({ stationInfo: info }); } else { this.setState({ stationInfo: stationInfo }); } }).catch(err => { this.setState({ stationInfo: stationInfo }); }); }); //startPage(PageList.chargeDetail, {...this.state.stopList[index]}); } render() { return ( { this.props.navigation.toggleDrawer(); }}> {/* */} startPage(PageList.scanqr, {actionDetail: true})}> this.findFilter(data)} onLocation={() => this.checkPermission2Geo(true)} /> { this.state.hasPermission && { this.setState({ mapReady: true }, () => { this.checkPermission2Geo(); }); }} onMarkerPress={id => this.viewChargeStation(id)} /> } ); } } 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', } })