Home.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462
  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. /**
  220. * 获取定位数据
  221. * @param {*} again
  222. */
  223. infoGeoLocation(again) {
  224. if (this.state.mapReady) {
  225. navigator.geolocation.getCurrentPosition(location => {
  226. let region = {
  227. latitude: location.coords.latitude,
  228. longitude: location.coords.longitude,
  229. latitudeDelta: 0.0922,
  230. longitudeDelta: 0.0421
  231. }
  232. //console.log("getGeoLocation", region);
  233. //if (this.state.stopList.length == 0) { //只加载一次
  234. let time = new Date().getTime();
  235. let interval = this.settingInfo.refreshInterval * 1000;
  236. let first = this.state.stopList.length == 0;
  237. if (first || time - this.refreshTime > interval) { //一分钟(10秒)加载一次
  238. this.getStationList(region, first);
  239. this.refreshTime = time;
  240. } else if (this.settingInfo.alwaysLocation) {
  241. this.setState({
  242. region: region
  243. });
  244. }
  245. }, error => {
  246. console.info("getGeoLocation", error);
  247. if (!again) {
  248. setTimeout(() => {
  249. this.infoGeoLocation(true);
  250. }, 2000);
  251. }
  252. });
  253. }
  254. }
  255. findFilter(data) {
  256. this.filter = data;
  257. this.getStationList();
  258. }
  259. /**
  260. * 获取所有充电桩
  261. * @param {Location} region 当前位置
  262. * @param {boolean} first 是否初始化
  263. */
  264. getStationList(region, first) {
  265. if (!isIOS)
  266. Dialog.showProgressDialog('Loading...');
  267. apiStation.getAllStation(this.filter).then(res => {
  268. if (!isIOS)
  269. Dialog.dismissLoading();
  270. if (res.data.sites) {
  271. const list = [];
  272. res.data.sites.forEach(item => {
  273. let available = false
  274. if (item.allConnector && item.allConnector.available) {
  275. available = true
  276. }
  277. list.push({
  278. id: item.sitePk,
  279. name: item.siteName,
  280. //address: item.siteAddress,
  281. available: available,
  282. siteType: item.siteType,
  283. latitude: item.locationLatitude,
  284. longitude: item.locationLongitude,
  285. /*acConnector: item.acConnector,
  286. allConnector: item.allConnector,
  287. dcConnector: item.dcConnector,
  288. distance: utils.getDistance(item.distance)*/
  289. });
  290. });
  291. this.setState({
  292. stopList: list
  293. });
  294. if (region && (this.settingInfo.alwaysLocation || first)) {
  295. setTimeout(() => {
  296. this.setState({
  297. region: region
  298. });
  299. }, 500);
  300. }
  301. }
  302. }).catch(err => {
  303. if (!isIOS)
  304. Dialog.dismissLoading();
  305. toastShort(err);
  306. this.setState({
  307. stopList: []
  308. });
  309. })
  310. }
  311. //点击Marker获取StaionInfo
  312. viewChargeStation(id, index) {
  313. //console.log('info', this.state.stopList[index]);
  314. //const stationInfo = this.state.stopList[index];
  315. navigator.geolocation.getCurrentPosition(location => {
  316. let params = {
  317. lat: location.coords.latitude,
  318. lng: location.coords.longitude,
  319. sitePk: id//stationInfo.id
  320. }
  321. apiStation.getStationRate(params).then(res => {
  322. if (res.data.sitePk) {
  323. var info = utils.getSiteInfo(res.data);
  324. this.setState({
  325. stationInfo: info
  326. });
  327. } else {
  328. this.setState({
  329. stationInfo: stationInfo
  330. });
  331. }
  332. }).catch(err => {
  333. this.setState({
  334. stationInfo: stationInfo
  335. });
  336. });
  337. });
  338. //startPage(PageList.chargeDetail, {...this.state.stopList[index]});
  339. }
  340. render() {
  341. return (
  342. <View style={ui.flex1}>
  343. <View style={Styles.toolbar}>
  344. <Pressable
  345. style={Styles.backIcon}
  346. android_ripple = {rippleLess}
  347. onPress={() => {
  348. this.props.navigation.toggleDrawer();
  349. }}>
  350. <EvilIcons name={'navicon'} size={28} color={colorPrimary} />
  351. </Pressable>
  352. <View style={styles.logoView}>
  353. <Image
  354. source={require('../../images/tool-logo.png')}
  355. style={Styles.logo}
  356. />
  357. </View>
  358. {/* <Text style={ui.flex1}></Text> */}
  359. <Pressable
  360. style={Styles.backIcon}
  361. android_ripple = {rippleLess}
  362. onPress={() => startPage(PageList.scanqr, {actionDetail: true})}>
  363. <MaterialCommunityIcons
  364. name='line-scan'
  365. size={20}
  366. color={colorPrimary}
  367. />
  368. </Pressable>
  369. </View>
  370. <SearchTool
  371. count={this.state.stopList.length}
  372. mapReady={this.state.mapReady}
  373. onFilter={data => this.findFilter(data)}
  374. onLocation={() => this.checkPermission2Geo(true)}
  375. />
  376. <View style={styles.mapContent}>
  377. { this.state.hasPermission &&
  378. <Maps.Maps3
  379. region={this.state.region}
  380. stopList={this.state.stopList}
  381. onMapReady={() => {
  382. this.setState({
  383. mapReady: true
  384. }, () => {
  385. this.checkPermission2Geo();
  386. });
  387. }}
  388. onMarkerPress={id => this.viewChargeStation(id)}
  389. />
  390. }
  391. <BottomSiteInfo stationInfo={this.state.stationInfo}/>
  392. </View>
  393. <View style={styles.drawerLeftTouchView}></View>
  394. </View>
  395. );
  396. }
  397. }
  398. const styles = StyleSheet.create({
  399. logoView: {
  400. /*left: 0,
  401. right: 0,
  402. bottom: 0,
  403. zIndex: 1,
  404. alignItems: 'center',
  405. position: 'absolute',*/
  406. flex: 1,
  407. alignItems: 'center',
  408. justifyContent: 'center'
  409. },
  410. searchView: {
  411. ...$padding(8, 16, 16),
  412. backgroundColor: colorThemes
  413. },
  414. searchInput: {
  415. alignItems: 'center',
  416. borderWidth: 1,
  417. borderStyle: 'solid',
  418. borderRadius: 60,
  419. borderColor: colorAccent,
  420. flexDirection: 'row',
  421. paddingLeft: 16,
  422. paddingRight: 16,
  423. backgroundColor: 'rgba(255, 255, 255, 0.5)'
  424. },
  425. searchText: {
  426. flex: 1,
  427. color: '#444',
  428. padding: 8,
  429. fontSize: 15
  430. },
  431. drawerLeftTouchView: {
  432. top: 0,
  433. left: 0,
  434. bottom: 0,
  435. width: 4,
  436. zIndex: 5,
  437. position: 'absolute',
  438. backgroundColor: 'rgba(0,0,0,0)'
  439. },
  440. mapContent: {
  441. flex: 1,
  442. zIndex: 4,
  443. position: 'relative',
  444. }
  445. })