Clock.weapp.tsx 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454
  1. import { Component, PropsWithChildren, useEffect, useRef, useState } from 'react'
  2. import { View, Text, Button, Input, Picker, Swiper, SwiperItem, Icon } from '@tarojs/components'
  3. import '../index/index.scss'
  4. import './Clock.scss'
  5. // import './context/locales/index'
  6. import '@/context/locales/index'
  7. import Taro, { useDidShow, usePageScroll, useReady, useRouter, useShareAppMessage } from '@tarojs/taro'
  8. // import ComponentA from './component'
  9. import { useDispatch, useSelector } from 'react-redux';
  10. import { getInfoSuccess, logoutSuccess } from '@/store/user';
  11. import { wxPubFollow } from '@/services/permission';
  12. import { gobalConfigs, staticResources, uploadSessionKey } from '@/services/common';
  13. import Clocks from '@/features/trackTimeDuration/components/Clock';
  14. import Console from '@/features/trackTimeDuration/components/Console';
  15. import Schedule from '@/features/trackTimeDuration/components/Schedule';
  16. import { getChecks, getClocks } from '@/services/trackTimeDuration';
  17. import { setScenario } from '@/store/scenario';
  18. import { setSpecifiedStatus, setSpecifiedState, machine } from '@/store/trackTimeMachine';
  19. import trackTimeService from '@/store/trackTimeMachine';
  20. import { setWXFollow } from '@/store/permission';
  21. import Tooltip from '@/components/view/Tooltip'
  22. import RequestType, { thirdPartRequest } from '@/services/thirdPartRequest'
  23. import { setConfigs } from '@/store/common'
  24. import RecordFastSleep from '@/features/trackTimeDuration/components/RecordFastSleep'
  25. import Box from '@/components/layout/Box'
  26. import Layout from '@/components/layout/layout'
  27. import { CheckBoxType, NaviBarTitleShowType, TemplateType } from '@/utils/types'
  28. import { updateScenario } from '@/store/time'
  29. import { showModal } from '@/store/modal'
  30. import { ConsoleType, changeConsoleStatus } from '@/store/console'
  31. import TitleView from '@/features/trackTimeDuration/components/TitleView'
  32. import StatusIndicator from '@/features/trackTimeDuration/components/StatusIndicator'
  33. import { useTranslation } from 'react-i18next'
  34. import TableCellHeader from '@/components/layout/TableCellHeader'
  35. import SectionHeader from '@/components/layout/SectionHeader'
  36. import Header from '@/components/layout/Header'
  37. import { TimeFormatter } from '@/utils/time_format'
  38. import NoData from '@/components/view/NoData'
  39. import { ColorType } from '@/context/themes/color'
  40. // import TabBar from '../../components/Tabbar';
  41. // import Rings from '@components/view/Rings';
  42. export default function IndexPage() {
  43. const dispatch = useDispatch();
  44. const { t } = useTranslation()
  45. const [checkData, setCheckData] = useState(null)
  46. const user = useSelector((state: any) => state.user);
  47. const time = useSelector((state: any) => state.time);
  48. const common = useSelector((state: any) => state.common);
  49. const consoleData = useSelector((state: any) => state.console);
  50. const [counter, setCounter] = useState(0)
  51. const [timerId, setTimerId] = useState(null)
  52. const [needShowAddTip, setNeedShowAddTip] = useState(false)
  53. const [showErrorPage, setErrorPage] = useState(false)
  54. const [swiperIndex, setSwiperIndex] = useState(0)
  55. const [autoPlay, setAutoPlay] = useState(false)
  56. const [showModal, setShowModal] = useState(false)
  57. const [modalDetail, setModalDetail] = useState<any>({})
  58. const [showModal2, setShowModal2] = useState(false)
  59. const [modalDetail2, setModalDetail2] = useState<any>({})
  60. const [showSingleFastEnd, setShowSingleFastEnd] = useState(false)
  61. const [consoleStatus, setConsoleStatus] = useState(consoleData.status)
  62. global.dispatch = dispatch;
  63. global.checkData = () => {
  64. console.log('refresh clock data')
  65. getCheckData()
  66. }
  67. useEffect(() => {
  68. global.consoleType = 'idle'
  69. dispatch(staticResources() as any);
  70. // dispatch(gobalConfigs() as any);
  71. trackTimeService.onTransition(state => {
  72. if ((state.value as any).FAST_SLEEP == 'COMPLETED' ||
  73. (state.value as any).FAST == 'ONGOING' ||
  74. (state.value as any).SLEEP == 'ONGOING' ||
  75. (state.value as any).FAST_SLEEP == 'ONGOING1' ||
  76. (state.value as any).FAST_SLEEP == 'ONGOING2' ||
  77. (state.value as any).FAST_SLEEP == 'ONGOING3' ||
  78. (state.value as any).FAST == 'COMPLETED' ||
  79. (state.value as any).SLEEP == 'COMPLETED') {
  80. getCheckData()
  81. }
  82. })
  83. }, [])
  84. useEffect(() => {
  85. setConsoleStatus(consoleData.status)
  86. switch (consoleData.status) {
  87. // case ConsoleType.going:
  88. // setShowSingleFastEnd(true)
  89. // setTimeout(() => {
  90. // setShowSingleFastEnd(false)
  91. // setSwiperIndex(1)
  92. // setAutoPlay(true)
  93. // dispatch(changeConsoleStatus({ status: ConsoleType.end }))
  94. // }, 2000)
  95. // break
  96. case ConsoleType.end:
  97. setTimeout(() => {
  98. dispatch(changeConsoleStatus({ status: ConsoleType.idle }))
  99. }, 2000)
  100. break
  101. }
  102. }, [consoleData.status])
  103. useEffect(() => {
  104. if (user.isLogin) {
  105. //检查用户是否添加过小程序
  106. checkAddToMini();
  107. //检查session是否过期
  108. checkSession()
  109. getCheckData()
  110. }
  111. }, [user.isLogin])
  112. function checkSession() {
  113. if (process.env.TARO_ENV === 'weapp') {
  114. thirdPartRequest(RequestType.RequestTypeCheckSession).then(res => {
  115. }).catch(err => {
  116. console.log('session_key 已经失效,需要更新登录code')
  117. thirdPartRequest(RequestType.RequestTypeWXLogin).then(result => {
  118. uploadSessionKey({ type: 'WX_MP', code: (result as any).code });
  119. })
  120. })
  121. }
  122. }
  123. function checkAddToMini() {
  124. process.env.TARO_ENV == 'weapp' &&
  125. wx.checkIsAddedToMyMiniProgram({
  126. success: (res) => {
  127. if (!res.added) {
  128. setNeedShowAddTip(true)
  129. }
  130. },
  131. fail: (e) => {
  132. }
  133. });
  134. }
  135. useEffect(() => {
  136. startTimer();
  137. return () => {
  138. // 在组件卸载时清除定时器
  139. if (timerId) {
  140. clearInterval(timerId);
  141. }
  142. };
  143. }, [timerId]);
  144. const startTimer = () => {
  145. // 避免重复启动定时器
  146. if (timerId) {
  147. return;
  148. }
  149. const id = setInterval(() => {
  150. setCounter((prevCounter) => prevCounter + 1);
  151. //每天0点刷新一下打卡数据
  152. var now = new Date()
  153. if (now.getHours() == 0 && now.getMinutes() == 0) {
  154. getCheckData()
  155. }
  156. }, 1000);
  157. setTimerId(id as any);
  158. };
  159. useReady(async () => {
  160. const userData = await getStorage('userData');
  161. if (userData) {
  162. dispatch(getInfoSuccess(JSON.parse(userData as string)) as any);
  163. setTimeout(() => {
  164. checkWXPubFollow()
  165. getCheckData()
  166. }, 200)
  167. }
  168. })
  169. if (process.env.TARO_ENV == 'weapp') {
  170. useShareAppMessage((e) => {
  171. return {
  172. title: t('share.title'),
  173. path: 'pages/clock/Clock'
  174. }
  175. })
  176. }
  177. function clearTempScenarioCache() {
  178. global.schedule_fast = null
  179. global.schedule_sleep = null
  180. Taro.removeStorage({
  181. key: 'tempScenario',
  182. success: function (res) {
  183. }
  184. })
  185. }
  186. usePageScroll((e) => {
  187. })
  188. useDidShow(() => {
  189. global.updateTab(0)
  190. if (user.isLogin) {
  191. checkWXPubFollow()
  192. // getCheckData();
  193. }
  194. clearTempScenarioCache()
  195. })
  196. global.refreshTime = () => {
  197. getCheckData()
  198. }
  199. global.showSingleFastEnd = () => {
  200. setShowSingleFastEnd(true)
  201. }
  202. function tapClock() {
  203. if (!user.isLogin) {
  204. Taro.navigateTo({
  205. url: '/pages/account/ChooseAuth'
  206. })
  207. }
  208. }
  209. function getCheckData() {
  210. getClocks().then(res => {
  211. setErrorPage(false)
  212. dispatch(updateScenario((res as any).current_record))
  213. dispatch(setConfigs((res as any).time_input_schema));
  214. dispatch(setScenario((res as any).scenario));
  215. if ((res as any).theme_color) {
  216. global.fastColor = (res as any).theme_color.fast
  217. global.sleepColor = (res as any).theme_color.sleep
  218. }
  219. machine.context.checkData = res as any;
  220. global.scenario = (res as any).current_record.scenario;
  221. const currentState = trackTimeService.getSnapshot();
  222. let json = {};
  223. var key = (res as any).current_record.scenario
  224. var status = (res as any).current_record.status
  225. json[key] = status
  226. currentState.value = json;
  227. machine.context.currentStatus = `${key}.${status}`;//'mixed.ON_GOING2'
  228. setCheckData(res as any)
  229. if ((res as any).current_record.status != 'ONGOING1') {
  230. setSwiperIndex(0)
  231. }
  232. else {
  233. if (global.consoleType == 'going') {
  234. setShowSingleFastEnd(true)
  235. setTimeout(() => {
  236. setShowSingleFastEnd(false)
  237. setSwiperIndex(1)
  238. setAutoPlay(true)
  239. global.consoleType = 'end'
  240. dispatch(changeConsoleStatus({ status: ConsoleType.end }))
  241. setTimeout(() => {
  242. global.consoleType = 'idle'
  243. }, 2000)
  244. }, 500)
  245. }
  246. else {
  247. }
  248. }
  249. }).catch(e => {
  250. console.log('aaa')
  251. if (!checkData) {
  252. console.log('this is a test')
  253. setErrorPage(true)
  254. }
  255. else {
  256. console.log('sss')
  257. }
  258. })
  259. }
  260. function checkWXPubFollow() {
  261. wxPubFollow().then(res => {
  262. dispatch(setWXFollow((res as any).wx_pub_followed));
  263. console.log('当前的关注状态' + (res as any).wx_pub_followed);
  264. })
  265. }
  266. async function getStorage(key: string) {
  267. try {
  268. const res = await Taro.getStorage({ key });
  269. return res.data;
  270. } catch {
  271. return '';
  272. }
  273. }
  274. function schedule() {
  275. if (!user.isLogin) {
  276. return <View />
  277. }
  278. return <Schedule data={(checkData as any).current_record} />
  279. }
  280. function needSwiper() {
  281. var isNeed = time.scenario == 'FAST_SLEEP' &&
  282. (time.status == 'WAIT_FOR_START' ||
  283. time.status == 'ONGOING1' ||
  284. time.status == 'ONGOING2')
  285. if (showSingleFastEnd) {
  286. return false;
  287. }
  288. return isNeed
  289. }
  290. global.showClockModal = (isShow: boolean, detail: any) => {
  291. setShowModal(isShow)
  292. setModalDetail(detail)
  293. }
  294. global.showClockModal2 = (isShow: boolean, detail: any) => {
  295. setShowModal2(isShow)
  296. setModalDetail2(detail)
  297. }
  298. function headerView() {
  299. return <TitleView title={t('page.clock.title')} showAddBtn={true}>
  300. <StatusIndicator />
  301. </TitleView>
  302. }
  303. function errorView() {
  304. if (showErrorPage) {
  305. return <NoData refresh={() => { getCheckData() }} />
  306. }
  307. return <View />
  308. }
  309. function consoleView() {
  310. if (!checkData) {
  311. return <View />
  312. }
  313. return <View className='console_bg'>
  314. {
  315. needSwiper() ? <Swiper className='swiper' indicatorColor='#333'
  316. indicatorActiveColor='#999'
  317. current={swiperIndex}
  318. autoplay={autoPlay}
  319. duration={300}
  320. interval={300}
  321. // indicator-margin={30}
  322. indicator-offset={[0, -30]}
  323. indicator-height={30}
  324. indicatorDots={global.consoleType == 'idle'}
  325. onChange={(e) => {
  326. setSwiperIndex(e.detail.current)
  327. if (e.detail.current == 0)
  328. setAutoPlay(false)
  329. }}
  330. >
  331. <SwiperItem className='swiperItem'>
  332. <Console />
  333. </SwiperItem>
  334. <SwiperItem className='swiperItem'>
  335. <Console isNextStep={true} />
  336. </SwiperItem>
  337. </Swiper> :
  338. <Console isNextStep={showSingleFastEnd} />
  339. }
  340. </View>
  341. }
  342. function detail() {
  343. return (
  344. <Layout type={TemplateType.customHeader} header={headerView()} title={t('page.clock.title')} titleShowStyle={NaviBarTitleShowType.scrollToShow}>
  345. <View style={{ flex: 1, flexDirection: 'column', display: 'flex', backgroundColor: '#000', color: '#fff' }}>
  346. {
  347. needShowAddTip && <Tooltip title="添加到我的小程序" closeTip={() => { setNeedShowAddTip(false) }} />
  348. }
  349. <Box>
  350. <View className='clock_bg' onClick={tapClock}>
  351. <Clocks />
  352. </View>
  353. </Box>
  354. {
  355. errorView()
  356. }
  357. {
  358. user.isLogin && consoleView()
  359. }
  360. {
  361. user.isLogin && checkData && schedule()
  362. }
  363. {
  364. user.isLogin && <View style={{ backgroundColor: global.isDebug ? 'pink' : 'transparent' }}>
  365. {
  366. checkData && (checkData as any).latest_record &&
  367. <SectionHeader top={48} bottom={24} title={t('feature.track_time_duration.record_fast_sleep.header.latest_record')}>
  368. <Header title='' action={() => {
  369. Taro.navigateTo({
  370. url: '/pages/common/RecordsHistory?type=time&title=time'
  371. })
  372. }} />
  373. </SectionHeader>
  374. }
  375. </View>
  376. }
  377. {
  378. user.isLogin && checkData && (checkData as any).latest_record &&
  379. <RecordFastSleep type='latest' data={(checkData as any).latest_record} delSuccess={getCheckData} />
  380. }
  381. <View style={{ height: 100 }} />
  382. </View>
  383. {
  384. showModal && modalDetail
  385. }
  386. {
  387. showModal2 && modalDetail2
  388. }
  389. </Layout>
  390. )
  391. }
  392. if (process.env.TARO_ENV == 'rn')
  393. return <View />
  394. return detail()
  395. }