Home.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580
  1. /**
  2. * 首页通用页
  3. * @邠心vbe on 2021/08/13
  4. */
  5. import React, { Component } from 'react';
  6. import { View, StyleSheet, BackHandler, Linking, AppState } from 'react-native';
  7. import app from '../../../app.json'
  8. import { i18nUtil } from '../../i18n';
  9. import apiBase from '../../api/apiBase';
  10. import apiStation from '../../api/apiStation';
  11. import Dialog from '../../components/Dialog';
  12. import utils from '../../utils/utils';
  13. import { SettingUtil } from '../Settings';
  14. import MyStatusBar from '../../components/MyStatusBar';
  15. import LocationPermission from './maps/LocationPermission';
  16. import MapUI from './MapUI';
  17. import MapUILumi from './MapUILumi';
  18. import storage from '../../utils/storage';
  19. const KEY_STORE_LIST = "map_stop_list"
  20. const KEY_STORE_GPS = "map_location_gps"
  21. export default class HomePage extends Component {
  22. constructor(props) {
  23. super(props);
  24. this.state = {
  25. region: {
  26. latitude: 1.3532623163977149,
  27. longitude: 103.87092316860532,
  28. latitudeDelta: 0.0922,
  29. longitudeDelta: 0.0421
  30. },
  31. lastRegion: {},
  32. mapReady: false,
  33. showStation: false,
  34. stationId: "",
  35. stationInfo: {},
  36. stopList: [],
  37. hasPermission: false,
  38. permissionDenied: false
  39. };
  40. this.isHide = true;
  41. this.denied = true;
  42. this.backSeconds = 0;
  43. this.refreshTime = 0;
  44. this.settingInfo = {}
  45. this.viewIndex = -1;
  46. this.filter = {
  47. parkingFee: 'ALL',
  48. connectorType: ''
  49. };
  50. this.refresh = false;
  51. this.stateListener;
  52. this.forceUpdateDialog = undefined;
  53. this.locationListener = undefined;
  54. }
  55. componentDidMount() {
  56. const navigation = this.props.navigation;
  57. if (this.locationListener) {
  58. this.locationListener.removeListener();
  59. this.locationListener = undefined;
  60. }
  61. if (!isIOS) {
  62. this.locationListener = new LocationPermission.LocationListener();
  63. if (this.locationListener) {
  64. this.locationListener.addListener();
  65. }
  66. }
  67. navigation.addListener('focus', () => {
  68. //console.log('------Home------', "Focus")
  69. this.onCloseInfo();
  70. SettingUtil.getSettings(set => {
  71. //console.log("获取设置信息", set);
  72. this.settingInfo = set;
  73. this.init();
  74. })
  75. this.isHide = false;
  76. /*if (!app.isWhitelabel) {
  77. MyStatusBar.setStatusBarThemes(MyStatusBar.DARK_STYLE, colorLight);
  78. }*/
  79. MyStatusBar.setTranslucentStatusBar();
  80. });
  81. navigation.addListener('blur', () => {
  82. //toastShort('onStop')
  83. this.isHide = true;
  84. /*if (app.isLumiWhitelabel) {
  85. MyStatusBar.setStatusBarThemes(MyStatusBar.DARK_STYLE, colorLight);
  86. } else {
  87. MyStatusBar.setStatusBarThemes(themeStatusBar, colorPrimaryDark);
  88. }*/
  89. setTimeout(() => {
  90. MyStatusBar.setStatusBarTheme(MyStatusBar.DEFAULT_STYLE);
  91. }, 50);
  92. setTimeout(() => {
  93. navigation.closeDrawer();
  94. }, 500);
  95. });
  96. this.stateListener = AppState.addEventListener("change", state => {
  97. if (state == 'active' && this.forceUpdateDialog) {
  98. this.showUpdateDialog(this.forceUpdateDialog);
  99. }
  100. });
  101. BackHandler.addEventListener('hardwareBackPress', this.toExit)
  102. this.isHide = false;
  103. this.checkUpdateVersion();
  104. }
  105. componentWillUnmount() {
  106. /*console.log("componentWillUnmount")
  107. if (this.unsubscribe) {
  108. this.unsubscribe();
  109. }*/
  110. this.backSeconds = 0;
  111. if (this.stateListener) {
  112. this.stateListener.remove();
  113. }
  114. BackHandler.removeEventListener("hardwareBackPress", this.toExit);
  115. }
  116. init() {
  117. if (this.state.stopList.length == 0 && !this.refresh) {
  118. storage.getStorage(KEY_STORE_LIST).then(data => {
  119. //console.log("获取站点缓存", "成功");
  120. if (data) {
  121. const list = JSON.parse(data);
  122. this.setState({
  123. stopList: list
  124. }, () => {
  125. this.checkPermission2Geo(true);
  126. })
  127. } else {
  128. this.checkPermission2Geo(true);
  129. }
  130. }).catch(err => {
  131. console.log("获取站点缓存-err", err);
  132. this.checkPermission2Geo(true);
  133. })
  134. storage.getStorage(KEY_STORE_GPS).then(data => {
  135. //console.log("获取GPS缓存", data);
  136. if (data && data.latitude) {
  137. this.setState({
  138. lastRegion: data
  139. });
  140. }
  141. }).catch(err => {
  142. console.log("获取GPS缓存-err", err);
  143. })
  144. }
  145. }
  146. toExit = () => {
  147. //console.log("beforeRemove", this.isHide);
  148. if (this.state.stationInfo?.id) {
  149. this.setState({
  150. stationInfo: {}
  151. });
  152. return true;
  153. }
  154. if (!this.isHide) {
  155. if (isIOS) {
  156. //e.preventDefault();
  157. } else {
  158. let time = new Date().getTime();
  159. //console.log("beforeRemove2", time, this.backSeconds);
  160. if (time - this.backSeconds < 2000) {
  161. BackHandler.exitApp();
  162. } else {
  163. toastShort($t("home.backAgainTips"));
  164. this.backSeconds = time;
  165. //e.preventDefault();
  166. }
  167. }
  168. return true;
  169. }
  170. }
  171. checkGPS() {
  172. if (this.locationListener) {
  173. this.locationListener.check();
  174. }
  175. }
  176. onMapReady() {
  177. this.setState({
  178. mapReady: true
  179. }, () => {
  180. this.init();
  181. });
  182. }
  183. checkUpdateVersion() {
  184. apiBase.checkUpdate().then(res => {
  185. if (res.data.versionCode > app.versionCode) {
  186. var desc = JSON.parse(res.data?.versionDesc ?? "{}");
  187. if (desc) {
  188. const upLog = i18nUtil.analyzeLocaleData(desc);
  189. if (typeof upLog == "string") {
  190. const prps = {
  191. title: $t("home.versionUpdate"),
  192. message: $t("home.newVersionName") + res.data.versionName + "\n\n" + upLog,
  193. showCancel: !(res.data.force),
  194. ok: $t("home.updateNow"),
  195. cancel: $t("home.later"),
  196. callback: btn => {
  197. if (btn == Dialog.BUTTON_OK) {
  198. //TODO 跳转到应用商店
  199. const uri = isIOS
  200. ? app.storeUrl.ios
  201. : app.storeUrl.android
  202. Linking.openURL(uri);
  203. }
  204. }
  205. }
  206. if (res.data.force) {
  207. prps.onBackPress = () => {
  208. }
  209. this.forceUpdateDialog = prps;
  210. }
  211. this.showUpdateDialog(prps);
  212. }
  213. }
  214. }
  215. }).catch(err => {
  216. })
  217. }
  218. showUpdateDialog(options) {
  219. if (Dialog.isShowing()) {
  220. setTimeout(() => {
  221. this.showUpdateDialog(options)
  222. }, 500);
  223. return;
  224. }
  225. Dialog.showDialog(options)
  226. }
  227. getPermission() {
  228. LocationPermission.requestPermission(hasPermission => {
  229. if (hasPermission) {
  230. this.setState({
  231. hasPermission: true
  232. });
  233. this.checkPermission2Geo();
  234. } else {
  235. this.noPermissionSite();
  236. }
  237. })
  238. }
  239. checkPermission2Geo(refresh, button) {
  240. if (button && this.state.lastRegion.latitude) {
  241. this.setState({
  242. region: {...this.state.lastRegion}
  243. });
  244. }
  245. if (this.refresh == refresh) {
  246. return;
  247. }
  248. if (refresh) {
  249. //避免关闭自动移动地图后无法点击按钮移动地图
  250. this.refresh = true
  251. }
  252. console.log("checkPermission2Geo", refresh, this.state.lastRegion);
  253. this.checkGPS();
  254. if (this.state.hasPermission) {
  255. this.infoGeoLocation();
  256. } else {
  257. LocationPermission.checkPermission((hasPermission, canRequestPermission) => {
  258. if (hasPermission) {
  259. this.setState({
  260. hasPermission: true
  261. });
  262. this.infoGeoLocation();
  263. } else {
  264. if (canRequestPermission) {
  265. if (this.denied) {
  266. this.denied = false;
  267. this.getPermission();
  268. } else {
  269. //避免多次请求
  270. this.denied = true;
  271. this.noPermissionSite();
  272. }
  273. } else {
  274. this.noPermissionSite();
  275. }
  276. }
  277. })
  278. }
  279. }
  280. noPermissionSite() {
  281. console.log("未获取权限也获取站点列表");
  282. this.setState({
  283. hasPermission: false,
  284. permissionDenied: true
  285. });
  286. let first = this.state.stopList.length == 0;//是否第一次加载
  287. this.getStationList(this.state.region, first);
  288. }
  289. /**
  290. * 获取定位数据
  291. * @param {*} again
  292. */
  293. infoGeoLocation(again) {
  294. if (this.state.mapReady) {
  295. navigator.geolocation.getCurrentPosition(location => {
  296. let region = {
  297. latitude: location.coords.latitude,
  298. longitude: location.coords.longitude,
  299. latitudeDelta: 0.0922,
  300. longitudeDelta: 0.0421
  301. }
  302. this.saveGPSCache(region);
  303. //console.log("getGeoLocation", region);
  304. //if (this.state.stopList.length == 0) { //只加载一次
  305. let time = new Date().getTime();
  306. let interval = this.settingInfo.refreshInterval * 1000;//重复加载时间
  307. let first = this.state.stopList.length == 0;//是否第一次加载
  308. if (first || this.refresh || time - this.refreshTime > interval) { //一分钟(10秒)加载一次
  309. this.getStationList(region, first || this.refresh);
  310. this.refreshTime = time;
  311. } else if (this.settingInfo.moveMyLocation) {
  312. this.setState({
  313. region: region
  314. });
  315. }
  316. }, error => {
  317. console.info("getGeoLocation", error);
  318. if (!again) {
  319. setTimeout(() => {
  320. this.infoGeoLocation(true);
  321. }, 2000);
  322. }
  323. });
  324. } else {
  325. setTimeout(() => {
  326. this.infoGeoLocation(true);
  327. }, 1000);
  328. }
  329. }
  330. findFilter(data) {
  331. this.filter = data;
  332. console.log("筛选站点", data);
  333. this.getStationList();
  334. }
  335. /**
  336. * 获取所有充电桩
  337. * @param {Location} region 当前位置
  338. * @param {boolean} first 是否初始化
  339. */
  340. getStationList(region, first) {
  341. //Dialog.showProgressDialog();
  342. if (getUserId()) {
  343. this.filter.operaUserId = getUserId()
  344. }
  345. if (region && (this.settingInfo.moveMyLocation || first)) {
  346. this.setState({
  347. region: region
  348. });
  349. }
  350. apiStation.getAllStation(this.filter).then(res => {
  351. Dialog.dismissLoading();
  352. if (res.data.sites) {
  353. const list = [];
  354. res.data.sites.forEach(item => {
  355. let available = false
  356. if (item.allConnector && item.allConnector.available) {
  357. available = true
  358. }
  359. list.push({
  360. id: item.sitePk,
  361. name: item.siteName,
  362. //address: item.siteAddress,
  363. available: available,
  364. siteType: item.siteType,
  365. latitude: item.locationLatitude,
  366. longitude: item.locationLongitude,
  367. favorite: item?.favorite ? true : false,
  368. hasLabel: item?.hasLabel,
  369. upcoming: item?.upcoming
  370. /*acConnector: item.acConnector,
  371. allConnector: item.allConnector,
  372. dcConnector: item.dcConnector,
  373. distance: utils.getDistance(item.distance)*/
  374. });
  375. });
  376. this.setState({
  377. stopList: list
  378. });
  379. if (this.filter.connectorType == "" && this.filter.parkingFee == "ALL") {
  380. storage.setStorageJson(KEY_STORE_LIST, list);
  381. }
  382. }
  383. this.refresh = false;
  384. }).catch(err => {
  385. Dialog.dismissLoading();
  386. toastShort(err);
  387. /*this.setState({
  388. stopList: []
  389. });*/
  390. this.refresh = false;
  391. })
  392. }
  393. //点击Marker获取StaionInfo
  394. viewChargeStation(id) {
  395. //console.log('info', this.state.stopList[index]);
  396. //const stationInfo = this.state.stopList[index];
  397. if (this.state.stationId == id) {
  398. return;
  399. }
  400. this.setState({
  401. stationId: id,
  402. stationInfo: {},
  403. showStation: true
  404. });
  405. if (app.modules.bookmarks) {
  406. for (let i = 0; i < this.state.stopList.length; i++) {
  407. let info = this.state.stopList[i];
  408. if (info.id == id) {
  409. this.viewIndex = i;
  410. break;
  411. }
  412. }
  413. }
  414. if (this.state.hasPermission) {
  415. navigator.geolocation.getCurrentPosition(location => {
  416. let region = {
  417. latitude: location.coords.latitude,
  418. longitude: location.coords.longitude,
  419. latitudeDelta: 0.0922,
  420. longitudeDelta: 0.0421
  421. }
  422. setTimeout(() => {
  423. this.getStationInfo(id, region);
  424. }, 500);
  425. /*if (this.settingInfo.alwaysLocation) {
  426. this.setState({
  427. region: region
  428. });
  429. }*/
  430. });
  431. } else {
  432. //无定位权限仍然显示
  433. setTimeout(() => {
  434. this.getStationInfo(id, this.state.region);
  435. }, 500);
  436. }
  437. //startPage(PageList.chargeDetail, {...this.state.stopList[index]});
  438. }
  439. getStationInfo(id, location) {
  440. apiStation.getStationRate({
  441. sitePk: id,
  442. lat: location?.latitude,
  443. lng: location?.longitude
  444. }).then(res => {
  445. if (res.data.sitePk) {
  446. var info = utils.getSiteInfo(res.data);
  447. this.setState({
  448. stationInfo: info
  449. });
  450. } else {
  451. this.setState({
  452. stationInfo: {}
  453. });
  454. }
  455. }).catch(err => {
  456. this.setState({
  457. stationInfo: {}
  458. });
  459. toastShort(err);
  460. });
  461. }
  462. onCloseInfo() {
  463. this.viewIndex = -1;
  464. this.setState({
  465. stationId: "",
  466. stationInfo: {},
  467. showStation: false
  468. });
  469. }
  470. favoriteSite() {
  471. if (this.state.stationInfo?.id) {
  472. Dialog.showProgressDialog();
  473. apiStation.bookmarkSite(this.state.stationInfo.id).then(res => {
  474. const info = {...this.state.stationInfo, favorite: !this.state.stationInfo.favorite}
  475. if (this.viewIndex >= 0) {
  476. const list = [...this.state.stopList]
  477. const inf = {...list[this.viewIndex], favorite: info.favorite};
  478. list[this.viewIndex] = inf;
  479. this.setState({
  480. stopList: list,
  481. stationInfo: info
  482. });
  483. } else {
  484. this.setState({
  485. stationInfo: info
  486. });
  487. }
  488. }).catch(err => {
  489. toastShort(err);
  490. console.log(err)
  491. }).finally(() => {
  492. Dialog.dismissLoading();
  493. })
  494. }
  495. }
  496. hidePermissionPanel() {
  497. this.setState({
  498. permissionDenied: false
  499. })
  500. }
  501. saveGPSCache(location) {
  502. storage.setStorageJson(KEY_STORE_GPS, location);
  503. this.setState({
  504. lastRegion: location
  505. });
  506. }
  507. render() {
  508. return (
  509. <View style={ui.flex1}>
  510. { app.isLumiWhitelabel
  511. ? <MapUILumi
  512. state={this.state}
  513. navigation={this.props.navigation}
  514. onFilter={data => this.findFilter(data)}
  515. onMapReady={() => this.onMapReady()}
  516. onFavorite={() => this.favoriteSite()}
  517. onCloseInfo={() => this.onCloseInfo()}
  518. onLocation={() => this.checkPermission2Geo(true, true)}
  519. useApplesMap={this.settingInfo.useApplesMap}
  520. showUserLocation={this.state.hasPermission && this.settingInfo.alwaysLocation}
  521. viewChargeStation={id => this.viewChargeStation(id)}/>
  522. : <MapUI
  523. state={this.state}
  524. navigation={this.props.navigation}
  525. onFilter={data => this.findFilter(data)}
  526. onMapReady={() => this.onMapReady()}
  527. onFavorite={() => this.favoriteSite()}
  528. onCloseInfo={() => this.onCloseInfo()}
  529. onLocation={() => this.checkPermission2Geo(true, true)}
  530. useApplesMap={this.settingInfo.useApplesMap}
  531. showUserLocation={this.state.hasPermission && this.settingInfo.alwaysLocation}
  532. viewChargeStation={id => this.viewChargeStation(id)}
  533. />
  534. }
  535. <LocationPermission.VIEW
  536. visible={this.state.permissionDenied}
  537. onView={() => this.hidePermissionPanel()}/>
  538. <View style={styles.drawerLeftTouchView}></View>
  539. </View>
  540. );
  541. }
  542. }
  543. const styles = StyleSheet.create({
  544. drawerLeftTouchView: {
  545. top: 0,
  546. left: 0,
  547. bottom: 0,
  548. width: 4,
  549. zIndex: 5,
  550. position: 'absolute',
  551. backgroundColor: 'rgba(0,0,0,0)'
  552. }
  553. })