add_moment.tsx 19 KB

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