add_moment.tsx 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601
  1. import { View, Text, Textarea, Image, Input, ScrollView } from "@tarojs/components";
  2. import Taro, { useLoad, useRouter, useUnload } from "@tarojs/taro";
  3. import { useTranslation } from "react-i18next";
  4. import './add_moment.scss'
  5. import { useEffect, useState } from "react";
  6. import { saveFoodCache } from "@/features/food/hooks/ExtraData";
  7. import { baseUrl } from "@/services/http/api";
  8. import { checkAuthorized } from "@/utils/check_authorized";
  9. import { eatMeals } from "@/services/trackSomething";
  10. import Modal from "@/components/layout/Modal.weapp";
  11. import dayjs from "dayjs";
  12. import TimePicker from "@/features/common/TimePicker";
  13. import { MainColorType } from "@/context/themes/color";
  14. import { createMoment, getLabelsEvent, updateMoment } from "@/services/health";
  15. import { useDispatch, useSelector } from "react-redux";
  16. import { getThemeColor } from "@/features/health/hooks/health_hooks";
  17. import DurationPicker from "../components/duration_picker";
  18. import NewModal from "../base/new_modal";
  19. import PostMomentTime from "../components/post_moment_time";
  20. import AddLabel from "../components/add_label";
  21. import showAlert from "@/components/basic/Alert";
  22. import NewButton, { NewButtonType } from "../base/new_button";
  23. import { rpxToPx } from "@/utils/tools";
  24. import StatusIndicator, { StatusType } from "../base/status_indicator";
  25. import { IconCheck } from "@/components/basic/Icons";
  26. let useRoute;
  27. let useNavigation;
  28. let scenario = '';
  29. if (process.env.TARO_ENV == 'rn') {
  30. useRoute = require("@react-navigation/native").useRoute
  31. useNavigation = require("@react-navigation/native").useNavigation
  32. }
  33. export default function AddMoment() {
  34. const [enterTimestmap] = useState(new Date().getTime())
  35. const [desc, setDesc] = useState('')
  36. const { t } = useTranslation()
  37. const [imgUrl, setImgUrl] = useState('')
  38. const [showPicker, setShowPicker] = useState(false)
  39. const [durationPicker, setDurationPicker] = useState(false)
  40. const [durationT, setDurationT] = useState(0)
  41. const dispatch = useDispatch()
  42. const health = useSelector((state: any) => state.health);
  43. const [timestamp, setTimestamp] = useState(new Date().getTime())
  44. const [showTimePicker, setShowTimePicker] = useState(false)
  45. const [showTitlePicker, setShowTitlePicker] = useState(false)
  46. const [isYesterday, setIsYesterday] = useState(false)
  47. const [labels, setLabels] = useState<any>([])
  48. const [bottom, setBottom] = useState(-120)
  49. const [titleFocus, setTitleFocus] = useState(false)
  50. const [posting, setPosting] = useState(false)
  51. let router
  52. let navigation;
  53. if (useNavigation) {
  54. navigation = useNavigation()
  55. }
  56. if (process.env.TARO_ENV == 'rn') {
  57. router = useRoute()
  58. }
  59. else {
  60. router = useRouter()
  61. }
  62. const [time, setTime] = useState(dayjs().format('HH:mm'))
  63. const [selDate, setSelDate] = useState(dayjs().format('YYYY-MM-DD'))
  64. const [title, setTitle] = useState(router.params.title)
  65. const { event_id, is_temp, schedule_id } = router.params
  66. const moment = router.params.moment ? JSON.parse(router.params.moment) : null
  67. useEffect(() => {
  68. global.set_time = new Date().getTime()
  69. // Taro.onKeyboardHeightChange(res => {
  70. // setBottom(res.height > 0 ? res.height : -120)
  71. // })
  72. getLabelsEvent({ window: health.mode, use: is_temp ? 'ONE_RECORD' : '' }).then(res => {
  73. setLabels((res as any).labels)
  74. if (is_temp && title == '') {
  75. // setShowTitlePicker(true)
  76. }
  77. })
  78. if (router.params.edit) {
  79. var detail = JSON.parse(router.params.detail)
  80. setTitle(detail.title)
  81. var moment = detail.moments[0]
  82. setDesc(moment.description)
  83. var timeObj = moment.time
  84. setTime(dayjs(timeObj.timestamp).format('HH:mm'))
  85. setSelDate(dayjs(timeObj.timestamp).format('YYYY-MM-DD'))
  86. if (moment.media.length > 0) {
  87. setImgUrl(moment.media[0].url)
  88. }
  89. }
  90. else {
  91. Taro.enableAlertBeforeUnload({
  92. message: t('health.quit_tip'),
  93. success(res) {
  94. },
  95. fail(res) {
  96. },
  97. complete(res) {
  98. },
  99. })
  100. }
  101. }, [])
  102. useLoad(() => {
  103. })
  104. useUnload(() => {
  105. Taro.disableAlertBeforeUnload({
  106. })
  107. })
  108. function duration() {
  109. const seconds = durationT / 1000
  110. var hours = Math.floor(seconds / 3600)
  111. var minutes = Math.floor((seconds % 3600) / 60)
  112. // const { hours, minutes } = getIntervalHoursAndMinutes(meal.schedule_end_time, meal.schedule_start_time)
  113. var time = ''
  114. if (hours > 0) {
  115. time = hours + '小时'
  116. }
  117. if (minutes > 0) {
  118. time += minutes + '分钟'
  119. }
  120. return time
  121. }
  122. function tapTime() {
  123. setShowPicker(true)
  124. }
  125. function tapDuration() {
  126. setDurationPicker(true)
  127. }
  128. function addImage(isCamera) {
  129. Taro.chooseMedia({
  130. count: 1,
  131. sizeType: ['compressed'],
  132. mediaType: ['image'],
  133. sourceType: [isCamera ? 'camera' : 'album'],
  134. success: function (res) {
  135. chooseSuccess(res, true)
  136. checkAuthorized()
  137. },
  138. fail: function (res) {
  139. }
  140. })
  141. }
  142. function save() {
  143. // if (desc.length == 0 && imgUrl.length == 0) {
  144. // Taro.showToast({
  145. // icon: 'none',
  146. // title: '请输入描述或添加图片'
  147. // })
  148. // return
  149. // }
  150. if (router.params.edit) {
  151. edit()
  152. return
  153. }
  154. // var date = new Date(timestamp)
  155. // var hour = parseInt(time.split(':')[0] + '')
  156. // var minute = parseInt(time.split(':')[1] + '')
  157. // date.setHours(hour)
  158. // date.setMinutes(minute)
  159. // var timestamp1 = date.getTime()
  160. // if (isYesterday) {
  161. // timestamp1 -= 24 * 3600 * 1000
  162. // }
  163. // debugger
  164. var date = new Date(selDate + ' ' + time + ':' + dayjs(enterTimestmap).format('ss'))
  165. date.setMilliseconds(new Date(enterTimestmap).getMilliseconds())
  166. var params: any = {
  167. schedule_id: schedule_id,
  168. title: title,
  169. description: desc,
  170. start: {
  171. date: dayjs(date.getTime()).format('YYYYMMDD'),
  172. timestamp: date.getTime()
  173. }
  174. }
  175. if (imgUrl.length > 0) {
  176. params.media = [{
  177. url: imgUrl,
  178. type: imgUrl.indexOf('mp4') != -1 ? 'video' : 'image',
  179. source: 'album'
  180. }]
  181. }
  182. if (event_id && event_id != 'undefined') {
  183. params.event_id = event_id
  184. }
  185. if (is_temp) {
  186. params.event = health.mode == 'EAT' ? 'EAT_CUSTOM' : 'ACTIVE_CUSTOM'
  187. }
  188. // if (moment.target && moment.target.duration) {
  189. // params.duration = durationT//moment.target.duration
  190. // }
  191. if (durationT) {
  192. params.duration = durationT * 60 * 1000
  193. }
  194. params.extra = {
  195. set_time: global.set_time ? global.set_time : new Date().getTime(),
  196. confirm_time: new Date().getTime()
  197. }
  198. if (posting) return
  199. setPosting(true)
  200. createMoment(params).then(res => {
  201. setTimeout(() => {
  202. setPosting(false)
  203. }, 1000)
  204. if (process.env.TARO_ENV == 'weapp') {
  205. // Taro.navigateBack();
  206. Taro.redirectTo({
  207. url: '/_health/pages/post_result?data=' + JSON.stringify(res)
  208. })
  209. }
  210. // if (health.mode == 'EAT') {
  211. // dispatch(setShowActionTip({
  212. // isShow: true,
  213. // isCompleted: false
  214. // }))
  215. // }
  216. Taro.disableAlertBeforeUnload({
  217. })
  218. global.refreshWindow()
  219. global.refreshHistory()
  220. if (global.postMomentSuccess) {
  221. global.postMomentSuccess()
  222. }
  223. }).catch(e => {
  224. debugger
  225. setPosting(false)
  226. })
  227. }
  228. function edit() {
  229. var date = new Date(selDate + ' ' + time + ':' + dayjs(enterTimestmap).format('ss'))
  230. var params: any = {
  231. schedule_id: schedule_id,
  232. title: title,
  233. description: desc,
  234. start: {
  235. date: dayjs(date.getTime()).format('YYYYMMDD'),
  236. timestamp: date.getTime()
  237. }
  238. }
  239. if (imgUrl.length > 0) {
  240. params.media = [{
  241. url: imgUrl,
  242. type: imgUrl.indexOf('mp4') != -1 ? 'video' : 'image',
  243. source: 'album'
  244. }]
  245. }
  246. if (event_id && event_id != 'undefined') {
  247. params.event_id = event_id
  248. }
  249. if (is_temp) {
  250. params.event = health.mode == 'EAT' ? 'EAT_CUSTOM' : 'ACTIVE_CUSTOM'
  251. }
  252. // if (moment.target && moment.target.duration) {
  253. // params.duration = durationT//moment.target.duration
  254. // }
  255. if (durationT) {
  256. params.duration = durationT * 60 * 1000
  257. }
  258. Taro.disableAlertBeforeUnload({
  259. })
  260. params.extra = {
  261. set_time: global.set_time ? global.set_time : new Date().getTime(),
  262. confirm_time: new Date().getTime()
  263. }
  264. if (posting) return
  265. setPosting(true)
  266. updateMoment(params, router.params.id).then(res => {
  267. setPosting(false)
  268. if (process.env.TARO_ENV == 'weapp') {
  269. Taro.navigateBack();
  270. // Taro.redirectTo({
  271. // url: '/_health/pages/post_result?data=' + JSON.stringify(res)
  272. // })
  273. }
  274. global.refreshWindow()
  275. global.refreshHistory()
  276. global.refreshMoment()
  277. }).catch(e => {
  278. setPosting(false)
  279. })
  280. }
  281. async function chooseSuccess(res, isAlbum) {
  282. var params = {
  283. event: 'add_a_picture',
  284. value: isAlbum ? 'choose_from_album_confirm' : 'use_camera_confirm',
  285. }
  286. saveFoodCache('create', params)
  287. var savedFilePath = process.env.TARO_ENV == 'rn' ? res.tempFiles[0].path : res.tempFiles[0].tempFilePath
  288. // var savedFilePath = res.savedFilePath
  289. // await Taro.setStorage({ key: 'pic', data: savedFilePath })
  290. // setImgUrl(savedFilePath as any)
  291. uploadFile(savedFilePath, isAlbum ? 'album' : 'camera')
  292. }
  293. function uploadFile(path, source) {
  294. Taro.showLoading({
  295. title: '加载中'
  296. })
  297. var dot = path.lastIndexOf('.')
  298. var fileExt = dot > 0 ? path.substring(dot) : ''
  299. Taro.request({
  300. method: 'GET',
  301. url: `${baseUrl}/api/thirdparty/aliyun/oss-form-upload`,
  302. header: {
  303. 'Authorization': 'bearer ' + global.token
  304. },
  305. data: {
  306. type: 'FOOD_JOURNAL',
  307. file_ext: fileExt
  308. },
  309. success: (rsp) => {
  310. if (rsp.statusCode != 200) {
  311. Taro.showToast({
  312. title: '操作失败,请检查网络',
  313. icon: 'none'
  314. })
  315. return
  316. }
  317. Taro.uploadFile({
  318. url: rsp.data.upload_url,
  319. filePath: path,
  320. name: 'file',
  321. formData: rsp.data.fields,
  322. success: rlt => {
  323. setImgUrl(rsp.data.view_url)
  324. Taro.hideLoading()
  325. // createData(rsp.data.view_url, source)
  326. // uploadAvatar(rsp.data.view_url)
  327. // _this.changeAvatar(rsp.data.view_url);
  328. },
  329. fail: rlt => {
  330. Taro.hideLoading()
  331. Taro.showModal({
  332. content: rlt.errMsg
  333. })
  334. }
  335. })
  336. }
  337. })
  338. }
  339. function timeContent() {
  340. return <Modal
  341. testInfo={null}
  342. dismiss={() => {
  343. setShowPicker(false)
  344. }}
  345. confirm={() => { }}>
  346. {
  347. pickerContent()
  348. }
  349. </Modal>
  350. }
  351. function pickerContent() {
  352. return <TimePicker time={time}
  353. color={MainColorType.eat}
  354. title={title}
  355. confirm={(e) => {
  356. confirmPickerTime(e)
  357. }}
  358. cancel={() => {
  359. setShowPicker(false)
  360. }} />
  361. }
  362. function confirmPickerTime(e) {
  363. const list = e.split(':')
  364. const date = new Date()
  365. date.setHours(list[0])
  366. date.setMinutes(list[1])
  367. console.log(date)
  368. setTimestamp(date.getTime())
  369. setShowPicker(false)
  370. }
  371. function durationContent() {
  372. return <View></View>
  373. }
  374. function getDate() {
  375. var sel = dayjs(selDate)
  376. var now = dayjs().format('YYYY-MM-DD')
  377. const yesterday = dayjs().subtract(1, 'day');
  378. if (sel.format('YYYY-MM-DD') == now) {
  379. return ''
  380. }
  381. if (yesterday.format('YYYY-MM-DD') == sel.format('YYYY-MM-DD')) {
  382. return global.language == 'en' ? 'Yesterday ' : '昨天 '
  383. }
  384. else {
  385. return global.language == 'en' ? sel.format('MMM D ') : sel.format('MMMD日 ')
  386. }
  387. }
  388. return <View>
  389. {/* {
  390. health.mode != 'FAST' && health.mode != 'SLEEP' &&
  391. <View className="addmoment_header">
  392. <Text className="header_time" onClick={tapTime} style={{ color: getThemeColor(health.mode) }}>{dayjs().format('HH:mm')}</Text>
  393. {
  394. (health.mode == 'EAT' || health.mode == 'ACTIVE') && <View className="header_line" />
  395. }
  396. {
  397. (health.mode == 'EAT' || health.mode == 'ACTIVE') && <Text className="header_time" style={{ color: getThemeColor(health.mode) }} onClick={tapDuration}>{duration()}</Text>
  398. }
  399. </View>
  400. } */}
  401. <View style={{
  402. display: 'flex',
  403. backgroundColor: '#fff',
  404. // padding: rpxToPx(40),
  405. flexDirection: 'column',
  406. height: rpxToPx(642),
  407. width: rpxToPx(750),
  408. boxSizing: 'border-box'
  409. }}>
  410. <View className="addmoment_header" onClick={() => {
  411. setShowTimePicker(true)
  412. }}>
  413. <StatusIndicator type={StatusType.big}
  414. color={getThemeColor(health.mode)}
  415. fontSize={rpxToPx(30)}
  416. fontColor={getThemeColor(health.mode)}
  417. text={getDate() + time}>
  418. <IconCheck color="#fff" width={rpxToPx(24)} height={24} />
  419. </StatusIndicator>
  420. <View className="h22" style={{ color: MainColorType.link, marginTop: rpxToPx(8) }}>{t('health.edit_time')}</View>
  421. </View>
  422. <Input className="meal_name" value={title}
  423. placeholder={health.mode == 'EAT' ? 'Meal Name' : 'Active Name'}
  424. style={{ caretColor: getThemeColor(health.mode) }}
  425. // cursorColor='#ff0000'
  426. onFocus={() => {
  427. setTitleFocus(true)
  428. }}
  429. onBlur={() => {
  430. setTitleFocus(false)
  431. }}
  432. onInput={(e: any) => {
  433. setTitle(e.target.value)
  434. }}
  435. onKeyboardHeightChange={(e) => {
  436. setBottom(e.detail.height > 0 ? e.detail.height : -120)
  437. }}
  438. />
  439. <View style={{ position: 'relative' }}>
  440. <View className="border_footer_line" style={{ left: rpxToPx(96) }} />
  441. </View>
  442. <View className="tag_list">
  443. <ScrollView style={{ width: rpxToPx(750), flexDirection: 'row', display: 'flex', height: rpxToPx(108) }} scrollX enableFlex showScrollbar={false}>
  444. <View style={{ width: rpxToPx(96), flexShrink: 0 }} />
  445. {
  446. labels.map((item, index) => {
  447. return <View className="add_page_tag_btn" key={index} onClick={() => {
  448. setTitle(item.title)
  449. }}>{item.title}</View>
  450. })
  451. }
  452. <View style={{ width: rpxToPx(40), flexShrink: 0 }} />
  453. </ScrollView>
  454. </View>
  455. <View style={{ height: rpxToPx(40), flexShrink: 0 }} />
  456. <Textarea placeholder="简单描述(选填)" className="textarea g01"
  457. placeholder-style="color:#B2B2B2"
  458. value={desc}
  459. onInput={e => {
  460. setDesc(e.detail.value)
  461. }} />
  462. <View className="form">
  463. {
  464. imgUrl.length > 0 && <View className="cover" ><NewButton type={NewButtonType.img} onClick={() => addImage(false)}><Image src={imgUrl} mode="aspectFill" className="cover" onClick={addImage} /></NewButton></View>
  465. }
  466. {
  467. imgUrl.length == 0 && <View style={{ display: 'flex', flexDirection: 'row' }}>
  468. <View className="cover" ><NewButton type={NewButtonType.img} onClick={() => addImage(false)}><View className="cover" >
  469. <Image src={require('@assets/_health/album.png')} style={{ width: 40, height: 40 }} />
  470. </View></NewButton></View>
  471. <View className="cover" style={{ marginLeft: rpxToPx(40) }}><NewButton type={NewButtonType.img} onClick={() => addImage(true)}><View className="cover" >
  472. <Image src={require('@assets/_health/camera.png')} style={{ width: 40, height: 40 }} />
  473. </View></NewButton></View>
  474. </View>
  475. }
  476. </View>
  477. </View>
  478. <View style={{ flex: 1 }} />
  479. <View className="main_footer"><NewButton
  480. type={NewButtonType.fill}
  481. color={getThemeColor(health.mode)}
  482. width={rpxToPx(646)}
  483. height={rpxToPx(96)}
  484. title={t('health.log_moment')}
  485. onClick={save}
  486. /></View>
  487. {/* <View className="save" style={{ backgroundColor: getThemeColor(health.mode) }} onClick={save}>Save</View> */}
  488. {
  489. showPicker && timeContent()
  490. }
  491. {
  492. showTimePicker && <PostMomentTime
  493. time={time}
  494. date={selDate}
  495. isTemp={is_temp}
  496. moment={moment}
  497. onChange={(e) => {
  498. const { date, duration, time, isYesterday } = e;
  499. setTime(time)
  500. setSelDate(date)
  501. setIsYesterday(isYesterday)
  502. setDurationT(duration)
  503. setShowTimePicker(false)
  504. }} dismiss={() => {
  505. setShowTimePicker(false)
  506. }} />
  507. }
  508. </View>
  509. }