add_moment.tsx 19 KB

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