| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538 |
- 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 './Index.scss'
- import { useDispatch, useSelector } from "react-redux";
- import { useDidHide, useDidShow, 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, 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 { 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/trackTimeDuration/components/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 } 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";
- let GradientText
- let useNavigation;
- let timer
- let pauseTimer = false;
- let AppState;
- if (process.env.TARO_ENV == 'rn') {
- AppState = require("react-native").AppState
- GradientText = require('@/components/basic/GradientText').default
- useNavigation = require("@react-navigation/native").useNavigation
- }
- 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"}}]`
- 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 [records, setRecords] = useState([])
- const nightStore = useSelector((state: any) => state.night);
- useEffect(() => {
- timer = setInterval(() => {
- if (global.pauseIndexTimer || pauseTimer) {
- return
- }
- setCount((prevCounter) => prevCounter + 1)
- }, 1000)
- }, [])
- useEffect(() => {
- if (process.env.TARO_ENV == 'weapp') {
- loadWXCache()
- }
- else {
- loadRNCache()
- }
- if (process.env.TARO_ENV == 'rn') {
- AppState.addEventListener('change', handleAppStateChange);
- }
- }, [])
- useEffect(() => {
- getCheckData()
- global.pauseIndexTimer = !user.isLogin
- if (user.isLogin) {
- uploadUserClient();
- checkAuthorized();
- }
- else {
- dispatch(clearNightStore());
- }
- }, [user.isLogin, time.status])
- useReady(async () => {
- const userData = await getStorage('userData');
- if (userData) {
- dispatch(getInfoSuccess(JSON.parse(userData as string)) as any);
- getHistory()
- }
- // if (process.env.TARO_ENV == 'weapp') {
- // useShareAppMessage((e) => {
- // return {
- // title: t('feature.track_time_duration.common.share_title'),
- // path: 'pages/clock/Clock'
- // }
- // })
- // }
- })
- useDidShow(() => {
- checkTimeZone()
- setCount(pre => pre + 1)
- //resume timer
- pauseTimer = false
- if (user.isLogin){
- getInfo().then(res => {
- dispatch(getInfoSuccess(res))
- }).catch(e => {
- Taro.stopPullDownRefresh()
- })
- }
- })
- useDidHide(() => {
- //pause timer
- pauseTimer = true
- })
- global.refreshIndex = () => {
- setCount((prevCounter) => prevCounter + 1)
- }
- const handleAppStateChange = (nextAppState) => {
- checkTimeZone()
- };
- function checkTimeZone() {
- var split = new Date().toString().split(' ');
- var timeZoneFormatted = split[split.length - 2];
- Taro.getStorage({
- key: 'last_tz',
- success: function (res) {
- if (res.data && res.data != timeZoneFormatted) {
- if (global.currentStatus != 'WAIT_FOR_START') {
- Taro.showModal({
- 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();
- var split = new Date().toString().split(' ');
- var timeZoneFormatted = split[split.length - 2];
- clientInfo({
- client: {
- client_type: process.env.TARO_ENV == 'weapp' ? 'MP' : 'APP',
- client_version: process.env.TARO_ENV == 'weapp' ? Taro.getAccountInfoSync().miniProgram.version : '1.0',//'1.0'
- wx_version:process.env.TARO_ENV == 'weapp' ?systemInfo.version:'_'
- },
- meta: {
- language: systemInfo.language,
- time_zone: {
- id: Intl.DateTimeFormat().resolvedOptions().timeZone,
- name: timeZoneFormatted
- },
- },
- 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)));
- }
- // getCheckData()
- }
- 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')
- if (userData) {
- dispatch(getInfoSuccess(JSON.parse(userData)));
- }
- // getCheckData()
- }
- function getCheckData() {
- Promise.all([getClocks(), getPlans()]).then((list) => {
- setErrorPage(false)
- setCheckData(list)
- }).catch((e) => {
- setErrorPage(true)
- var list = JSON.parse(defaultValue)
- setCheckData(list)
- })
- 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 = null
- array.map(item => {
- if (item.name == 'FAST_SLEEP') {
- schedule = item.schedule;
- }
- })
- 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()
- }
- 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) => {
- if (data.id == (homeData as any).current_record.id) {
- var obj = JSON.parse(JSON.stringify(homeData))
- obj.current_record = data
- 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') {
- debugger
- dispatch(changeSleepDuration(data.sleep.target_end_time - data.sleep.target_start_time))
- }
- break;
- }
- }
- function modalContent() {
- if (showModal || showModal2) {
- if (process.env.TARO_ENV == 'weapp') {
- return <Modal
- testInfo={debugInfo}
- dismiss={() => {
- setDebugInfo(null)
- setShowModal(false);
- setShowModal2(false);
- global.pauseIndexTimer = false
- }}
- confirm={() => { }}>
- {
- showModal ? modalDetail : modalDetail2
- }
- </Modal>
- }
- else if (process.env.TARO_ENV == 'rn') {
- return <PageContainer style={{ backgroundColor: '#1c1c1c' }}
- // overlayStyle='background-color:rgba(0,0,0,0.9)'
- // custom-style='background-color:#1c1c1c'
- overlayStyle={{ backgroundColor: 'rgba(0,0,0,0.9)' }}
- customStyle={{ backgroundColor: '#1c1c1c' }}
- closeOnSlideDown={false}
- onBeforeEnter={() => {
- Taro.hideTabBar();
- }}
- onBeforeLeave={() => {
- Taro.showTabBar();
- }}
- onClick={() => { alert('b') }}
- onClickOverlay={() => { alert('a') }}
- onAfterLeave={() => { setShowModal(false); setShowModal2(false); global.pauseIndexTimer = false }}
- show={showModal || showModal2} round={true} overlay={true} position='bottom'
- >
- {
- showModal ? modalDetail : modalDetail2
- }
- </PageContainer>
- }
- }
- 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')
- return
- }
- }
- function headerView() {
- return <ClockHeader homeData={homeData} />
- }
- var timestamp = new Date().getTime()
- function render() {
- if (!loaded) {
- return <View style={{ width: rpxToPx(750), height: rpxToPx(900), display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
- <AtActivityIndicator size={40} color="#fff"/>
- <Tabbar index={0} />
- </View>
- }
- return <Layout type={TemplateType.customHeader} header={headerView()} title={t('page.clock.title')} titleShowStyle={NaviBarTitleShowType.scrollToShow}>
- <View className="index_container">
- <Text className="count">{count}</Text>
- <Box>
- <View>
- <IndexItem type="FAST_SLEEP" data={homeData} time={timestamp} showStage={false} />
- {
- user.isLogin ? <IndexConsole record={homeData} /> : <StageSelector />
- }
- </View>
- </Box>
- <DayNightCard isNight={true} count={count} />
- {
- 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' && <GradientText onClick={more} style={{ fontSize: rpxToPx(32), fontWeight: 'bold' }}>{t('feature.track_time_duration.record_fast_sleep.header.btn_show_all')}</GradientText>
- }
- </View>
- }
- {
- user.isLogin && records.length > 0 && <View 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>
- }
- {
- showErrorPage && <NoData refresh={() => { getCheckData() }} />
- }
- {
- user.isLogin && !showErrorPage && <View style={{ marginTop: rpxToPx(60), display: 'flex', flexDirection: 'column' }}>
- <Text className="discovery1" >周统计</Text>
- <WeekCalendar />
- </View>
- }
- <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()
- }
|