ClockMain.tsx 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995
  1. import { View, Text, Image, ScrollView, PageContainer, Swiper, SwiperItem, Switch } from "@tarojs/components";
  2. import Tabbar from "@/components/navigation/TabBar";
  3. import IndexItem from '@/features/trackTimeDuration/components/IndexItem';
  4. import Rings from "@/features/trackTimeDuration/components/Rings";
  5. import './Clock.scss'
  6. import { useDispatch, useSelector } from "react-redux";
  7. import { useDidHide, useDidShow, usePageScroll, useReady, useShareAppMessage } from "@tarojs/taro";
  8. import Taro from "@tarojs/taro";
  9. import { getInfoSuccess } from "@/store/user";
  10. import { clockHome, clockSummaryRecords, clockSummaryStats, getClockRecords, getClocks, getPlans } from "@/services/trackTimeDuration";
  11. import { updateScenario } from "@/store/time";
  12. import { setConfigs } from "@/store/common";
  13. import { setScenario, setStep } from "@/store/scenario";
  14. import { useEffect, useRef, useState } from "react";
  15. import { IconPlus, IconRadioCheck, IconRadioCross } from "@/components/basic/Icons";
  16. import { ColorType } from "@/context/themes/color";
  17. import { bigRingRadius, getBgRing, getCommon, getDot, getSchedule, ringWidth, smallRingRadius } from "@/features/trackTimeDuration/hooks/RingData";
  18. import { RealRing, CurrentDot } from "@/features/trackTimeDuration/components/Rings";
  19. import IndexConsole from "@/features/trackTimeDuration/components/IndexConsole";
  20. import Modal from '@/components/layout/Modal.weapp'
  21. import { compareVersion, getTimezone, getTimezoneId, getTimezoneName, kIsIOS, rpxToPx } from "@/utils/tools";
  22. import RecordFastSleep from "@/features/trackTimeDuration/components/RecordFastSleep";
  23. import WeekCalendar from "@/features/trackTimeDuration/components/WeekCalendar";
  24. import { useTranslation } from "react-i18next";
  25. import { jumpPage } from "@/features/trackTimeDuration/hooks/Common";
  26. import Layout from "@/components/layout/layout";
  27. import { ModalType, NaviBarTitleShowType, TemplateType } from "@/utils/types";
  28. import ClockHeader from "@/features/trackTimeDuration/components/ClockHeader";
  29. import DurationPicker from "@/features/trackTimeDuration/components/DurationPicker";
  30. import SegmentPop from "@/features/trackTimeDuration/components/SegmentPop";
  31. import Box from "@/components/layout/Box";
  32. import DayNightCard from "@/features/daynight/DayNightCard";
  33. import StageSelector from "@/features/trackTimeDuration/components/StageSelector";
  34. import { ChooseScenarioBtn } from "@/features/common/SpecBtns";
  35. import { clearNightStore, showNight } from "@/store/night";
  36. import { showDay } from "@/store/day";
  37. import { clientInfo, staticResources, systemVersion } from "@/services/common";
  38. import { changeFastDuration, changeSleepDuration, setCurrentRecord, setSchedule } from "@/store/ring";
  39. import { checkAuthorized } from "@/utils/check_authorized";
  40. import { AtActivityIndicator } from "taro-ui";
  41. import Tooltip from "@/components/view/Tooltip";
  42. import AllRings from "@/features/daynight/AllRings";
  43. import Streaks from "@/features/trackTimeDuration/components/Streaks";
  44. import dayjs from 'dayjs'
  45. import DayNightSwiper from "@/features/daynight/DayNightSwiper";
  46. import showAlert from "@/components/basic/Alert";
  47. import { APP_VERSION, WX_VERSION } from "@/services/http/api";
  48. import { wxPubFollow } from "@/services/permission";
  49. import { repeat } from "lodash";
  50. import { setWXFollow } from "@/store/permission";
  51. import Discovery from "@/features/trackTimeDuration/components/Discovery";
  52. import NoData from "@/components/view/NoData";
  53. import { getLocalPush } from "@/features/trackTimeDuration/actions/TrackTimeActions";
  54. import { TimeFormatter } from "@/utils/time_format";
  55. import { userAccess } from "@/services/user";
  56. const utc = require('dayjs/plugin/utc')
  57. const timezone = require('dayjs/plugin/timezone')
  58. dayjs.extend(utc)
  59. dayjs.extend(timezone)
  60. let GradientText
  61. let useNavigation;
  62. let timer
  63. let pauseTimer = false;
  64. let AppState;
  65. let needScroll = false;
  66. let showUpdate = false;
  67. let Linking;
  68. let PushNotification;
  69. let checkNotification, uploadPermissions, NativeAppEventEmitter;
  70. let messaging;
  71. if (process.env.TARO_ENV == 'rn') {
  72. messaging = require('@react-native-firebase/messaging').default
  73. PushNotification = require('react-native-push-notification')
  74. Linking = require('react-native').Linking;
  75. AppState = require("react-native").AppState
  76. NativeAppEventEmitter = require("react-native").NativeAppEventEmitter
  77. GradientText = require('@/components/basic/GradientText').default
  78. useNavigation = require("@react-navigation/native").useNavigation
  79. checkNotification = require('@/utils/native_permission_check').checkNotification;
  80. uploadPermissions = require('@/utils/native_permission_check').uploadPermissions;
  81. }
  82. const defaultValue = `[{"scenario":{"name":"FAST_SLEEP","count":0,"schedule":{"fast":{"start_time":"15:00","end_time":"08:00"},"sleep":{"start_time":"22:00","end_time":"07:00"}}},"current_record":{"scenario":"FAST_SLEEP","status":"WAIT_FOR_START","fast":{"status":"WAIT_FOR_START","target_start_time":1710514800000,"target_end_time":1710576000000},"sleep":{"status":"WAIT_FOR_START","target_start_time":1710540000000,"target_end_time":1710572400000}},"wx_pub_followed":false,"time_input_schema":{"min":60,"max":1380,"step":5},"theme_color":{"fast":"#00FFFF","sleep":"#8183FF"}},{"scenarios":[{"name":"FAST","count":0,"schedule":{"fast":{"start_time":"15:00","end_time":"08:00"}}},{"name":"SLEEP","count":0,"schedule":{"sleep":{"start_time":"22:00","end_time":"07:00"}}},{"name":"FAST_SLEEP","count":0,"schedule":{"fast":{"start_time":"15:00","end_time":"08:00"},"sleep":{"start_time":"22:00","end_time":"07:00"}}}],"select_count":0,"theme_color":{"fast":"#00FFFF","sleep":"#8183FF"}}]`
  83. let fcmUnsubscribe: any = null;
  84. export default function Page() {
  85. const dispatch = useDispatch();
  86. global.dispatch = dispatch;
  87. let navigation;
  88. if (useNavigation) {
  89. navigation = useNavigation()
  90. }
  91. const { t } = useTranslation()
  92. const user = useSelector((state: any) => state.user);
  93. const time = useSelector((state: any) => state.time);
  94. const [count, setCount] = useState(0)
  95. const [homeData, setHomeData] = useState(null)
  96. const [loaded, setLoaded] = useState(false)
  97. const [showErrorPage, setErrorPage] = useState(false)
  98. const [showModal, setShowModal] = useState(false)
  99. const [modalDetail, setModalDetail] = useState<any>(null)
  100. const [showModal2, setShowModal2] = useState(false)
  101. const [modalDetail2, setModalDetail2] = useState<any>(null)
  102. const [debugInfo, setDebugInfo] = useState(null)
  103. const [needShowAddTip, setNeedShowAddTip] = useState(false)
  104. const [showTip, setShowTip] = useState(false)
  105. const [records, setRecords] = useState([])
  106. const [showEatCalendar, setShowEatCalendar] = useState(false)
  107. const [schedules, setSchedules] = useState<any>(null)
  108. const permission = useSelector((state: any) => state.permission);
  109. const common = useSelector((state: any) => state.common);
  110. const [access, setAccess] = useState<any>(null)
  111. const scrollRef = useRef(null);
  112. const nightStore = useSelector((state: any) => state.night);
  113. if (process.env.TARO_ENV == 'weapp') {
  114. useShareAppMessage((e) => {
  115. return {
  116. title: t('feature.track_time_duration.common.share_title'),
  117. path: 'pages/clock/Clock'
  118. }
  119. })
  120. }
  121. useEffect(() => {
  122. console.log(new Date().toString());
  123. dispatch(staticResources() as any);
  124. pauseTimer = false;
  125. mainTimer()
  126. if (process.env.TARO_ENV == 'rn') {
  127. NativeAppEventEmitter.addListener('openNotificationSetting', (data) => {
  128. jumpPage('/pages/account/ChooseAuth', 'NotificationSetting', navigation)
  129. })
  130. }
  131. }, [])
  132. function mainTimer() {
  133. if (timer) {
  134. clearInterval(timer)
  135. timer = null
  136. }
  137. timer = setInterval(() => {
  138. var now = new Date()
  139. if (now.getDay() == 0 && now.getHours() == 12 && now.getMinutes() == 0 && now.getSeconds() == 0) {
  140. if (global.refrehWeekly) {
  141. global.refrehWeekly()
  142. }
  143. }
  144. if (global.pauseIndexTimer || pauseTimer) {
  145. return
  146. }
  147. setCount((prevCounter) => prevCounter + 1)
  148. }, 1000)
  149. }
  150. useEffect(() => {
  151. if (process.env.TARO_ENV == 'rn') {
  152. AppState.addEventListener('change', handleAppStateChange);
  153. }
  154. }, [])
  155. useEffect(() => {
  156. getCheckData()
  157. if (user.isLogin) {
  158. uploadUserClient();
  159. checkAuthorized();
  160. //检查用户是否添加过小程序
  161. checkAddToMini();
  162. wxPubFollow({ force_refresh: true }).then(res => {
  163. dispatch(setWXFollow((res as any).wx_pub_followed));
  164. })
  165. if (process.env.TARO_ENV == 'rn') {
  166. if (kIsIOS) {
  167. var Jto = require('react-native').NativeModules.NativeBridge;
  168. Jto.getNotificationAuthStatus()
  169. // Jto.rnPageLoaded()
  170. NativeAppEventEmitter.addListener('notificationResult', (data) => {
  171. console.log('notification auth result', data)
  172. global.notification = data;
  173. uploadPermissions()
  174. })
  175. }
  176. // uploadPermissions()
  177. // JPush.isNotificationEnabled((res) => {
  178. // if (res) {
  179. // const test = require('@/utils/push').default
  180. // test()
  181. // }
  182. // })
  183. checkVersionUpdate()
  184. }
  185. }
  186. else {
  187. dispatch(clearNightStore());
  188. }
  189. }, [user.isLogin])
  190. useReady(async () => {
  191. const userData = await getStorage('userData');
  192. if (userData) {
  193. dispatch(getInfoSuccess(JSON.parse(userData as string)) as any);
  194. getHistory()
  195. }
  196. })
  197. async function checkVersionUpdate() {
  198. if (!user.isLogin) {
  199. return
  200. }
  201. if (process.env.TARO_ENV == 'rn') {
  202. systemVersion().then(res => {
  203. if ((res as any).result == 'UPDATE' && !showUpdate) {
  204. showUpdate = true
  205. showAlert({
  206. title: (res as any).title,
  207. content: (res as any).description,
  208. showCancel: true,
  209. confirmText: 'Update',
  210. confirm: () => {
  211. Linking.openURL((res as any).download_url)
  212. }
  213. })
  214. }
  215. else if ((res as any).result == 'FORCE_UPDATE') {
  216. showAlert({
  217. title: (res as any).title,
  218. content: (res as any).description,
  219. showCancel: false,
  220. confirmText: 'Update',
  221. confirm: () => {
  222. Linking.openURL((res as any).download_url)
  223. }
  224. })
  225. }
  226. })
  227. return;
  228. }
  229. const showAlert1 = await getStorage('121alert') || false;
  230. if (!showAlert1) {
  231. showAlert({
  232. title: '重要更新提示',
  233. content: '🔥 连续打卡天数现根据结束日期统计;\n 🪐 断食与睡眠升级为高级功能。\n连续打卡的老用户仍可继续使用。\n更多高级功能如『进食窗口』显示、『社区排行』等敬请期待!',
  234. showCancel: false,
  235. confirmText: '我知道了'
  236. })
  237. }
  238. Taro.setStorage({ key: '121alert', data: true })
  239. }
  240. function checkAddToMini() {
  241. if (process.env.TARO_ENV == 'weapp') {
  242. const version = Taro.getAppBaseInfo().SDKVersion
  243. if (compareVersion(version, '2.30.3') >= 0) {
  244. wx.checkIsAddedToMyMiniProgram({
  245. success: (res) => {
  246. if (!res.added) {
  247. setNeedShowAddTip(true)
  248. }
  249. },
  250. fail: (e) => {
  251. }
  252. });
  253. }
  254. }
  255. }
  256. useDidShow(() => {
  257. if (process.env.TARO_ENV == 'weapp') {
  258. checkTimeZone()
  259. }
  260. else {
  261. if (!kIsIOS) {
  262. updateNotificationStatus()
  263. }
  264. }
  265. setCount(pre => pre + 1)
  266. //resume timer
  267. pauseTimer = false
  268. if (user.isLogin) {
  269. if (global.refreshRecent) {
  270. global.refreshRecent()
  271. }
  272. }
  273. setTimeout(() => {
  274. checkVersionUpdate();
  275. updateNotificationStatus();
  276. }, 1000)
  277. })
  278. usePageScroll((e) => {
  279. if (e.scrollTop > 70) {
  280. setShowTip(true)
  281. }
  282. else {
  283. setShowTip(false)
  284. }
  285. })
  286. useDidHide(() => {
  287. //pause timer
  288. pauseTimer = true
  289. })
  290. global.refreshIndex = () => {
  291. setCount((prevCounter) => prevCounter + 1)
  292. }
  293. const handleAppStateChange = (nextAppState) => {
  294. console.log(nextAppState)
  295. if (nextAppState != 'active') {
  296. return
  297. }
  298. if (nextAppState == 'active') {
  299. checkTimeZone()
  300. updateNotificationStatus()
  301. mainTimer()
  302. }
  303. };
  304. function updateNotificationStatus() {
  305. if (process.env.TARO_ENV == 'rn') {
  306. if (user.isLogin) {
  307. if (kIsIOS) {
  308. var Jto = require('react-native').NativeModules.NativeBridge;
  309. Jto.getNotificationAuthStatus()
  310. }
  311. else {
  312. uploadPermissions()
  313. }
  314. }
  315. // JPush.setBadge({
  316. // badge: 0,
  317. // appBadge: 0
  318. // })
  319. }
  320. }
  321. function checkTimeZone() {
  322. getLocalPush()
  323. setCount((prevCounter) => prevCounter + 1)
  324. var timeZoneFormatted = getTimezone()
  325. Taro.getStorage({
  326. key: 'last_tz',
  327. success: function (res) {
  328. if (res.data && res.data != timeZoneFormatted) {
  329. if (global.refrehWeekly) {
  330. global.refrehWeekly()
  331. }
  332. global.indexPageRefresh()
  333. // if (global.refreshNight){
  334. // global.refreshNight()
  335. // }
  336. // if (global.refreshDay){
  337. // global.refreshDay()
  338. // }
  339. // if (global.currentStatus != 'WAIT_FOR_START') {
  340. showAlert({
  341. title: t('feature.track_time_duration.change_tz_alert.title'),
  342. content: t('feature.track_time_duration.change_tz_alert.content', { tz: timeZoneFormatted }),
  343. showCancel: false,
  344. confirmText: t('feature.track_time_duration.change_tz_alert.confirm'),
  345. })
  346. // }
  347. }
  348. },
  349. complete: function () {
  350. Taro.setStorage({ key: 'last_tz', data: timeZoneFormatted })
  351. }
  352. })
  353. }
  354. function uploadUserClient() {
  355. var systemInfo = Taro.getSystemInfoSync();
  356. console.log(systemInfo)
  357. var language: any = systemInfo.language
  358. if (process.env.TARO_ENV == 'rn') {
  359. var NativeModules = require('react-native').NativeModules;
  360. if (kIsIOS) {
  361. // language = NativeModules.SettingsManager.settings.AppleLocale
  362. // languageList = NativeModules.SettingsManager.settings.AppleLanguages
  363. language = {
  364. AppleLocale: NativeModules.SettingsManager.settings.AppleLocale,
  365. AppleLanguages: NativeModules.SettingsManager.settings.AppleLanguages,
  366. NSLanguages: NativeModules.SettingsManager.settings.NSLanguages
  367. }
  368. }
  369. else {
  370. language = NativeModules.I18nManager.localeIdentifier
  371. }
  372. // iOS:
  373. // var locale = NativeModules.SettingsManager.settings.AppleLocale ||
  374. // NativeModules.SettingsManager.settings.AppleLanguages[0] // "fr_FR"
  375. // showAlert({
  376. // title: 'locale',
  377. // content: JSON.stringify(NativeModules.SettingsManager.settings)
  378. // })
  379. // Android:
  380. // locale = NativeModules.I18nManager.localeIdentifier // "fr_FR"
  381. }
  382. var timeZoneFormatted = getTimezone()
  383. var timeZoneId = ''
  384. var timeZoneName = ''
  385. if (kIsIOS) {
  386. timeZoneId = getTimezoneId()
  387. timeZoneName = getTimezoneName()
  388. }
  389. else {
  390. timeZoneId = getTimezoneId()
  391. timeZoneName = getTimezoneName()
  392. }
  393. var clientInfoParams = {
  394. client: {
  395. client_type: process.env.TARO_ENV == 'weapp' ? 'MP' : 'APP',
  396. client_version: process.env.TARO_ENV == 'weapp' ? WX_VERSION : APP_VERSION,//Taro.getAccountInfoSync().miniProgram.version : '1.0',//'1.0'
  397. wx_version: process.env.TARO_ENV == 'weapp' ? systemInfo.version : '_'
  398. },
  399. meta: {
  400. language: language,
  401. timezone: {
  402. gmt: timeZoneFormatted,
  403. id: timeZoneId,
  404. name: timeZoneName
  405. },
  406. },
  407. device: {
  408. brand: systemInfo.brand,
  409. model: systemInfo.model,
  410. platform: systemInfo.platform,
  411. system: systemInfo.system
  412. },
  413. }
  414. if (process.env.TARO_ENV == 'weapp') {
  415. (clientInfoParams as any).perm = {
  416. wxmp: {
  417. wifi_enabled: systemInfo.wifiEnabled,
  418. location_authorized: systemInfo.locationAuthorized,
  419. location_enabled: systemInfo.locationEnabled
  420. }
  421. }
  422. }
  423. clientInfo(clientInfoParams)
  424. }
  425. function getCheckData() {
  426. Promise.all([getClocks(), getPlans()]).then((list) => {
  427. setErrorPage(false)
  428. setCheckData(list)
  429. if (needScroll) {
  430. needScroll = false
  431. if (process.env.TARO_ENV == 'weapp') {
  432. setTimeout(() => {
  433. Taro.createSelectorQuery().select('#latest').boundingClientRect((rect) => {
  434. Taro.pageScrollTo({
  435. scrollTop: (rect as any).top,
  436. duration: 150
  437. })
  438. }).exec()
  439. }, 100)
  440. }
  441. else {
  442. // (scrollRef.current as any).scrollTo({ y: rpxToPx(400), animated: true })
  443. }
  444. }
  445. if (process.env.TARO_ENV == 'rn' && user.isLogin) {
  446. if (kIsIOS) {
  447. var Jto = require('react-native').NativeModules.NativeBridge;
  448. Jto.rnPageLoaded()
  449. }
  450. else {
  451. var Jto = require('react-native').NativeModules.NativeBridge;
  452. Jto.rnPageLoaded()
  453. }
  454. }
  455. setLoaded(true)
  456. }).catch((e) => {
  457. setErrorPage(true)
  458. var list = JSON.parse(defaultValue)
  459. setCheckData(list)
  460. needScroll = false
  461. setLoaded(true)
  462. })
  463. if (user.isLogin) {
  464. getHistory()
  465. userAccess().then(res => {
  466. console.log('useraccess', res)
  467. setAccess(res)
  468. })
  469. }
  470. }
  471. global.refreshAccess = (res) => {
  472. setAccess(res)
  473. }
  474. function setCheckData(list: any) {
  475. setHomeData(list[0])
  476. setSchedules(list[1].scenarios)
  477. global.homeData = list[0]
  478. global.currentStatus = list[0].current_record.status;
  479. var array = list[1].scenarios
  480. var schedule: any = null
  481. array.map(item => {
  482. if (item.name == 'FAST_SLEEP') {
  483. schedule = item.schedule;
  484. schedule.sleep.prev_input = item.prev_input;
  485. schedule.sleep.valid = item.valid;
  486. }
  487. })
  488. if (user.isLogin) {
  489. dispatch(updateScenario(list[0].current_record))
  490. dispatch(setConfigs(list[0].time_input_schema));
  491. dispatch(setScenario(list[0].scenario));
  492. global.scenario = list[0].scenario.name;
  493. }
  494. dispatch(setCurrentRecord(list[0].current_record))
  495. dispatch(setSchedule(schedule))
  496. // setLoaded(true)
  497. }
  498. function getHistory() {
  499. if (user.isLogin)
  500. getClockRecords({
  501. page: 1,
  502. limit: 1,
  503. // part_completed: true
  504. completed: true
  505. }).then(res => {
  506. setRecords((res as any).data)
  507. })
  508. }
  509. global.indexPageRefresh = () => {
  510. if (global.refreshStreaks) {
  511. global.refreshStreaks()
  512. }
  513. getCheckData()
  514. if (global.swiperDayNightRefresh) {
  515. global.swiperDayNightRefresh()
  516. }
  517. }
  518. global.showIndexModal = (isShow: boolean, detail: any, debugNode?: any) => {
  519. global.showModal = isShow
  520. setDebugInfo(debugNode)
  521. setShowModal(isShow)
  522. setModalDetail(detail)
  523. }
  524. global.showIndexModal2 = (isShow: boolean, detail: any) => {
  525. setDebugInfo(null)
  526. global.showModal = isShow
  527. setShowModal2(isShow)
  528. setModalDetail2(detail)
  529. }
  530. global.changeTargetDuration = (duration: number, isFast: boolean) => {
  531. var obj = JSON.parse(JSON.stringify(homeData))
  532. var record = obj.current_record
  533. if (isFast) {
  534. record.fast.target_end_time = record.fast.target_start_time + duration * 60 * 1000
  535. }
  536. else {
  537. record.sleep.target_end_time = record.sleep.target_start_time + duration * 60 * 1000
  538. }
  539. setHomeData(obj)
  540. }
  541. global.updateFastSleepData = (data: any, schedule?: any) => {
  542. if (data.id == (homeData as any).current_record.id) {
  543. var obj = JSON.parse(JSON.stringify(homeData))
  544. obj.current_record = data
  545. if (schedule) {
  546. obj.scenario.schedule = schedule
  547. }
  548. setHomeData(obj)
  549. }
  550. switch (data.scenario) {
  551. case 'FAST':
  552. if (data.status == 'WAIT_FOR_START') {
  553. dispatch(changeFastDuration(data.fast.target_end_time - data.fast.target_start_time))
  554. }
  555. break;
  556. case 'SLEEP':
  557. if (data.status == 'WAIT_FOR_START') {
  558. dispatch(changeSleepDuration(data.sleep.target_end_time - data.sleep.target_start_time))
  559. }
  560. break;
  561. case 'FAST_SLEEP':
  562. if (data.status == 'WAIT_FOR_START') {
  563. dispatch(changeFastDuration(data.fast.target_end_time - data.fast.target_start_time))
  564. }
  565. else if (data.status == 'ONGOING1') {
  566. dispatch(changeSleepDuration(data.sleep.target_end_time - data.sleep.target_start_time))
  567. }
  568. break;
  569. }
  570. }
  571. global.popScheduleAlert = (scenario, startTime) => {
  572. if (process.env.TARO_ENV == 'weapp') {
  573. if (permission.wxPubFollow) {
  574. }
  575. else {
  576. showAlert({
  577. title: t('feature.track_time_duration.reminders.schedule_title'),
  578. content: scenario.name == 'FAST' ?
  579. t('feature.track_time_duration.reminders.schedule_fast_content', { time: startTime }) :
  580. t('feature.track_time_duration.reminders.schedule_sleep_content', { time: startTime }),
  581. cancelText: t('feature.track_time_duration.reminders.later'),
  582. confirmText: t('feature.track_time_duration.reminders.open'),
  583. showCancel: true,
  584. confirm: () => {
  585. followWxPub()
  586. }
  587. })
  588. }
  589. }
  590. else {
  591. PushNotification.checkPermissions((res) => {
  592. //允许授权
  593. if ((kIsIOS && res.authorizationStatus == 2) || (!kIsIOS && res.alert)) {
  594. }
  595. else {
  596. showAlert({
  597. title: t('feature.track_time_duration.reminders.schedule_title'),
  598. content: scenario.name == 'FAST' ?
  599. t('feature.track_time_duration.reminders.schedule_fast_content', { time: startTime }) :
  600. t('feature.track_time_duration.reminders.schedule_sleep_content', { time: startTime }),
  601. cancelText: t('feature.track_time_duration.reminders.later'),
  602. confirmText: t('feature.track_time_duration.reminders.open'),
  603. showCancel: true,
  604. confirm: () => {
  605. checkNotification()
  606. // Linking.openURL('app-settings:notifications')
  607. }
  608. })
  609. }
  610. })
  611. }
  612. }
  613. global.popMixScheduleAlert = (time1, time2) => {
  614. if (process.env.TARO_ENV == 'weapp') {
  615. if (permission.wxPubFollow) {
  616. }
  617. else {
  618. showAlert({
  619. title: t('feature.track_time_duration.reminders.schedule_title'),
  620. content:
  621. t('feature.track_time_duration.reminders.schedule_mix_content'),
  622. cancelText: t('feature.track_time_duration.reminders.later'),
  623. confirmText: t('feature.track_time_duration.reminders.open'),
  624. showCancel: true,
  625. confirm: () => {
  626. followWxPub()
  627. }
  628. })
  629. }
  630. }
  631. else {
  632. PushNotification.checkPermissions((res) => {
  633. //允许授权
  634. if ((kIsIOS && res.authorizationStatus == 2) || (!kIsIOS && res.alert)) {
  635. }
  636. else {
  637. showAlert({
  638. title: t('feature.track_time_duration.reminders.schedule_title'),
  639. content:
  640. t('feature.track_time_duration.reminders.schedule_mix_content'),
  641. cancelText: t('feature.track_time_duration.reminders.later'),
  642. confirmText: t('feature.track_time_duration.reminders.open'),
  643. showCancel: true,
  644. confirm: () => {
  645. checkNotification()
  646. // Linking.openURL('app-settings:notifications')
  647. }
  648. })
  649. }
  650. })
  651. }
  652. }
  653. function followWxPub() {
  654. const resource = common.resources.filter((item: any) => {
  655. return item.code == 'follow_wx_pub'
  656. })
  657. jumpPage('/pages/common/H5?title=fast16cc 关注服务号&url=' + resource[0].url)
  658. }
  659. function modalContent() {
  660. if (showModal || showModal2) {
  661. return <Modal
  662. testInfo={debugInfo}
  663. dismiss={() => {
  664. setDebugInfo(null)
  665. setShowModal(false);
  666. setShowModal2(false);
  667. global.pauseIndexTimer = false
  668. }}
  669. confirm={() => { }}>
  670. {
  671. showModal ? modalDetail : modalDetail2
  672. }
  673. </Modal>
  674. }
  675. return <View />
  676. }
  677. async function getStorage(key: string) {
  678. try {
  679. const res = await Taro.getStorage({ key });
  680. return res.data;
  681. } catch {
  682. return '';
  683. }
  684. }
  685. function more() {
  686. jumpPage('/pages/common/RecordsHistory?type=time&title=time', 'RecordsHistory', navigation, {
  687. type: 'time',
  688. title: 'time'
  689. })
  690. }
  691. function tapLogin() {
  692. if (!user.isLogin) {
  693. jumpPage('/pages/account/ChooseAuth', 'ChooseAuth', navigation)
  694. }
  695. }
  696. function headerView() {
  697. return <ClockHeader homeData={homeData} />
  698. }
  699. global.scrollToLatest = () => {
  700. needScroll = true;
  701. }
  702. var timestamp = new Date().getTime()
  703. function goSetting() {
  704. if (process.env.TARO_ENV == 'weapp') {
  705. Taro.navigateTo({
  706. url: '/pages/notification/setting'
  707. })
  708. }
  709. else {
  710. jumpPage('/pages/account/ChooseAuth', 'NotificationSetting', navigation)
  711. }
  712. }
  713. function eatCalendarContent() {
  714. return <View style={{ display: 'flex', flexDirection: 'column' }}>
  715. <View className="index_section">
  716. <Text className="index_section_title">{t('feature.track_time_duration.weekly.title')}</Text>
  717. </View>
  718. <WeekCalendar isFastSleep={false} />
  719. <View className="vip_calendar" style={{ marginBottom: 40 }} onClick={() => setShowEatCalendar(false)}>
  720. <Text style={{ color: '#fff' }}>关闭</Text>
  721. </View>
  722. </View>
  723. }
  724. function render() {
  725. var smallTitle = ''
  726. const weekday = TimeFormatter.getDayOfWeek(new Date().getDay(), true);
  727. const date = global.language == 'en' ? dayjs().format('MMMM DD') : dayjs().format('M月D日 ')
  728. smallTitle = global.language == 'en' ? (weekday + ', ' + date) : (date + weekday);
  729. if (!loaded) {
  730. return <Layout type={TemplateType.customHeader} header={headerView()} title={smallTitle} titleShowStyle={NaviBarTitleShowType.scrollToShow}>
  731. <View style={{ width: rpxToPx(750), height: rpxToPx(900), display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center' }}>
  732. <AtActivityIndicator size={40} color="#fff" />
  733. {
  734. process.env.TARO_ENV == 'weapp' && <Tabbar index={0} />
  735. }
  736. </View>
  737. </Layout>
  738. }
  739. return <Layout type={TemplateType.customHeader} header={headerView()} title={smallTitle} titleShowStyle={NaviBarTitleShowType.scrollToShow}>
  740. <View className="index_container">
  741. {
  742. needShowAddTip && showTip && <Tooltip title="添加到我的小程序" closeTip={() => { setNeedShowAddTip(false) }} />
  743. }
  744. <Text className="count">{count}</Text>
  745. <Box>
  746. <View>
  747. <IndexItem type="FAST_SLEEP" data={homeData} time={timestamp} showStage={false} />
  748. {
  749. user.isLogin ? <IndexConsole record={homeData} count={count} access={access} /> : <StageSelector />
  750. }
  751. </View>
  752. </Box>
  753. {/*
  754. <Text style={{color:'#fff',fontSize:30}} onClick={goSetting}>notification setting</Text> */}
  755. {
  756. user.isLogin && records && records.length > 0 && <View className="index_section" style={{ marginTop: -rpxToPx(25 - 12), marginBottom: -rpxToPx(20) }}>
  757. <Text className="index_section_title">{t('feature.track_time_duration.record_fast_sleep.header.latest_record')}</Text>
  758. {
  759. process.env.TARO_ENV == 'weapp' && <Text className="fast_sleep_more index_more" onClick={more}>{t('feature.track_time_duration.record_fast_sleep.header.btn_show_all')}</Text>
  760. }
  761. {
  762. process.env.TARO_ENV == 'rn' && <View onClick={more}>
  763. <GradientText style={{ fontSize: rpxToPx(32), fontWeight: 'bold', color: 'black' }}>{t('feature.track_time_duration.record_fast_sleep.header.btn_show_all')}</GradientText>
  764. </View>
  765. }
  766. </View>
  767. }
  768. {
  769. user.isLogin && records && records.length == 0 && <View style={{ marginTop: -rpxToPx(25) }} />
  770. }
  771. {
  772. user.isLogin && records && records.length > 0 && <View id="latest" className="fast_sleep_item_bg">
  773. <RecordFastSleep data={records[0]} type='record' index={-20000} />
  774. </View>
  775. }
  776. {
  777. loaded && !user.isLogin && <View style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', marginTop: rpxToPx(36) }}>
  778. <ChooseScenarioBtn title={t('feature.auth.login.login_now')} background={ColorType.fast} onClick={tapLogin} />
  779. </View>
  780. }
  781. {
  782. showErrorPage && <NoData refresh={() => { getCheckData() }} />
  783. }
  784. {
  785. user.isLogin && <Streaks count={count} />
  786. }
  787. {
  788. user.isLogin && !showErrorPage && <View style={{ display: 'flex', flexDirection: 'column' }}>
  789. <View className="index_section">
  790. <Text className="index_section_title">{t('feature.track_time_duration.weekly.title')}</Text>
  791. </View>
  792. <WeekCalendar isFastSleep={true} />
  793. <View className="vip_calendar" onClick={() => setShowEatCalendar(true)}>
  794. <Text style={{ color: '#fff' }}>Show eating and wake windows</Text>
  795. </View>
  796. </View>
  797. }
  798. {
  799. showEatCalendar && <Modal
  800. testInfo={null}
  801. dismiss={() => {
  802. setShowEatCalendar(false)
  803. }}
  804. confirm={() => { }}>
  805. {
  806. eatCalendarContent()
  807. }
  808. </Modal>
  809. }
  810. {
  811. user.isLogin && !showErrorPage && <View className="index_section" style={{ height: rpxToPx(120), marginTop: rpxToPx(40) }}>
  812. <Text className="index_main_title">{t('feature.pro.for_pro')}</Text>
  813. </View>
  814. }
  815. {
  816. user.isLogin && !showErrorPage && <View className="index_section" style={{ marginBottom: -rpxToPx(10), marginTop: -rpxToPx(40) }}>
  817. <Text className="index_section_title">{t('feature.day_night.group_title')}</Text>
  818. </View>
  819. }
  820. {
  821. user.isLogin && !showErrorPage && <DayNightSwiper count={count} schedule={schedules} homeData={homeData} />
  822. }
  823. {
  824. user.isLogin && (process.env.TARO_ENV == 'weapp') && <View className="index_section">
  825. <Text className="index_section_title">{t('page.explore.title')}</Text>
  826. </View>
  827. }
  828. {
  829. user.isLogin && (process.env.TARO_ENV == 'weapp') && <Discovery />
  830. }
  831. {
  832. modalContent()
  833. }
  834. {
  835. homeData && <SegmentPop data={homeData} />
  836. }
  837. {
  838. homeData && <DurationPicker record={(homeData as any).current_record} />
  839. }
  840. {
  841. user.isLogin && user.test_user && homeData && access && <View style={{ display: 'flex', flexDirection: 'column' }}>
  842. <Text style={{ color: '#fff', fontSize: 15 }}>member status:{access && access.member && access.member.status}</Text>
  843. {
  844. access && access.member && access.member.status=='MEMBER' &&
  845. <Text style={{ color: '#fff', fontSize: 15 }}>会员过期时间:{TimeFormatter.countdown(access.member.expire)}</Text>
  846. }
  847. <Text style={{ color: '#fff', fontSize: 15 }}>current status:{access.fast_sleep.current.qualification.status}</Text>
  848. <Text style={{ color: '#fff', fontSize: 15 }}>previous status:{access.fast_sleep.previous.qualification.status}</Text>
  849. <Text style={{ color: '#fff', fontSize: 15 }}>trigger event:{access.fast_sleep.current.qualification.trigger_event}</Text>
  850. <Text style={{ color: '#fff', fontSize: 15 }}>lost_access_total:{access.fast_sleep.current.qualification.condition.lost_access_total}</Text>
  851. <Text style={{ color: '#fff', fontSize: 15 }}>streak_fast_min_required:{access.fast_sleep.current.qualification.condition.streak_fast_min_required}</Text>
  852. </View>
  853. }
  854. {
  855. process.env.TARO_ENV == 'weapp' && <View style={{ height: 100 }} />
  856. }
  857. <Tabbar index={0} />
  858. </View>
  859. </Layout>
  860. }
  861. return render()
  862. }