| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468 |
- import { Component, PropsWithChildren, useEffect, useRef, useState } from 'react'
- import { View, Text, Button, Input, Picker, Swiper, SwiperItem, Icon } from '@tarojs/components'
- import '../index/index.scss'
- import './Clock.scss'
- // import './context/locales/index'
- import '@/context/locales/index'
- import Taro, { useDidShow, usePageScroll, useReady, useRouter, useShareAppMessage } from '@tarojs/taro'
- // import ComponentA from './component'
- import { useDispatch, useSelector } from 'react-redux';
- import { getInfoSuccess, logoutSuccess } from '@/store/user';
- import { wxPubFollow } from '@/services/permission';
- import { gobalConfigs, staticResources, uploadSessionKey } from '@/services/common';
- import Clocks from '@/features/trackTimeDuration/components/Clock';
- import Console from '@/features/trackTimeDuration/components/Console';
- import Schedule from '@/features/trackTimeDuration/components/Schedule';
- import { getChecks, getClocks } from '@/services/trackTimeDuration';
- import { setScenario } from '@/store/scenario';
- import { setSpecifiedStatus, setSpecifiedState, machine } from '@/store/trackTimeMachine';
- import trackTimeService from '@/store/trackTimeMachine';
- import { setWXFollow } from '@/store/permission';
- import Tooltip from '@/components/view/Tooltip'
- import RequestType, { thirdPartRequest } from '@/services/thirdPartRequest'
- import { setConfigs } from '@/store/common'
- import RecordFastSleep from '@/features/trackTimeDuration/components/RecordFastSleep'
- import Box from '@/components/layout/Box'
- import Layout from '@/components/layout/layout'
- import { CheckBoxType, NaviBarTitleShowType, TemplateType } from '@/utils/types'
- import { updateScenario } from '@/store/time'
- import { showModal } from '@/store/modal'
- import { ConsoleType, changeConsoleStatus } from '@/store/console'
- import TitleView from '@/features/trackTimeDuration/components/TitleView'
- import StatusIndicator from '@/features/trackTimeDuration/components/StatusIndicator'
- import { useTranslation } from 'react-i18next'
- import TableCellHeader from '@/components/layout/TableCellHeader'
- import SectionHeader from '@/components/layout/SectionHeader'
- import Header from '@/components/layout/Header'
- import { TimeFormatter } from '@/utils/time_format'
- import NoData from '@/components/view/NoData'
- import { ColorType } from '@/context/themes/color'
- import { jumpPage } from '@/features/trackTimeDuration/hooks/Common'
- // import TabBar from '../../components/Tabbar';
- // import Rings from '@components/view/Rings';
- let useNavigation;
- if (process.env.TARO_ENV == 'rn') {
- useNavigation = require("@react-navigation/native").useNavigation
- }
- export default function IndexPage() {
- const dispatch = useDispatch();
- const { t } = useTranslation()
- const [checkData, setCheckData] = useState(null)
- const user = useSelector((state: any) => state.user);
- const time = useSelector((state: any) => state.time);
- const common = useSelector((state: any) => state.common);
- const consoleData = useSelector((state: any) => state.console);
- const [counter, setCounter] = useState(0)
- const [timerId, setTimerId] = useState(null)
- const [needShowAddTip, setNeedShowAddTip] = useState(false)
- const [showErrorPage, setErrorPage] = useState(false)
- const [swiperIndex, setSwiperIndex] = useState(0)
- const [autoPlay, setAutoPlay] = useState(false)
- const [showModal, setShowModal] = useState(false)
- const [modalDetail, setModalDetail] = useState<any>({})
- const [showModal2, setShowModal2] = useState(false)
- const [modalDetail2, setModalDetail2] = useState<any>({})
- const [showSingleFastEnd, setShowSingleFastEnd] = useState(false)
- const [consoleStatus, setConsoleStatus] = useState(consoleData.status)
- let navigation;
- if (useNavigation) {
- navigation = useNavigation()
- }
- global.dispatch = dispatch;
- global.checkData = () => {
- console.log('refresh clock data')
- getCheckData()
- }
- useEffect(() => {
- global.consoleType = 'idle'
- dispatch(staticResources() as any);
- // dispatch(gobalConfigs() as any);
- trackTimeService.onTransition(state => {
- if ((state.value as any).FAST_SLEEP == 'COMPLETED' ||
- (state.value as any).FAST == 'ONGOING' ||
- (state.value as any).SLEEP == 'ONGOING' ||
- (state.value as any).FAST_SLEEP == 'ONGOING1' ||
- (state.value as any).FAST_SLEEP == 'ONGOING2' ||
- (state.value as any).FAST_SLEEP == 'ONGOING3' ||
- (state.value as any).FAST == 'COMPLETED' ||
- (state.value as any).SLEEP == 'COMPLETED') {
- getCheckData()
- }
- })
- }, [])
- useEffect(() => {
- setConsoleStatus(consoleData.status)
- switch (consoleData.status) {
- // case ConsoleType.going:
- // setShowSingleFastEnd(true)
- // setTimeout(() => {
- // setShowSingleFastEnd(false)
- // setSwiperIndex(1)
- // setAutoPlay(true)
- // dispatch(changeConsoleStatus({ status: ConsoleType.end }))
- // }, 2000)
- // break
- case ConsoleType.end:
- setTimeout(() => {
- dispatch(changeConsoleStatus({ status: ConsoleType.idle }))
- }, 2000)
- break
- }
- }, [consoleData.status])
- useEffect(() => {
- if (user.isLogin) {
- //检查用户是否添加过小程序
- checkAddToMini();
- //检查session是否过期
- checkSession()
- getCheckData()
- }
- }, [user.isLogin])
- function checkSession() {
- if (process.env.TARO_ENV === 'weapp') {
- thirdPartRequest(RequestType.RequestTypeCheckSession).then(res => {
- }).catch(err => {
- console.log('session_key 已经失效,需要更新登录code')
- thirdPartRequest(RequestType.RequestTypeWXLogin).then(result => {
- uploadSessionKey({ type: 'WX_MP', code: (result as any).code });
- })
- })
- }
- }
- function checkAddToMini() {
- process.env.TARO_ENV == 'weapp' &&
- wx.checkIsAddedToMyMiniProgram({
- success: (res) => {
- if (!res.added) {
- setNeedShowAddTip(true)
- }
- },
- fail: (e) => {
- }
- });
- }
- useEffect(() => {
- startTimer();
- return () => {
- // 在组件卸载时清除定时器
- if (timerId) {
- clearInterval(timerId);
- }
- };
- }, [timerId]);
- const startTimer = () => {
- // 避免重复启动定时器
- if (timerId) {
- return;
- }
- const id = setInterval(() => {
- setCounter((prevCounter) => prevCounter + 1);
- //每天0点刷新一下打卡数据
- var now = new Date()
- if (now.getHours() == 0 && now.getMinutes() == 0) {
- getCheckData()
- }
- }, 1000);
- setTimerId(id as any);
- };
- useReady(async () => {
- const userData = await getStorage('userData');
- if (userData) {
- dispatch(getInfoSuccess(JSON.parse(userData as string)) as any);
- setTimeout(() => {
- checkWXPubFollow()
- getCheckData()
- }, 200)
- }
- })
- if (process.env.TARO_ENV == 'weapp') {
- useShareAppMessage((e) => {
- return {
- title: t('share.title'),
- path: 'pages/clock/Clock'
- }
- })
- }
- function clearTempScenarioCache() {
- global.schedule_fast = null
- global.schedule_sleep = null
- Taro.removeStorage({
- key: 'tempScenario',
- success: function (res) {
- }
- })
- }
- usePageScroll((e) => {
- })
- useDidShow(() => {
- global.updateTab(0)
- if (user.isLogin) {
- checkWXPubFollow()
- // getCheckData();
- }
- clearTempScenarioCache()
- })
- global.refreshTime = () => {
- getCheckData()
- }
- global.showSingleFastEnd = () => {
- setShowSingleFastEnd(true)
- }
- function tapClock() {
- if (!user.isLogin) {
- jumpPage('/pages/account/ChooseAuth', 'ChooseAuth', navigation)
- }
- }
- function getCheckData() {
- getClocks().then(res => {
- setErrorPage(false)
- dispatch(updateScenario((res as any).current_record))
- dispatch(setConfigs((res as any).time_input_schema));
- dispatch(setScenario((res as any).scenario));
- if ((res as any).theme_color) {
- global.fastColor = (res as any).theme_color.fast
- global.sleepColor = (res as any).theme_color.sleep
- }
- machine.context.checkData = res as any;
- global.scenario = (res as any).current_record.scenario;
- const currentState = trackTimeService.getSnapshot();
- let json = {};
- var key = (res as any).current_record.scenario
- var status = (res as any).current_record.status
- json[key] = status
- currentState.value = json;
- machine.context.currentStatus = `${key}.${status}`;//'mixed.ON_GOING2'
- setCheckData(res as any)
- if ((res as any).current_record.status != 'ONGOING1') {
- setSwiperIndex(0)
- }
- else {
- if (global.consoleType == 'going') {
- setShowSingleFastEnd(true)
- setTimeout(() => {
- setShowSingleFastEnd(false)
- setSwiperIndex(1)
- setAutoPlay(true)
- global.consoleType = 'end'
- dispatch(changeConsoleStatus({ status: ConsoleType.end }))
- setTimeout(() => {
- global.consoleType = 'idle'
- }, 2000)
- }, 500)
- }
- else {
- }
- }
- }).catch(e => {
- console.log('aaa')
- if (!checkData) {
- console.log('this is a test')
- setErrorPage(true)
- }
- else {
- console.log('sss')
- }
- })
- }
- function checkWXPubFollow() {
- var params;
- if (global.forceRefreshWXPub) {
- params = {
- force_refresh: true
- }
- }
- global.forceRefreshWXPub = false
- wxPubFollow(params).then(res => {
- dispatch(setWXFollow((res as any).wx_pub_followed));
- console.log('当前的关注状态' + (res as any).wx_pub_followed);
- })
- }
- async function getStorage(key: string) {
- try {
- const res = await Taro.getStorage({ key });
- return res.data;
- } catch {
- return '';
- }
- }
- function schedule() {
- if (!user.isLogin) {
- return <View />
- }
- return <Schedule data={(checkData as any).current_record} />
- }
- function needSwiper() {
- var isNeed = time.scenario == 'FAST_SLEEP' &&
- (time.status == 'WAIT_FOR_START' ||
- time.status == 'ONGOING1' ||
- time.status == 'ONGOING2')
- if (showSingleFastEnd) {
- return false;
- }
- return isNeed
- }
- global.showClockModal = (isShow: boolean, detail: any) => {
- setShowModal(isShow)
- setModalDetail(detail)
- }
- global.showClockModal2 = (isShow: boolean, detail: any) => {
- setShowModal2(isShow)
- setModalDetail2(detail)
- }
- function headerView() {
- return <TitleView title={t('page.clock.title')} showAddBtn={true}>
- <StatusIndicator />
- </TitleView>
- }
- function errorView() {
- if (showErrorPage) {
- return <NoData refresh={() => { getCheckData() }} />
- }
- return <View />
- }
- function consoleView() {
- if (!checkData) {
- return <View />
- }
- return <View className='console_bg'>
- {
- needSwiper() ? <Swiper className='swiper' indicatorColor='#333'
- indicatorActiveColor='#999'
- current={swiperIndex}
- autoplay={autoPlay}
- duration={300}
- interval={300}
- // indicator-margin={30}
- indicator-offset={[0, -30]}
- indicator-height={30}
- indicatorDots={global.consoleType == 'idle'}
- onChange={(e) => {
- setSwiperIndex(e.detail.current)
- if (e.detail.current == 0)
- setAutoPlay(false)
- }}
- >
- <SwiperItem className='swiperItem'>
- <Console />
- </SwiperItem>
- <SwiperItem className='swiperItem'>
- <Console isNextStep={true} />
- </SwiperItem>
- </Swiper> :
- <Console isNextStep={showSingleFastEnd} />
- }
- </View>
- }
- function detail() {
- return (
- <Layout type={TemplateType.customHeader} header={headerView()} title={t('page.clock.title')} titleShowStyle={NaviBarTitleShowType.scrollToShow}>
- <View style={{ flex: 1, flexDirection: 'column', display: 'flex', backgroundColor: '#000', color: '#fff' }}>
- {
- needShowAddTip && <Tooltip title="添加到我的小程序" closeTip={() => { setNeedShowAddTip(false) }} />
- }
- <Box>
- <View className='clock_bg' onClick={tapClock}>
- <Clocks />
- </View>
- </Box>
- {
- errorView()
- }
- {
- user.isLogin && consoleView()
- }
- {
- user.isLogin && checkData && schedule()
- }
- {
- user.isLogin && <View style={{ backgroundColor: global.isDebug ? 'pink' : 'transparent' }}>
- {
- checkData && (checkData as any).latest_record &&
- <SectionHeader top={48} bottom={24} title={t('feature.track_time_duration.record_fast_sleep.header.latest_record')}>
- <Header title='' action={() => {
- jumpPage('/pages/common/RecordsHistory?type=time&title=time')
- }} />
- </SectionHeader>
- }
- </View>
- }
- {
- user.isLogin && checkData && (checkData as any).latest_record &&
- <RecordFastSleep type='latest' data={(checkData as any).latest_record} delSuccess={getCheckData} />
- }
- <View style={{ height: 100 }} />
- </View>
- {
- showModal && modalDetail
- }
- {
- showModal2 && modalDetail2
- }
- </Layout>
- )
- }
- if (process.env.TARO_ENV == 'rn')
- return <View />
- return detail()
- }
|