Home.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455
  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. Dialog.showProgressDialog('Loading...');
  262. apiStation.getAllStation(this.filter).then(res => {
  263. Dialog.dismissLoading();
  264. if (res.data.sites) {
  265. const list = [];
  266. res.data.sites.forEach(item => {
  267. let available = false
  268. if (item.allConnector && item.allConnector.available) {
  269. available = true
  270. }
  271. list.push({
  272. id: item.sitePk,
  273. name: item.siteName,
  274. //address: item.siteAddress,
  275. available: available,
  276. siteType: item.siteType,
  277. latitude: item.locationLatitude,
  278. longitude: item.locationLongitude,
  279. /*acConnector: item.acConnector,
  280. allConnector: item.allConnector,
  281. dcConnector: item.dcConnector,
  282. distance: utils.getDistance(item.distance)*/
  283. });
  284. });
  285. this.setState({
  286. stopList: list
  287. });
  288. if (region && (this.settingInfo.alwaysLocation || first)) {
  289. setTimeout(() => {
  290. this.setState({
  291. region: region
  292. });
  293. }, 500);
  294. }
  295. }
  296. }).catch(err => {
  297. Dialog.dismissLoading();
  298. toastShort(err);
  299. this.setState({
  300. stopList: []
  301. });
  302. })
  303. }
  304. //点击Marker获取StaionInfo
  305. viewChargeStation(id, index) {
  306. //console.log('info', this.state.stopList[index]);
  307. //const stationInfo = this.state.stopList[index];
  308. navigator.geolocation.getCurrentPosition(location => {
  309. let params = {
  310. lat: location.coords.latitude,
  311. lng: location.coords.longitude,
  312. sitePk: id//stationInfo.id
  313. }
  314. apiStation.getStationRate(params).then(res => {
  315. if (res.data.sitePk) {
  316. var info = utils.getSiteInfo(res.data);
  317. this.setState({
  318. stationInfo: info
  319. });
  320. } else {
  321. this.setState({
  322. stationInfo: stationInfo
  323. });
  324. }
  325. }).catch(err => {
  326. this.setState({
  327. stationInfo: stationInfo
  328. });
  329. });
  330. });
  331. //startPage(PageList.chargeDetail, {...this.state.stopList[index]});
  332. }
  333. render() {
  334. return (
  335. <View style={ui.flex1}>
  336. <View style={Styles.toolbar}>
  337. <Pressable
  338. style={Styles.backIcon}
  339. android_ripple = {rippleLess}
  340. onPress={() => {
  341. this.props.navigation.toggleDrawer();
  342. }}>
  343. <EvilIcons name={'navicon'} size={28} color={colorPrimary} />
  344. </Pressable>
  345. <View style={styles.logoView}>
  346. <Image
  347. source={require('../../images/tool-logo.png')}
  348. style={Styles.logo}
  349. />
  350. </View>
  351. {/* <Text style={ui.flex1}></Text> */}
  352. <Pressable
  353. style={Styles.backIcon}
  354. android_ripple = {rippleLess}
  355. onPress={() => startPage(PageList.scanqr, {actionDetail: true})}>
  356. <MaterialCommunityIcons
  357. name='line-scan'
  358. size={20}
  359. color={colorPrimary}
  360. />
  361. </Pressable>
  362. </View>
  363. <SearchTool
  364. count={this.state.stopList.length}
  365. mapReady={this.state.mapReady}
  366. onFilter={data => this.findFilter(data)}
  367. onLocation={() => this.checkPermission2Geo(true)}
  368. />
  369. <View style={styles.mapContent}>
  370. { this.state.hasPermission &&
  371. <Maps.Maps3
  372. region={this.state.region}
  373. stopList={this.state.stopList}
  374. onMapReady={() => {
  375. this.setState({
  376. mapReady: true
  377. }, () => {
  378. this.checkPermission2Geo();
  379. });
  380. }}
  381. onMarkerPress={id => this.viewChargeStation(id)}
  382. />
  383. }
  384. <BottomSiteInfo stationInfo={this.state.stationInfo}/>
  385. </View>
  386. <View style={styles.drawerLeftTouchView}></View>
  387. </View>
  388. );
  389. }
  390. }
  391. const styles = StyleSheet.create({
  392. logoView: {
  393. /*left: 0,
  394. right: 0,
  395. bottom: 0,
  396. zIndex: 1,
  397. alignItems: 'center',
  398. position: 'absolute',*/
  399. flex: 1,
  400. alignItems: 'center',
  401. justifyContent: 'center'
  402. },
  403. searchView: {
  404. ...$padding(8, 16, 16),
  405. backgroundColor: colorThemes
  406. },
  407. searchInput: {
  408. alignItems: 'center',
  409. borderWidth: 1,
  410. borderStyle: 'solid',
  411. borderRadius: 60,
  412. borderColor: colorAccent,
  413. flexDirection: 'row',
  414. paddingLeft: 16,
  415. paddingRight: 16,
  416. backgroundColor: 'rgba(255, 255, 255, 0.5)'
  417. },
  418. searchText: {
  419. flex: 1,
  420. color: '#444',
  421. padding: 8,
  422. fontSize: 15
  423. },
  424. drawerLeftTouchView: {
  425. top: 0,
  426. left: 0,
  427. bottom: 0,
  428. width: 4,
  429. zIndex: 5,
  430. position: 'absolute',
  431. backgroundColor: 'rgba(0,0,0,0)'
  432. },
  433. mapContent: {
  434. flex: 1,
  435. zIndex: 4,
  436. position: 'relative',
  437. }
  438. })