Clock.weapp.tsx 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461
  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. var params;
  262. if (global.forceRefreshWXPub){
  263. params = {
  264. force_refresh:true
  265. }
  266. }
  267. global.forceRefreshWXPub = false
  268. wxPubFollow(params).then(res => {
  269. dispatch(setWXFollow((res as any).wx_pub_followed));
  270. console.log('当前的关注状态' + (res as any).wx_pub_followed);
  271. })
  272. }
  273. async function getStorage(key: string) {
  274. try {
  275. const res = await Taro.getStorage({ key });
  276. return res.data;
  277. } catch {
  278. return '';
  279. }
  280. }
  281. function schedule() {
  282. if (!user.isLogin) {
  283. return <View />
  284. }
  285. return <Schedule data={(checkData as any).current_record} />
  286. }
  287. function needSwiper() {
  288. var isNeed = time.scenario == 'FAST_SLEEP' &&
  289. (time.status == 'WAIT_FOR_START' ||
  290. time.status == 'ONGOING1' ||
  291. time.status == 'ONGOING2')
  292. if (showSingleFastEnd) {
  293. return false;
  294. }
  295. return isNeed
  296. }
  297. global.showClockModal = (isShow: boolean, detail: any) => {
  298. setShowModal(isShow)
  299. setModalDetail(detail)
  300. }
  301. global.showClockModal2 = (isShow: boolean, detail: any) => {
  302. setShowModal2(isShow)
  303. setModalDetail2(detail)
  304. }
  305. function headerView() {
  306. return <TitleView title={t('page.clock.title')} showAddBtn={true}>
  307. <StatusIndicator />
  308. </TitleView>
  309. }
  310. function errorView() {
  311. if (showErrorPage) {
  312. return <NoData refresh={() => { getCheckData() }} />
  313. }
  314. return <View />
  315. }
  316. function consoleView() {
  317. if (!checkData) {
  318. return <View />
  319. }
  320. return <View className='console_bg'>
  321. {
  322. needSwiper() ? <Swiper className='swiper' indicatorColor='#333'
  323. indicatorActiveColor='#999'
  324. current={swiperIndex}
  325. autoplay={autoPlay}
  326. duration={300}
  327. interval={300}
  328. // indicator-margin={30}
  329. indicator-offset={[0, -30]}
  330. indicator-height={30}
  331. indicatorDots={global.consoleType == 'idle'}
  332. onChange={(e) => {
  333. setSwiperIndex(e.detail.current)
  334. if (e.detail.current == 0)
  335. setAutoPlay(false)
  336. }}
  337. >
  338. <SwiperItem className='swiperItem'>
  339. <Console />
  340. </SwiperItem>
  341. <SwiperItem className='swiperItem'>
  342. <Console isNextStep={true} />
  343. </SwiperItem>
  344. </Swiper> :
  345. <Console isNextStep={showSingleFastEnd} />
  346. }
  347. </View>
  348. }
  349. function detail() {
  350. return (
  351. <Layout type={TemplateType.customHeader} header={headerView()} title={t('page.clock.title')} titleShowStyle={NaviBarTitleShowType.scrollToShow}>
  352. <View style={{ flex: 1, flexDirection: 'column', display: 'flex', backgroundColor: '#000', color: '#fff' }}>
  353. {
  354. needShowAddTip && <Tooltip title="添加到我的小程序" closeTip={() => { setNeedShowAddTip(false) }} />
  355. }
  356. <Box>
  357. <View className='clock_bg' onClick={tapClock}>
  358. <Clocks />
  359. </View>
  360. </Box>
  361. {
  362. errorView()
  363. }
  364. {
  365. user.isLogin && consoleView()
  366. }
  367. {
  368. user.isLogin && checkData && schedule()
  369. }
  370. {
  371. user.isLogin && <View style={{ backgroundColor: global.isDebug ? 'pink' : 'transparent' }}>
  372. {
  373. checkData && (checkData as any).latest_record &&
  374. <SectionHeader top={48} bottom={24} title={t('feature.track_time_duration.record_fast_sleep.header.latest_record')}>
  375. <Header title='' action={() => {
  376. Taro.navigateTo({
  377. url: '/pages/common/RecordsHistory?type=time&title=time'
  378. })
  379. }} />
  380. </SectionHeader>
  381. }
  382. </View>
  383. }
  384. {
  385. user.isLogin && checkData && (checkData as any).latest_record &&
  386. <RecordFastSleep type='latest' data={(checkData as any).latest_record} delSuccess={getCheckData} />
  387. }
  388. <View style={{ height: 100 }} />
  389. </View>
  390. {
  391. showModal && modalDetail
  392. }
  393. {
  394. showModal2 && modalDetail2
  395. }
  396. </Layout>
  397. )
  398. }
  399. if (process.env.TARO_ENV == 'rn')
  400. return <View />
  401. return detail()
  402. }