add_moment.tsx 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568
  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 { setShowActionTip } from "@/store/health";
  18. import DurationPicker from "../components/duration_picker";
  19. import NewModal from "../base/new_modal";
  20. import PostMomentTime from "../components/post_moment_time";
  21. import AddLabel from "../components/add_label";
  22. import showAlert from "@/components/basic/Alert";
  23. import NewButton, { NewButtonType } from "../base/new_button";
  24. import { rpxToPx } from "@/utils/tools";
  25. import StatusIndicator, { StatusType } from "../base/status_indicator";
  26. import { IconCheck } from "@/components/basic/Icons";
  27. let useRoute;
  28. let useNavigation;
  29. let scenario = '';
  30. if (process.env.TARO_ENV == 'rn') {
  31. useRoute = require("@react-navigation/native").useRoute
  32. useNavigation = require("@react-navigation/native").useNavigation
  33. }
  34. export default function AddMoment() {
  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. 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. debugger
  88. }
  89. }, [])
  90. useLoad(() => {
  91. if (!router.params.edit)
  92. Taro.enableAlertBeforeUnload({
  93. message: 'hhh',
  94. success(res) {
  95. },
  96. fail(res) {
  97. },
  98. complete(res) {
  99. },
  100. })
  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. })
  213. }
  214. function edit() {
  215. var date = new Date(selDate + ' ' + time + ':00')
  216. var params: any = {
  217. schedule_id: schedule_id,
  218. title: title,
  219. description: desc,
  220. start: {
  221. date: dayjs(date.getTime()).format('YYYYMMDD'),
  222. timestamp: date.getTime()
  223. }
  224. }
  225. if (imgUrl.length > 0) {
  226. params.media = [{
  227. url: imgUrl,
  228. type: imgUrl.indexOf('mp4') != -1 ? 'video' : 'image',
  229. source: 'album'
  230. }]
  231. }
  232. if (event_id && event_id != 'undefined') {
  233. params.event_id = event_id
  234. }
  235. if (is_temp) {
  236. params.event = health.mode == 'EAT' ? 'EAT_CUSTOM' : 'ACTIVE_CUSTOM'
  237. }
  238. // if (moment.target && moment.target.duration) {
  239. // params.duration = durationT//moment.target.duration
  240. // }
  241. if (durationT) {
  242. params.duration = durationT * 60 * 1000
  243. }
  244. params.extra = {
  245. set_time: global.set_time ? global.set_time : new Date().getTime(),
  246. confirm_time: new Date().getTime()
  247. }
  248. updateMoment(params, router.params.id).then(res => {
  249. if (process.env.TARO_ENV == 'weapp') {
  250. Taro.navigateBack();
  251. // Taro.redirectTo({
  252. // url: '/_health/pages/post_result?data=' + JSON.stringify(res)
  253. // })
  254. }
  255. global.refreshWindow()
  256. global.refreshHistory()
  257. global.refreshMoment()
  258. })
  259. }
  260. async function chooseSuccess(res, isAlbum) {
  261. var params = {
  262. event: 'add_a_picture',
  263. value: isAlbum ? 'choose_from_album_confirm' : 'use_camera_confirm',
  264. }
  265. saveFoodCache('create', params)
  266. var savedFilePath = process.env.TARO_ENV == 'rn' ? res.tempFiles[0].path : res.tempFiles[0].tempFilePath
  267. // var savedFilePath = res.savedFilePath
  268. await Taro.setStorage({ key: 'pic', data: savedFilePath })
  269. setImgUrl(savedFilePath as any)
  270. uploadFile(savedFilePath, isAlbum ? 'album' : 'camera')
  271. }
  272. function uploadFile(path, source) {
  273. Taro.showLoading({
  274. title: '加载中'
  275. })
  276. var dot = path.lastIndexOf('.')
  277. var fileExt = dot > 0 ? path.substring(dot) : ''
  278. Taro.request({
  279. method: 'GET',
  280. url: `${baseUrl}/api/thirdparty/aliyun/oss-form-upload`,
  281. header: {
  282. 'Authorization': 'bearer ' + global.token
  283. },
  284. data: {
  285. type: 'FOOD_JOURNAL',
  286. file_ext: fileExt
  287. },
  288. success: (rsp) => {
  289. if (rsp.statusCode != 200) {
  290. Taro.showToast({
  291. title: '操作失败,请检查网络',
  292. icon: 'none'
  293. })
  294. return
  295. }
  296. Taro.uploadFile({
  297. url: rsp.data.upload_url,
  298. filePath: path,
  299. name: 'file',
  300. formData: rsp.data.fields,
  301. success: rlt => {
  302. setImgUrl(rsp.data.view_url)
  303. Taro.hideLoading()
  304. // createData(rsp.data.view_url, source)
  305. // uploadAvatar(rsp.data.view_url)
  306. // _this.changeAvatar(rsp.data.view_url);
  307. },
  308. fail: rlt => {
  309. Taro.hideLoading()
  310. Taro.showModal({
  311. content: rlt.errMsg
  312. })
  313. }
  314. })
  315. }
  316. })
  317. }
  318. function timeContent() {
  319. return <Modal
  320. testInfo={null}
  321. dismiss={() => {
  322. setShowPicker(false)
  323. }}
  324. confirm={() => { }}>
  325. {
  326. pickerContent()
  327. }
  328. </Modal>
  329. }
  330. function pickerContent() {
  331. return <TimePicker time={time}
  332. color={MainColorType.eat}
  333. title={title}
  334. confirm={(e) => {
  335. confirmPickerTime(e)
  336. }}
  337. cancel={() => {
  338. setShowPicker(false)
  339. }} />
  340. }
  341. function confirmPickerTime(e) {
  342. const list = e.split(':')
  343. const date = new Date()
  344. date.setHours(list[0])
  345. date.setMinutes(list[1])
  346. console.log(date)
  347. setTimestamp(date.getTime())
  348. setShowPicker(false)
  349. }
  350. function durationContent() {
  351. return <View></View>
  352. }
  353. function getDate() {
  354. var sel = dayjs(selDate)
  355. var now = dayjs().format('YYYY-MM-DD')
  356. const yesterday = dayjs().subtract(1, 'day');
  357. if (sel.format('YYYY-MM-DD') == now) {
  358. return ''
  359. }
  360. if (yesterday.format('YYYY-MM-DD') == sel.format('YYYY-MM-DD')) {
  361. return global.languange == 'en' ? 'Yesterday ' : '昨天 '
  362. }
  363. else {
  364. return global.languange == 'en' ? sel.format('MMM D ') : sel.format('MMMD日 ')
  365. }
  366. }
  367. return <View>
  368. {/* {
  369. health.mode != 'FAST' && health.mode != 'SLEEP' &&
  370. <View className="addmoment_header">
  371. <Text className="header_time" onClick={tapTime} style={{ color: getThemeColor(health.mode) }}>{dayjs().format('HH:mm')}</Text>
  372. {
  373. (health.mode == 'EAT' || health.mode == 'ACTIVE') && <View className="header_line" />
  374. }
  375. {
  376. (health.mode == 'EAT' || health.mode == 'ACTIVE') && <Text className="header_time" style={{ color: getThemeColor(health.mode) }} onClick={tapDuration}>{duration()}</Text>
  377. }
  378. </View>
  379. } */}
  380. <View style={{
  381. display: 'flex',
  382. backgroundColor: '#fff',
  383. // padding: rpxToPx(40),
  384. flexDirection: 'column',
  385. height: rpxToPx(550),
  386. width: rpxToPx(750),
  387. boxSizing: 'border-box'
  388. }}>
  389. <View className="addmoment_header" onClick={() => {
  390. setShowTimePicker(true)
  391. }}>
  392. <StatusIndicator type={StatusType.big}
  393. color={getThemeColor(health.mode)}
  394. fontSize={rpxToPx(30)}
  395. fontColor={getThemeColor(health.mode)}
  396. text={getDate() + time}>
  397. <IconCheck color="#fff" width={rpxToPx(24)} height={24} />
  398. </StatusIndicator>
  399. <View className="h22" style={{ color: MainColorType.link, marginTop: rpxToPx(8) }}>编辑打卡</View>
  400. </View>
  401. <Input className="meal_name" value={title}
  402. placeholder={health.mode == 'EAT' ? 'Meal Name' : 'Active Name'}
  403. style={{ caretColor: getThemeColor(health.mode) }}
  404. // cursorColor='#ff0000'
  405. // onFocus={() => {
  406. // setTitleFocus(true)
  407. // }}
  408. // onBlur={() => {
  409. // setTitleFocus(false)
  410. // }}
  411. onInput={(e: any) => {
  412. setTitle(e.target.value)
  413. }}
  414. onKeyboardHeightChange={(e) => {
  415. setBottom(e.detail.height > 0 ? e.detail.height : -120)
  416. }}
  417. />
  418. <Textarea placeholder="简单描述(选填)" className="textarea"
  419. placeholder-style="color:#B2B2B2"
  420. value={desc}
  421. onInput={e => {
  422. setDesc(e.detail.value)
  423. }} />
  424. <View className="form">
  425. {
  426. imgUrl.length > 0 && <View className="cover" ><NewButton type={NewButtonType.img} onClick={() => addImage(false)}><Image src={imgUrl} mode="aspectFill" className="cover" onClick={addImage} /></NewButton></View>
  427. }
  428. {
  429. imgUrl.length == 0 && <View style={{ display: 'flex', flexDirection: 'row' }}>
  430. <View className="cover" ><NewButton type={NewButtonType.img} onClick={() => addImage(false)}><View className="cover" >
  431. <Image src={require('@assets/_health/album.png')} style={{ width: 40, height: 40 }} />
  432. </View></NewButton></View>
  433. <View className="cover" style={{ marginLeft: rpxToPx(40) }}><NewButton type={NewButtonType.img} onClick={() => addImage(true)}><View className="cover" >
  434. <Image src={require('@assets/_health/camera.png')} style={{ width: 40, height: 40 }} />
  435. </View></NewButton></View>
  436. </View>
  437. }
  438. </View>
  439. </View>
  440. <View style={{ flex: 1 }} />
  441. <View className="main_footer"><NewButton
  442. type={NewButtonType.fill}
  443. color={getThemeColor(health.mode)}
  444. width={rpxToPx(646)}
  445. height={rpxToPx(96)}
  446. title={t('health.log')}
  447. onClick={save}
  448. /></View>
  449. {/* <View className="save" style={{ backgroundColor: getThemeColor(health.mode) }} onClick={save}>Save</View> */}
  450. {
  451. showPicker && timeContent()
  452. }
  453. {
  454. showTimePicker && <PostMomentTime
  455. time={time}
  456. date={selDate}
  457. isTemp={is_temp}
  458. moment={moment}
  459. onChange={(e) => {
  460. const { date, duration, time, isYesterday } = e;
  461. setTime(time)
  462. setSelDate(date)
  463. setIsYesterday(isYesterday)
  464. setDurationT(duration)
  465. setShowTimePicker(false)
  466. }} dismiss={() => {
  467. setShowTimePicker(false)
  468. }} />
  469. }
  470. {
  471. <View className="tag_list" style={{ bottom: bottom }}>
  472. <ScrollView style={{ width: rpxToPx(750), flexDirection: 'row', display: 'flex', height: rpxToPx(108) }} scrollX enableFlex showScrollbar={false}>
  473. <View style={{ width: rpxToPx(40), flexShrink: 0 }} />
  474. {
  475. labels.map((item, index) => {
  476. return <View className="add_page_tag_btn" key={index} onClick={() => {
  477. setTitle(item.title)
  478. }}>{item.title}</View>
  479. })
  480. }
  481. <View style={{ width: rpxToPx(40), flexShrink: 0 }} />
  482. </ScrollView>
  483. </View>
  484. }
  485. </View>
  486. }