add_moment.tsx 18 KB

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