Home.js 17 KB

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