Home.js 17 KB

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