Home.js 17 KB

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