Home.js 16 KB

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