Home.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458
  1. /**
  2. * 首页地图页
  3. * @邠心vbe on 2021/08/13
  4. */
  5. import React, { Component } from 'react';
  6. import { View, Text, Pressable, Image, StyleSheet, BackHandler, Linking } from 'react-native';
  7. import {check, request, openSettings, PERMISSIONS, RESULTS} from 'react-native-permissions';
  8. import apiBase from '../../api/apiBase';
  9. import apiStation from '../../api/apiStation';
  10. import Dialog from '../../components/Dialog';
  11. import { Styles } from '../../components/Toolbar';
  12. import utils from '../../utils/utils';
  13. import { PageList } from '../Router';
  14. import { SettingUtil } from '../Settings';
  15. import BottomSiteInfo from './maps/BottomSiteInfo';
  16. import Maps from './maps/Maps';
  17. import SearchTool from './maps/SearchTool';
  18. import app from '../../../app.json'
  19. export default class HomePage extends Component {
  20. constructor(props) {
  21. super(props);
  22. this.state = {
  23. region: {
  24. latitude: 1.3532623163977149,
  25. longitude: 103.87092316860532,
  26. latitudeDelta: 0.0922,
  27. longitudeDelta: 0.0421
  28. },
  29. mapReady: false,
  30. stationInfo: {},
  31. stopList: [],
  32. hasPermission: isIOS
  33. };
  34. this.isHide = true;
  35. this.denied = true;
  36. this.backSeconds = 0;
  37. this.refreshTime = 0;
  38. this.settingInfo = {}
  39. //this.unsubscribe = null;
  40. this.filter = {
  41. parkingFee: 'ALL',
  42. connectorType: ''
  43. };
  44. }
  45. componentDidMount() {
  46. console.log("componentDidMount")
  47. const navigation = this.props.navigation;
  48. navigation.addListener('focus', () => {
  49. //toastShort('onResume')
  50. this.setState({
  51. stationInfo: {}
  52. });
  53. SettingUtil.getSettings(set => {
  54. console.log("获取设置信息", set);
  55. this.settingInfo = set;
  56. this.checkPermission2Geo();
  57. })
  58. console.log("focus");
  59. this.isHide = false;
  60. });
  61. navigation.addListener('blur', () => {
  62. //toastShort('onStop')
  63. this.isHide = true;
  64. setTimeout(() => {
  65. navigation.closeDrawer();
  66. }, 200);
  67. });
  68. /*this.unsubscribe = navigation.addListener('beforeRemove', (e) => {
  69. this.toExit(e);
  70. });*/
  71. BackHandler.addEventListener('hardwareBackPress', this.toExit)
  72. this.isHide = false;
  73. this.checkUpdateVersion();
  74. }
  75. /*componentDidUpdate() {
  76. console.log("componentDidUpdate", this.unsubscribe);
  77. if (!this.unsubscribe) {
  78. this.unsubscribe = this.props.navigation.addListener('beforeRemove', (e) => {
  79. this.toExit(e);
  80. });
  81. }
  82. }*/
  83. componentWillUnmount() {
  84. /*console.log("componentWillUnmount")
  85. if (this.unsubscribe) {
  86. this.unsubscribe();
  87. }*/
  88. this.backSeconds = 0;
  89. BackHandler.removeEventListener("hardwareBackPress", this.toExit)
  90. }
  91. toExit = () => {
  92. //console.log("beforeRemove", this.isHide);
  93. if (!this.isHide) {
  94. if (isIOS) {
  95. //e.preventDefault();
  96. } else {
  97. let time = new Date().getTime();
  98. //console.log("beforeRemove2", time, this.backSeconds);
  99. if (time - this.backSeconds < 2000) {
  100. BackHandler.exitApp();
  101. } else {
  102. toastShort("Press the back button again to exit the program");
  103. this.backSeconds = time;
  104. //e.preventDefault();
  105. }
  106. }
  107. return true;
  108. }
  109. }
  110. checkUpdateVersion() {
  111. apiBase.checkUpdate().then(res => {
  112. if (res.data.versionCode > app.versionCode) {
  113. var desc = JSON.parse(res.data?.versionDesc ?? "{}");
  114. if (desc && typeof desc.en == "string") {
  115. Dialog.showDialog({
  116. title: "Version Update",
  117. message: "New Version: " + res.data.versionName + "\n\n" + desc.en,
  118. showCancel: !(res.data.force),
  119. ok: "UPDATE NOW",
  120. cancel: "LATER",
  121. callback: btn => {
  122. if (btn == Dialog.BUTTON_OK) {
  123. //TODO 跳转到应用商店
  124. const uri = isIOS
  125. ? 'itms-appss://apps.apple.com/app/id1664718768'
  126. : 'market://details?id=com.strides.chargeco'
  127. Linking.openURL(uri);
  128. }
  129. }
  130. })
  131. }
  132. }
  133. }).catch(err => {
  134. })
  135. }
  136. getPermission() {
  137. request(
  138. isIOS
  139. ? PERMISSIONS.IOS.LOCATION_WHEN_IN_USE
  140. : PERMISSIONS.ANDROID.ACCESS_FINE_LOCATION)
  141. .then(res => {
  142. console.log('getPermission', res)
  143. this.setState({
  144. hasPermission: true
  145. });
  146. this.checkPermission2Geo();
  147. }).catch(err => {
  148. console.info('getPermission', err)
  149. });
  150. }
  151. checkPermission2Geo(refresh) {
  152. if (this.state.hasPermission) {
  153. if (refresh) {
  154. //避免关闭自动移动地图后无法点击按钮移动地图
  155. this.state.stopList = []
  156. }
  157. this.infoGeoLocation();
  158. return;
  159. }
  160. check(
  161. isIOS
  162. ? PERMISSIONS.IOS.LOCATION_WHEN_IN_USE
  163. : PERMISSIONS.ANDROID.ACCESS_FINE_LOCATION)
  164. .then(res => {
  165. //console.log('checkPermission2Geo', res);
  166. switch (res) {
  167. case RESULTS.UNAVAILABLE:
  168. console.log('此功能不可用(在此设备上/在此上下文中)');
  169. if (isIOS) {
  170. this.setState({
  171. hasPermission: true
  172. });
  173. this.infoGeoLocation();
  174. }
  175. break;
  176. case RESULTS.DENIED:
  177. console.log('权限未被请求/被拒绝,但可以请求');
  178. if (this.denied) {
  179. this.denied = false;
  180. this.getPermission();
  181. } else {
  182. this.denied = true;
  183. }
  184. break;
  185. case RESULTS.LIMITED:
  186. console.log('权限是有限的:有些操作是可能的');
  187. this.setState({
  188. hasPermission: true
  189. });
  190. this.infoGeoLocation();
  191. break;
  192. case RESULTS.GRANTED:
  193. console.log('许可被授予');
  194. this.setState({
  195. hasPermission: true
  196. });
  197. this.infoGeoLocation();
  198. break;
  199. case RESULTS.BLOCKED:
  200. console.log('权限被拒绝,不再可请求');
  201. Dialog.showDialog({
  202. title: 'Error',
  203. message: 'Can not get charge station, Please grant location permissions.',
  204. ok: 'SETTING',
  205. callback: btn => {
  206. if (btn == Dialog.BUTTON_OK) {
  207. console.log('ok');
  208. openSettings().catch(() => console.warn('cannot open settings'));
  209. }
  210. }
  211. });
  212. //toastShort('Save to gallery failed');
  213. break;
  214. }
  215. }).catch(err => {
  216. console.log('checkPermission2Geo-error', err);
  217. });
  218. }
  219. infoGeoLocation(again) {
  220. if (this.state.mapReady) {
  221. navigator.geolocation.getCurrentPosition(location => {
  222. let region = {
  223. latitude: location.coords.latitude,
  224. longitude: location.coords.longitude,
  225. latitudeDelta: 0.0922,
  226. longitudeDelta: 0.0421
  227. }
  228. //console.log("getGeoLocation", region);
  229. //if (this.state.stopList.length == 0) { //只加载一次
  230. let time = new Date().getTime();
  231. let interval = this.settingInfo.refreshInterval * 1000;
  232. let first = this.state.stopList.length == 0;
  233. if (first || time - this.refreshTime > interval) { //一分钟(10秒)加载一次
  234. this.getStationList(region, first);
  235. this.refreshTime = time;
  236. } else if (this.settingInfo.alwaysLocation) {
  237. this.setState({
  238. region: region
  239. });
  240. }
  241. }, error => {
  242. console.info("getGeoLocation", error);
  243. if (!again) {
  244. setTimeout(() => {
  245. this.infoGeoLocation(true);
  246. }, 2000);
  247. }
  248. });
  249. }
  250. }
  251. findFilter(data) {
  252. this.filter = data;
  253. this.getStationList();
  254. }
  255. /**
  256. * 获取所有充电桩
  257. * @param {Location} region 当前位置
  258. * @param {boolean} first 是否初始化
  259. */
  260. getStationList(region, first) {
  261. if (!isIOS)
  262. Dialog.showProgressDialog('Loading...');
  263. apiStation.getAllStation(this.filter).then(res => {
  264. if (!isIOS)
  265. Dialog.dismissLoading();
  266. if (res.data.sites) {
  267. const list = [];
  268. res.data.sites.forEach(item => {
  269. let available = false
  270. if (item.allConnector && item.allConnector.available) {
  271. available = true
  272. }
  273. list.push({
  274. id: item.sitePk,
  275. name: item.siteName,
  276. //address: item.siteAddress,
  277. available: available,
  278. siteType: item.siteType,
  279. latitude: item.locationLatitude,
  280. longitude: item.locationLongitude,
  281. /*acConnector: item.acConnector,
  282. allConnector: item.allConnector,
  283. dcConnector: item.dcConnector,
  284. distance: utils.getDistance(item.distance)*/
  285. });
  286. });
  287. this.setState({
  288. stopList: list
  289. });
  290. if (region && (this.settingInfo.alwaysLocation || first)) {
  291. setTimeout(() => {
  292. this.setState({
  293. region: region
  294. });
  295. }, 500);
  296. }
  297. }
  298. }).catch(err => {
  299. if (!isIOS)
  300. Dialog.dismissLoading();
  301. toastShort(err);
  302. this.setState({
  303. stopList: []
  304. });
  305. })
  306. }
  307. //点击Marker获取StaionInfo
  308. viewChargeStation(id, index) {
  309. //console.log('info', this.state.stopList[index]);
  310. //const stationInfo = this.state.stopList[index];
  311. navigator.geolocation.getCurrentPosition(location => {
  312. let params = {
  313. lat: location.coords.latitude,
  314. lng: location.coords.longitude,
  315. sitePk: id//stationInfo.id
  316. }
  317. apiStation.getStationRate(params).then(res => {
  318. if (res.data.sitePk) {
  319. var info = utils.getSiteInfo(res.data);
  320. this.setState({
  321. stationInfo: info
  322. });
  323. } else {
  324. this.setState({
  325. stationInfo: stationInfo
  326. });
  327. }
  328. }).catch(err => {
  329. this.setState({
  330. stationInfo: stationInfo
  331. });
  332. });
  333. });
  334. //startPage(PageList.chargeDetail, {...this.state.stopList[index]});
  335. }
  336. render() {
  337. return (
  338. <View style={ui.flex1}>
  339. <View style={Styles.toolbar}>
  340. <Pressable
  341. style={Styles.backIcon}
  342. android_ripple = {rippleLess}
  343. onPress={() => {
  344. this.props.navigation.toggleDrawer();
  345. }}>
  346. <EvilIcons name={'navicon'} size={28} color={colorPrimary} />
  347. </Pressable>
  348. <View style={styles.logoView}>
  349. <Image
  350. source={require('../../images/tool-logo.png')}
  351. style={Styles.logo}
  352. />
  353. </View>
  354. {/* <Text style={ui.flex1}></Text> */}
  355. <Pressable
  356. style={Styles.backIcon}
  357. android_ripple = {rippleLess}
  358. onPress={() => startPage(PageList.scanqr, {actionDetail: true})}>
  359. <MaterialCommunityIcons
  360. name='line-scan'
  361. size={20}
  362. color={colorPrimary}
  363. />
  364. </Pressable>
  365. </View>
  366. <SearchTool
  367. count={this.state.stopList.length}
  368. mapReady={this.state.mapReady}
  369. onFilter={data => this.findFilter(data)}
  370. onLocation={() => this.checkPermission2Geo(true)}
  371. />
  372. <View style={styles.mapContent}>
  373. { this.state.hasPermission &&
  374. <Maps.Maps3
  375. region={this.state.region}
  376. stopList={this.state.stopList}
  377. onMapReady={() => {
  378. this.setState({
  379. mapReady: true
  380. }, () => {
  381. this.checkPermission2Geo();
  382. });
  383. }}
  384. onMarkerPress={id => this.viewChargeStation(id)}
  385. />
  386. }
  387. <BottomSiteInfo stationInfo={this.state.stationInfo}/>
  388. </View>
  389. <View style={styles.drawerLeftTouchView}></View>
  390. </View>
  391. );
  392. }
  393. }
  394. const styles = StyleSheet.create({
  395. logoView: {
  396. /*left: 0,
  397. right: 0,
  398. bottom: 0,
  399. zIndex: 1,
  400. alignItems: 'center',
  401. position: 'absolute',*/
  402. flex: 1,
  403. alignItems: 'center',
  404. justifyContent: 'center'
  405. },
  406. searchView: {
  407. ...$padding(8, 16, 16),
  408. backgroundColor: colorThemes
  409. },
  410. searchInput: {
  411. alignItems: 'center',
  412. borderWidth: 1,
  413. borderStyle: 'solid',
  414. borderRadius: 60,
  415. borderColor: colorAccent,
  416. flexDirection: 'row',
  417. paddingLeft: 16,
  418. paddingRight: 16,
  419. backgroundColor: 'rgba(255, 255, 255, 0.5)'
  420. },
  421. searchText: {
  422. flex: 1,
  423. color: '#444',
  424. padding: 8,
  425. fontSize: 15
  426. },
  427. drawerLeftTouchView: {
  428. top: 0,
  429. left: 0,
  430. bottom: 0,
  431. width: 4,
  432. zIndex: 5,
  433. position: 'absolute',
  434. backgroundColor: 'rgba(0,0,0,0)'
  435. },
  436. mapContent: {
  437. flex: 1,
  438. zIndex: 4,
  439. position: 'relative',
  440. }
  441. })