| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048 |
- import { View, Text, Image, ScrollView, PageContainer, Swiper, SwiperItem, Switch } from "@tarojs/components";
- import Tabbar from "@/components/navigation/TabBar";
- import IndexItem from '@/features/trackTimeDuration/components/IndexItem';
- import Rings from "@/features/trackTimeDuration/components/Rings";
- import './Clock.scss'
- import { useDispatch, useSelector } from "react-redux";
- import { useDidHide, useDidShow, usePageScroll, useReady, useShareAppMessage } from "@tarojs/taro";
- import Taro from "@tarojs/taro";
- import { getInfoSuccess } from "@/store/user";
- import { clockHome, clockSummaryRecords, clockSummaryStats, getClockRecords, getClocks, getPlans } from "@/services/trackTimeDuration";
- import { updateScenario } from "@/store/time";
- import { setConfigs } from "@/store/common";
- import { setScenario, setStep } from "@/store/scenario";
- import { useEffect, useRef, useState } from "react";
- import { IconPlus, IconRadioCheck, IconRadioCross } from "@/components/basic/Icons";
- import { ColorType } from "@/context/themes/color";
- import { bigRingRadius, getBgRing, getCommon, getDot, getSchedule, ringWidth, smallRingRadius } from "@/features/trackTimeDuration/hooks/RingData";
- import { RealRing, CurrentDot } from "@/features/trackTimeDuration/components/Rings";
- import IndexConsole from "@/features/trackTimeDuration/components/IndexConsole";
- import Modal from '@/components/layout/Modal'
- import { compareVersion, getTimezone, getTimezoneId, getTimezoneName, rpxToPx } from "@/utils/tools";
- import RecordFastSleep from "@/features/trackTimeDuration/components/RecordFastSleep";
- import DayLight from "@/features/trackTimeDuration/components/DayLight";
- import { getInfo, latestLocation } from "@/services/user";
- import { TimeFormatter } from "@/utils/time_format";
- import WeekCalendar from "@/features/trackTimeDuration/components/WeekCalendar";
- import { useTranslation } from "react-i18next";
- import { jumpPage } from "@/features/trackTimeDuration/hooks/Common";
- import Layout from "@/components/layout/layout";
- import { ModalType, NaviBarTitleShowType, TemplateType } from "@/utils/types";
- import TitleView from "@/features/trackTimeDuration/components/TitleView";
- import ClockHeader from "@/features/trackTimeDuration/components/ClockHeader";
- import DurationPicker from "@/features/trackTimeDuration/components/DurationPicker";
- import SegmentPop from "@/features/trackTimeDuration/components/SegmentPop";
- import Box from "@/components/layout/Box";
- import DayNightCard from "@/features/daynight/DayNightCard";
- import StageSelector from "@/features/trackTimeDuration/components/StageSelector";
- import { ChooseScenarioBtn } from "@/features/common/SpecBtns";
- import { clearNightStore, showNight } from "@/store/night";
- import { showDay } from "@/store/day";
- import { clientInfo, staticResources, systemVersion } from "@/services/common";
- import { changeFastDuration, changeSleepDuration, setCurrentRecord, setSchedule } from "@/store/ring";
- import { checkAuthorized } from "@/utils/check_authorized";
- import NoData from "@/components/view/NoData";
- import { AtActivityIndicator } from "taro-ui";
- import Tooltip from "@/components/view/Tooltip";
- import AllRings from "@/features/daynight/AllRings";
- import Streaks from "@/features/trackTimeDuration/components/Streaks";
- import dayjs from 'dayjs'
- import DayNightSwiper from "@/features/daynight/DayNightSwiper";
- import showAlert from "@/components/basic/Alert";
- import { APP_VERSION, WX_VERSION } from "@/services/http/api";
- import { wxPubFollow } from "@/services/permission";
- import { repeat } from "lodash";
- import { setWXFollow } from "@/store/permission";
- const utc = require('dayjs/plugin/utc')
- const timezone = require('dayjs/plugin/timezone')
- dayjs.extend(utc)
- dayjs.extend(timezone)
- let GradientText
- let useNavigation;
- let timer
- let pauseTimer = false;
- let AppState;
- let needScroll = false;
- let showUpdate = false;
- let Linking;
- let JPush;
- let checkNotification, uploadPermissions, NativeAppEventEmitter;
- let messaging;
- let PushNotification;
- let Importance;
- if (process.env.TARO_ENV == 'rn') {
- messaging = require('@react-native-firebase/messaging').default
- JPush = require('jpush-react-native').default;
- Linking = require('react-native').Linking;
- AppState = require("react-native").AppState
- NativeAppEventEmitter = require("react-native").NativeAppEventEmitter
- GradientText = require('@/components/basic/GradientText').default
- useNavigation = require("@react-navigation/native").useNavigation
- checkNotification = require('@/utils/native_permission_check').checkNotification;
- uploadPermissions = require('@/utils/native_permission_check').uploadPermissions;
- PushNotification = require('react-native-push-notification')
- Importance = require('react-native-push-notification').Importance
- }
- 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"}}]`
- let fcmUnsubscribe: any = null;
- export default function Page() {
- const dispatch = useDispatch();
- global.dispatch = dispatch;
- let navigation;
- if (useNavigation) {
- navigation = useNavigation()
- }
- const { t } = useTranslation()
- const user = useSelector((state: any) => state.user);
- const time = useSelector((state: any) => state.time);
- const [count, setCount] = useState(0)
- const [homeData, setHomeData] = useState(null)
- const [loaded, setLoaded] = useState(false)
- const [showErrorPage, setErrorPage] = useState(false)
- const [showModal, setShowModal] = useState(false)
- const [modalDetail, setModalDetail] = useState<any>(null)
- const [showModal2, setShowModal2] = useState(false)
- const [modalDetail2, setModalDetail2] = useState<any>(null)
- const [debugInfo, setDebugInfo] = useState(null)
- const [needShowAddTip, setNeedShowAddTip] = useState(false)
- const [showTip, setShowTip] = useState(false)
- const [records, setRecords] = useState([])
- const permission = useSelector((state: any) => state.permission);
- const common = useSelector((state: any) => state.common);
- const scrollRef = useRef(null);
- const nightStore = useSelector((state: any) => state.night);
- if (process.env.TARO_ENV == 'weapp') {
- useShareAppMessage((e) => {
- return {
- title: t('feature.track_time_duration.common.share_title'),
- path: 'pages/clock/Clock'
- }
- })
- }
- useEffect(() => {
- console.log(new Date().toString());
- dispatch(staticResources() as any);
- timer = setInterval(() => {
- var now = new Date()
- if (now.getDay() == 0 && now.getHours() == 12 && now.getMinutes() == 0 && now.getSeconds() == 0) {
- if (global.refrehWeekly) {
- global.refrehWeekly()
- }
- }
- if (global.pauseIndexTimer || pauseTimer) {
- return
- }
- setCount((prevCounter) => prevCounter + 1)
- }, 1000)
- }, [])
- useEffect(() => {
- // Taro.request({
- // url:'https://api.fast.dev.liveplus.fun/api/static-resource-urls',
- // method:'GET',
- // data:{},
- // timeout:20000,
- // success(result) {
- // showAlert({
- // title:'success',
- // content:JSON.stringify(result)
- // })
- // },
- // fail(res) {
- // showAlert({
- // title:'fail',
- // content:JSON.stringify(res)
- // })
- // },
- // })
- if (process.env.TARO_ENV == 'weapp') {
- loadWXCache()
- }
- else {
- loadRNCache()
- PushNotification.configure({
- onRegister: function (token) {
- console.log('TOKEN:', token);
- },
- onNotification: function (notification) {
- console.log('NOTIFICATION:', notification);
- // notification.finish(PushNotificationIOS.FetchResult.NoData);
- },
- permissions: {
- alert: true,
- badge: true,
- sound: true,
- },
- popInitialNotification: true,
- requestPermissions: true,
- });
- var channelId = "your-channel-id" + new Date().getTime()
- PushNotification.createChannel({
- channelId: channelId, // (required)
- channelName: "My channel", // (required)
- channelDescription: "A channel to categorise your notifications", // (optional) default: undefined.
- playSound: false, // (optional) default: true
- soundName: "default", // (optional) See `soundName` parameter of `localNotification` function
- importance: Importance.HIGH, // (optional) default: Importance.HIGH. Int value of the Android notification importance
- vibrate: true, // (optional) default: true. Creates the default vibration pattern if true.
- }, (created) => {
- console.log('create channel result',created)
- PushNotification.localNotificationSchedule({
- //... You can use all the options from localNotifications
- channelId: channelId,
- title: 'Leon test',
- message: "Local notification push", // (required)
- date: new Date(Date.now() + 10 * 1000), // in 60 secs
- allowWhileIdle: true, // (optional) set notification to work while on doze, default: false
- // repeatType:'minute',
- /* Android Only Properties */
- // repeatTime: 1, // (optional) Increment of configured repeatType. Check 'Repeating Notifications' section for more info.
- });
- })
- PushNotification.localNotificationSchedule({
- //... You can use all the options from localNotifications
- title: 'Leon test2',
- message: "Local notification push2", // (required)
- date: new Date(Date.now() + 15 * 1000), // in 60 secs
- allowWhileIdle: true, // (optional) set notification to work while on doze, default: false
- // repeatType:'minute',
- /* Android Only Properties */
- // repeatTime: 1, // (optional) Increment of configured repeatType. Check 'Repeating Notifications' section for more info.
- });
- // PushNotification.localNotificationSchedule({
- // //... You can use all the options from localNotifications
- // channelId: "your-channel-id"+new Date().getTime(),
- // title: 'Leon test',
- // message: "Local notification push", // (required)
- // date: new Date(Date.now() + 10 * 1000), // in 60 secs
- // allowWhileIdle: true, // (optional) set notification to work while on doze, default: false
- // // repeatType:'minute',
- // /* Android Only Properties */
- // // repeatTime: 1, // (optional) Increment of configured repeatType. Check 'Repeating Notifications' section for more info.
- // });
- // PushNotification.localNotificationSchedule({
- // title: "My notification title",
- // message: "My notification message",
- // date: new Date(Date.now() + 10 * 1000), // first trigger in 30 secs
- // // channelId: 'DemoAppID',
- // repeatType: 'time',
- // repeatTime: 30 * 1000 // repeats every 30 seconds (value has to be defined in miliseconds when the repeatType is 'time')
- // });
- }
- if (process.env.TARO_ENV == 'rn') {
- JPush.setBadge({
- badge: 0,
- appBadge: 0
- })
- JPush.isNotificationEnabled((res) => {
- if (res) {
- const test = require('@/utils/push').default
- test()
- }
- })
- AppState.addEventListener('change', handleAppStateChange);
- /*
- if (Taro.getSystemInfoSync().platform == 'ios') {
- setTimeout(() => {
- var Jto = require('react-native').NativeModules.NativeBridge;
- // Jto.authNotification()
- Jto.getNotificationAuthStatus()
- }, 5000)
- NativeAppEventEmitter.addListener('notificationResult', (data) => {
- console.log(data)
- showAlert({
- title:'notification status',
- content:data
- })
- })
- }*/
- }
- }, [])
- useEffect(() => {
- console.log(user.isLogin)
- getCheckData()
- // global.pauseIndexTimer = !user.isLogin
- if (user.isLogin) {
- uploadUserClient();
- checkAuthorized();
- //检查用户是否添加过小程序
- checkAddToMini();
- wxPubFollow({ force_refresh: true }).then(res => {
- dispatch(setWXFollow((res as any).wx_pub_followed));
- })
- if (process.env.TARO_ENV == 'rn') {
- if (Taro.getSystemInfoSync().platform == 'ios') {
- var Jto = require('react-native').NativeModules.NativeBridge;
- Jto.getNotificationAuthStatus()
- NativeAppEventEmitter.addListener('notificationResult', (data) => {
- global.notification = data;
- uploadPermissions()
- })
- }
- // uploadPermissions()
- JPush.isNotificationEnabled((res) => {
- if (res) {
- const test = require('@/utils/push').default
- test()
- }
- })
- checkVersionUpdate()
- }
- }
- else {
- dispatch(clearNightStore());
- }
- }, [user.isLogin])
- useReady(async () => {
- const userData = await getStorage('userData');
- if (userData) {
- dispatch(getInfoSuccess(JSON.parse(userData as string)) as any);
- getHistory()
- }
- })
- async function checkVersionUpdate() {
- if (!user.isLogin) {
- return
- }
- if (process.env.TARO_ENV == 'rn') {
- systemVersion().then(res => {
- if ((res as any).result == 'UPDATE' && !showUpdate) {
- showUpdate = true
- showAlert({
- title: (res as any).title,
- content: (res as any).description,
- showCancel: true,
- confirmText: '更新',
- confirm: () => {
- Linking.openURL((res as any).download_url)
- }
- })
- }
- else if ((res as any).result == 'FORCE_UPDATE') {
- showAlert({
- title: (res as any).title,
- content: (res as any).description,
- showCancel: false,
- confirmText: '更新',
- confirm: () => {
- Linking.openURL((res as any).download_url)
- }
- })
- }
- })
- return;
- }
- const showAlert1 = await getStorage('120alert') || false;
- if (!showAlert1) {
- showAlert({
- title: '版本更新提示',
- content: '「连续纪录」新增归零倒计时提示⏳\n别让连续记录终止, 将它们一直保持下去!',
- showCancel: false,
- confirmText: '我知道了'
- })
- }
- Taro.setStorage({ key: '120alert', data: true })
- }
- function checkAddToMini() {
- if (process.env.TARO_ENV == 'weapp') {
- const version = Taro.getAppBaseInfo().SDKVersion
- if (compareVersion(version, '2.30.3') >= 0) {
- wx.checkIsAddedToMyMiniProgram({
- success: (res) => {
- if (!res.added) {
- setNeedShowAddTip(true)
- }
- },
- fail: (e) => {
- }
- });
- }
- }
- }
- useDidShow(() => {
- checkTimeZone()
- setCount(pre => pre + 1)
- //resume timer
- pauseTimer = false
- if (user.isLogin) {
- if (global.refreshRecent) {
- global.refreshRecent()
- }
- }
- setTimeout(() => {
- checkVersionUpdate();
- updateNotificationStatus();
- }, 1000)
- })
- usePageScroll((e) => {
- if (e.scrollTop > 70) {
- setShowTip(true)
- }
- else {
- setShowTip(false)
- }
- })
- useDidHide(() => {
- //pause timer
- pauseTimer = true
- })
- global.refreshIndex = () => {
- setCount((prevCounter) => prevCounter + 1)
- }
- const handleAppStateChange = (nextAppState) => {
- console.log(nextAppState)
- if (nextAppState != 'active') {
- return
- }
- checkTimeZone()
- updateNotificationStatus()
- };
- function updateNotificationStatus() {
- if (process.env.TARO_ENV == 'rn') {
- if (user.isLogin) {
- if (Taro.getSystemInfoSync().platform == 'ios') {
- var Jto = require('react-native').NativeModules.NativeBridge;
- Jto.getNotificationAuthStatus()
- }
- }
- JPush.setBadge({
- badge: 0,
- appBadge: 0
- })
- }
- }
- function checkTimeZone() {
- setCount((prevCounter) => prevCounter + 1)
- var timeZoneFormatted = getTimezone()
- Taro.getStorage({
- key: 'last_tz',
- success: function (res) {
- if (res.data && res.data != timeZoneFormatted) {
- if (global.refrehWeekly) {
- global.refrehWeekly()
- }
- // if (global.refreshNight){
- // global.refreshNight()
- // }
- // if (global.refreshDay){
- // global.refreshDay()
- // }
- if (global.currentStatus != 'WAIT_FOR_START') {
- showAlert({
- title: t('feature.track_time_duration.change_tz_alert.title'),
- content: t('feature.track_time_duration.change_tz_alert.content', { tz: timeZoneFormatted }),
- showCancel: false,
- confirmText: t('feature.track_time_duration.change_tz_alert.confirm'),
- })
- }
- }
- },
- complete: function () {
- Taro.setStorage({ key: 'last_tz', data: timeZoneFormatted })
- }
- })
- }
- function uploadUserClient() {
- var systemInfo = Taro.getSystemInfoSync();
- console.log(systemInfo)
- var language: any = systemInfo.language
- if (process.env.TARO_ENV == 'rn') {
- var NativeModules = require('react-native').NativeModules;
- if (Taro.getSystemInfoSync().platform == 'ios') {
- // language = NativeModules.SettingsManager.settings.AppleLocale
- // languageList = NativeModules.SettingsManager.settings.AppleLanguages
- language = {
- AppleLocale: NativeModules.SettingsManager.settings.AppleLocale,
- AppleLanguages: NativeModules.SettingsManager.settings.AppleLanguages,
- NSLanguages: NativeModules.SettingsManager.settings.NSLanguages
- }
- }
- else {
- language = NativeModules.I18nManager.localeIdentifier
- }
- // iOS:
- // var locale = NativeModules.SettingsManager.settings.AppleLocale ||
- // NativeModules.SettingsManager.settings.AppleLanguages[0] // "fr_FR"
- // showAlert({
- // title: 'locale',
- // content: JSON.stringify(NativeModules.SettingsManager.settings)
- // })
- // Android:
- // locale = NativeModules.I18nManager.localeIdentifier // "fr_FR"
- }
- var timeZoneFormatted = getTimezone()
- var timeZoneId = ''
- var timeZoneName = ''
- if (Taro.getSystemInfoSync().platform == 'ios') {
- timeZoneId = getTimezoneId()
- timeZoneName = getTimezoneName()
- }
- clientInfo({
- client: {
- client_type: process.env.TARO_ENV == 'weapp' ? 'MP' : 'APP',
- client_version: process.env.TARO_ENV == 'weapp' ? WX_VERSION : APP_VERSION,//Taro.getAccountInfoSync().miniProgram.version : '1.0',//'1.0'
- wx_version: process.env.TARO_ENV == 'weapp' ? systemInfo.version : '_'
- },
- meta: {
- language: language,
- timezone: {
- gmt: timeZoneFormatted,
- id: timeZoneId,
- name: timeZoneName
- },
- },
- device: {
- brand: systemInfo.brand,
- model: systemInfo.model,
- platform: systemInfo.platform,
- system: systemInfo.system
- },
- perm: {
- wifi_enabled: systemInfo.wifiEnabled,
- location_authorized: systemInfo.locationAuthorized,
- location_enabled: systemInfo.locationEnabled
- }
- })
- }
- function loadWXCache() {
- var showDayRing = Taro.getStorageSync('showDayRing') || false;
- var showNightRing = Taro.getStorageSync('showNightRing') || false;
- dispatch(showDay(showDayRing))
- dispatch(showNight(showNightRing))
- var gps = Taro.getStorageSync('gps')
- if (gps) {
- global.locationDetail = JSON.parse(gps)
- }
- var userData = Taro.getStorageSync('userData')
- if (userData) {
- dispatch(getInfoSuccess(JSON.parse(userData)));
- }
- }
- async function loadRNCache() {
- var showDayRing = await getStorage('showDayRing') || false;
- var showNightRing = await getStorage('showNightRing') || false;
- dispatch(showDay(showDayRing))
- dispatch(showNight(showNightRing))
- var gps = await getStorage('gps')
- if (gps) {
- global.locationDetail = JSON.parse(gps)
- }
- var userData = await getStorage('userData')
- console.log(userData)
- if (userData) {
- dispatch(getInfoSuccess(JSON.parse(userData)));
- }
- // //测试直接登录
- // else {
- // userData = '{"metrics_times":0,"ongoing":false,"id":"fe6641e66a0e411937a52511e19851cd","mobile_bind":false,"mobile":"","avatar":"https://api.fast.dev.liveplus.fun/api/avatars/fast_441b5a21.svg","nickname":"fast_441b5a21","type":"GENERAL","lv":1,"invite_code":"LVQ5","input_invite_code":true,"reg_time":1712838856000,"login_bind":{"wx":false,"wx_mp":false,"wx_pub":false,"qq":false,"weibo":false},"test_user":true,"manager_user":false,"web_user":false,"rjv_balance":0,"day_level":1,"scenario_select_count":77,"push_enabled":false,"is_new_user":true,"lang":"en","timezone":{},"token":"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJhdWQiOiJhY2NvdW50Iiwic3ViIjoiZmU2NjQxZTY2YTBlNDExOTM3YTUyNTExZTE5ODUxY2QiLCJpc3MiOiJmYXN0Iiwibmlja25hbWUiOiJmYXN0XzQ0MWI1YTIxIiwidHlwIjoiQmVhcmVyIiwic2Vzc2lvbl9zdGF0ZSI6IjA0NTcxOGYzN2Y5NTYzYjcxMTNkMWZhODI5NmE2MjQ2IiwiZXhwIjoxNzQ2Njg4NTYxLCJpYXQiOjE3MTUxNTI1NjF9.x1CguOILCTjT8lKcEdSEeuS9ACc5QK2G4Rxmcz9OMLQ","need_improve":false}'
- // dispatch(getInfoSuccess(JSON.parse(userData)));
- // }
- }
- function getCheckData() {
- Promise.all([getClocks(), getPlans()]).then((list) => {
- setErrorPage(false)
- setCheckData(list)
- if (needScroll) {
- needScroll = false
- if (process.env.TARO_ENV == 'weapp') {
- setTimeout(() => {
- Taro.createSelectorQuery().select('#latest').boundingClientRect((rect) => {
- Taro.pageScrollTo({
- scrollTop: (rect as any).top,
- duration: 150
- })
- }).exec()
- }, 100)
- }
- else {
- // debugger
- // (scrollRef.current as any).scrollTo({ y: rpxToPx(400), animated: true })
- }
- }
- setLoaded(true)
- }).catch((e) => {
- setErrorPage(true)
- var list = JSON.parse(defaultValue)
- setCheckData(list)
- needScroll = false
- setLoaded(true)
- })
- getHistory()
- }
- function setCheckData(list: any) {
- setHomeData(list[0])
- global.homeData = list[0]
- global.currentStatus = list[0].current_record.status;
- var array = list[1].scenarios
- var schedule: any = null
- array.map(item => {
- if (item.name == 'FAST_SLEEP') {
- schedule = item.schedule;
- schedule.sleep.prev_input = item.prev_input;
- schedule.sleep.valid = item.valid;
- }
- })
- if (user.isLogin) {
- dispatch(updateScenario(list[0].current_record))
- dispatch(setConfigs(list[0].time_input_schema));
- dispatch(setScenario(list[0].scenario));
- global.scenario = list[0].scenario.name;
- }
- dispatch(setCurrentRecord(list[0].current_record))
- dispatch(setSchedule(schedule))
- // setLoaded(true)
- }
- function getHistory() {
- if (user.isLogin)
- getClockRecords({
- page: 1,
- limit: 1,
- // part_completed: true
- completed: true
- }).then(res => {
- setRecords((res as any).data)
- })
- }
- global.indexPageRefresh = () => {
- getCheckData()
- if (global.swiperDayNightRefresh) {
- global.swiperDayNightRefresh()
- }
- }
- global.showIndexModal = (isShow: boolean, detail: any, debugNode?: any) => {
- global.showModal = isShow
- setDebugInfo(debugNode)
- setShowModal(isShow)
- setModalDetail(detail)
- }
- global.showIndexModal2 = (isShow: boolean, detail: any) => {
- setDebugInfo(null)
- global.showModal = isShow
- setShowModal2(isShow)
- setModalDetail2(detail)
- }
- global.changeTargetDuration = (duration: number, isFast: boolean) => {
- var obj = JSON.parse(JSON.stringify(homeData))
- var record = obj.current_record
- if (isFast) {
- record.fast.target_end_time = record.fast.target_start_time + duration * 60 * 1000
- }
- else {
- record.sleep.target_end_time = record.sleep.target_start_time + duration * 60 * 1000
- }
- setHomeData(obj)
- }
- global.updateFastSleepData = (data: any, schedule?: any) => {
- if (data.id == (homeData as any).current_record.id) {
- var obj = JSON.parse(JSON.stringify(homeData))
- obj.current_record = data
- if (schedule) {
- obj.scenario.schedule = schedule
- }
- setHomeData(obj)
- }
- switch (data.scenario) {
- case 'FAST':
- if (data.status == 'WAIT_FOR_START') {
- dispatch(changeFastDuration(data.fast.target_end_time - data.fast.target_start_time))
- }
- break;
- case 'SLEEP':
- if (data.status == 'WAIT_FOR_START') {
- dispatch(changeSleepDuration(data.sleep.target_end_time - data.sleep.target_start_time))
- }
- break;
- case 'FAST_SLEEP':
- if (data.status == 'WAIT_FOR_START') {
- dispatch(changeFastDuration(data.fast.target_end_time - data.fast.target_start_time))
- }
- else if (data.status == 'ONGOING1') {
- dispatch(changeSleepDuration(data.sleep.target_end_time - data.sleep.target_start_time))
- }
- break;
- }
- }
- global.popScheduleAlert = (scenario, startTime) => {
- if (process.env.TARO_ENV == 'weapp') {
- if (permission.wxPubFollow) {
- showAlert({
- title: t('feature.track_time_duration.reminders.schedule_title'),
- content: scenario.name == 'FAST' ?
- t('feature.track_time_duration.reminders.enable_schedule_fast_content', { time: startTime }) :
- t('feature.track_time_duration.reminders.enable_schedule_sleep_content', { time: startTime }),
- showCancel: false,
- confirmText: t('feature.track_time_duration.reminders.ok')
- })
- }
- else {
- showAlert({
- title: t('feature.track_time_duration.reminders.schedule_title'),
- content: scenario.name == 'FAST' ?
- t('feature.track_time_duration.reminders.schedule_fast_content', { time: startTime }) :
- t('feature.track_time_duration.reminders.schedule_sleep_content', { time: startTime }),
- cancelText: t('feature.track_time_duration.reminders.later'),
- confirmText: t('feature.track_time_duration.reminders.open'),
- showCancel: true,
- confirm: () => {
- followWxPub()
- }
- })
- }
- }
- else {
- JPush.isNotificationEnabled((res) => {
- if (res) {
- showAlert({
- title: t('feature.track_time_duration.reminders.schedule_title'),
- content: scenario.name == 'FAST' ?
- t('feature.track_time_duration.reminders.enable_schedule_fast_content', { time: startTime }) :
- t('feature.track_time_duration.reminders.enable_schedule_sleep_content', { time: startTime }),
- showCancel: false,
- confirmText: t('feature.track_time_duration.reminders.ok')
- })
- }
- else {
- showAlert({
- title: t('feature.track_time_duration.reminders.schedule_title'),
- content: scenario.name == 'FAST' ?
- t('feature.track_time_duration.reminders.schedule_fast_content', { time: startTime }) :
- t('feature.track_time_duration.reminders.schedule_sleep_content', { time: startTime }),
- cancelText: t('feature.track_time_duration.reminders.later'),
- confirmText: t('feature.track_time_duration.reminders.open'),
- showCancel: true,
- confirm: () => {
- checkNotification()
- // Linking.openURL('app-settings:notifications')
- }
- })
- }
- })
- }
- }
- global.popMixScheduleAlert = (time1, time2) => {
- if (process.env.TARO_ENV == 'weapp') {
- if (permission.wxPubFollow) {
- showAlert({
- title: t('feature.track_time_duration.reminders.schedule_title'),
- content: t('feature.track_time_duration.reminders.enable_schedule_mix_content', { time1: time1, time2: time2 }),
- showCancel: false,
- confirmText: t('feature.track_time_duration.reminders.ok')
- })
- }
- else {
- showAlert({
- title: t('feature.track_time_duration.reminders.schedule_title'),
- content:
- t('feature.track_time_duration.reminders.schedule_mix_content'),
- cancelText: t('feature.track_time_duration.reminders.later'),
- confirmText: t('feature.track_time_duration.reminders.open'),
- showCancel: true,
- confirm: () => {
- followWxPub()
- }
- })
- }
- }
- else {
- JPush.isNotificationEnabled((res) => {
- if (res) {
- showAlert({
- title: t('feature.track_time_duration.reminders.schedule_title'),
- content: t('feature.track_time_duration.reminders.enable_schedule_mix_content', { time1: time1, time2: time2 }),
- showCancel: false,
- confirmText: t('feature.track_time_duration.reminders.ok')
- })
- }
- else {
- showAlert({
- title: t('feature.track_time_duration.reminders.schedule_title'),
- content:
- t('feature.track_time_duration.reminders.schedule_mix_content'),
- cancelText: t('feature.track_time_duration.reminders.later'),
- confirmText: t('feature.track_time_duration.reminders.open'),
- showCancel: true,
- confirm: () => {
- checkNotification()
- // Linking.openURL('app-settings:notifications')
- }
- })
- }
- })
- }
- }
- function followWxPub() {
- const resource = common.resources.filter((item: any) => {
- return item.code == 'follow_wx_pub'
- })
- jumpPage('/pages/common/H5?title=fast16cc 关注服务号&url=' + resource[0].url)
- }
- function modalContent() {
- if (showModal || showModal2) {
- return <Modal
- testInfo={debugInfo}
- dismiss={() => {
- setDebugInfo(null)
- setShowModal(false);
- setShowModal2(false);
- global.pauseIndexTimer = false
- }}
- confirm={() => { }}>
- {
- showModal ? modalDetail : modalDetail2
- }
- </Modal>
- }
- return <View />
- }
- async function getStorage(key: string) {
- try {
- const res = await Taro.getStorage({ key });
- return res.data;
- } catch {
- return '';
- }
- }
- function more() {
- jumpPage('/pages/common/RecordsHistory?type=time&title=time', 'RecordsHistory', navigation, {
- type: 'time',
- title: 'time'
- })
- }
- function tapLogin() {
- if (!user.isLogin) {
- jumpPage('/pages/account/ChooseAuth', 'ChooseAuth', navigation)
- }
- }
- function headerView() {
- return <ClockHeader homeData={homeData} />
- }
- global.scrollToLatest = () => {
- needScroll = true;
- }
- var timestamp = new Date().getTime()
- function render() {
- if (!loaded) {
- return <Layout type={TemplateType.customHeader} header={headerView()} title={t('page.clock.title')} titleShowStyle={NaviBarTitleShowType.scrollToShow}>
- <View style={{ width: rpxToPx(750), height: rpxToPx(900), display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center' }}>
- <AtActivityIndicator size={40} color="#fff" />
- {
- process.env.TARO_ENV == 'weapp' && <Tabbar index={0} />
- }
- </View>
- </Layout>
- }
- return <Layout type={TemplateType.customHeader} header={headerView()} title={t('page.clock.title')} titleShowStyle={NaviBarTitleShowType.scrollToShow}>
- <View className="index_container">
- {
- needShowAddTip && showTip && <Tooltip title="添加到我的小程序" closeTip={() => { setNeedShowAddTip(false) }} />
- }
- <Text className="count">{count}</Text>
- <Box>
- <View>
- <IndexItem type="FAST_SLEEP" data={homeData} time={timestamp} showStage={false} />
- {
- user.isLogin ? <IndexConsole record={homeData} count={count} /> : <StageSelector />
- }
- </View>
- </Box>
- {
- process.env.TARO_ENV == 'weapp' && <DayNightCard isNight={true} count={count} />
- }
- {
- process.env.TARO_ENV == 'rn' && <DayNightSwiper count={count} />
- }
- {
- process.env.TARO_ENV == 'rn' && <View style={{ height: rpxToPx(20) }} />
- }
- {user.isLogin && <AllRings data={homeData} time={timestamp} />}
- {
- user.isLogin && records.length > 0 && <View style={{ display: 'flex', flexDirection: 'row', justifyContent: 'space-between', marginTop: rpxToPx(40), }}>
- {
- <Text className="discovery1" style={{ marginBottom: 0 }}>{t('feature.track_time_duration.record_fast_sleep.header.latest_record')}</Text>
- }
- {
- 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>
- }
- {
- process.env.TARO_ENV == 'rn' && <View onClick={more}>
- <GradientText style={{ fontSize: rpxToPx(32), fontWeight: 'bold', marginRight: rpxToPx(46) }}>{t('feature.track_time_duration.record_fast_sleep.header.btn_show_all')}</GradientText>
- </View>
- }
- </View>
- }
- {
- user.isLogin && records.length > 0 && <View id="latest" className="fast_sleep_item_bg">
- <RecordFastSleep data={records[0]} type='record' index={-20000} />
- </View>
- }
- {
- loaded && !user.isLogin && <View style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', marginTop: rpxToPx(36) }}>
- <ChooseScenarioBtn title={t('feature.auth.login.login_now')} background={ColorType.fast} onClick={tapLogin} />
- </View>
- }
- {
- user.isLogin && !showErrorPage && <View style={{ marginTop: rpxToPx(60), display: 'flex', flexDirection: 'column' }}>
- <Text className="discovery1" >{t('feature.track_time_duration.weekly.title')}</Text>
- <WeekCalendar />
- </View>
- }
- {
- user.isLogin && <Streaks count={count} />
- }
- {
- user.isLogin && user.test_user && homeData && (homeData as any).access && <View style={{ display: 'flex', flexDirection: 'column' }}>
- <Text style={{ color: '#fff', fontSize: 15 }}>current status:{(homeData as any).access.current.qualification.status}</Text>
- <Text style={{ color: '#fff', fontSize: 15 }}>previous status:{(homeData as any).access.previous.qualification.status}</Text>
- </View>
- }
- {
- process.env.TARO_ENV == 'weapp' && <View style={{ height: 100 }} />
- }
- {
- modalContent()
- }
- {
- homeData && <SegmentPop data={homeData} />
- }
- {
- homeData && <DurationPicker record={(homeData as any).current_record} />
- }
- <Tabbar index={0} />
- </View>
- </Layout>
- }
- // if (process.env.TARO_ENV == 'rn') {
- // return <ScrollView>
- // {
- // render()
- // }
- // </ScrollView>
- // }
- return render()
- }
|