add_moment.tsx 18 KB

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