Home.js 17 KB

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