import { View, Image, PageMeta, NavigationBar, Input, Textarea, ScrollView, Snapshot, PickerView, PickerViewColumn, Text } from "@tarojs/components"; import './record_log.scss' import { useEffect, useState } from "react"; import Taro, { useRouter, useShareAppMessage } from "@tarojs/taro"; import { rpxToPx } from "@/utils/tools"; import { IconAdd, IconArrow, IconCheck, IconClose } from "@/components/basic/Icons"; import { MainColorType } from "@/context/themes/color"; import { useTranslation } from "react-i18next"; import showAlert from "@/components/basic/Alert"; import showActionSheet from "@/components/basic/ActionSheet"; import { BASE_IMG_URL, baseUrl } from "@/services/http/api"; import { checkAuthorized } from "@/utils/check_authorized"; import NewButton, { NewButtonType } from "@/_health/base/new_button"; import dayjs from "dayjs"; import { TimeFormatter } from "@/utils/time_format"; import { useSelector } from "react-redux"; import { addEvents, addUserTag, createMoment, eventDetail, updateMoment, userTags } from "@/services/health"; import PostMomentTime from "@/_health/components/post_moment_time"; import ShareBtn from "@/components/basic/ShareBtn"; import { jumpPage } from "@/features/trackTimeDuration/hooks/Common"; import ChooseActions from "@/pages/clock/components/choose_actions"; import FollowInfo from "@/_moment/components/follow_info"; import NewDateTimePicker from "@/_health/base/new_date_time_picker"; import { IconCamera, IconClock } from "@/_record/components/record_icon"; import PickerCard from "@/_record/components/picker_card"; import LogTags from "./log_tags"; let useRoute; let useNavigation; let LinearGradient; if (process.env.TARO_ENV == 'rn') { useRoute = require("@react-navigation/native").useRoute useNavigation = require("@react-navigation/native").useNavigation LinearGradient = require('react-native-linear-gradient').default } let useActionSheet; if (process.env.TARO_ENV == 'rn') { useActionSheet = require('@expo/react-native-action-sheet').useActionSheet } export default function RecordLog(props: { scenario, showPublish: any, contentHeight: number, imgs?: any, only_text?: any, quick?: any, join_id?: any, id?: any, edit?: any, check_in?: any, tags: any, }) { const systemInfo: any = Taro.getWindowInfo ? Taro.getWindowInfo() : Taro.getSystemInfoSync(); const navigationBarHeight = systemInfo.statusBarHeight + 44; const screenHeight = systemInfo.screenHeight const scale = '?x-oss-process=image/format,jpg/resize,w_400' const long = useSelector((state: any) => state.long); const health = useSelector((state: any) => state.health); const record = useSelector((state: any) => state.record); const user = useSelector((state: any) => state.user); const [title, setTitle] = useState('') const [chooseTitle, setChooseTitle] = useState('') const [desc, setDesc] = useState('') const [step, setStep] = useState(0) const { t } = useTranslation() const [time, setTime] = useState(dayjs().format('HH:mm')) const [selDate, setSelDate] = useState(dayjs().format('YYYY-MM-DD')) const [enterTimestmap] = useState(new Date().getTime()) const [posting, setPosting] = useState(false) const [showTimePicker, setShowTimePicker] = useState(false) const [result, setResult] = useState(null) const [showResult, setShowResult] = useState(false) const [tags, setTags] = useState([]) const [selPostCount, setPostCount] = useState(1) const [showChoose, setShowChoose] = useState(false) const [selTag, setSelTag] = useState(null) const [loading, setLoading] = useState(false) let showActionSheetWithOptions; if (process.env.TARO_ENV == 'rn') { showActionSheetWithOptions = useActionSheet() } let router let navigation; if (useNavigation) { navigation = useNavigation() } if (process.env.TARO_ENV == 'rn') { router = useRoute() } else { router = useRouter() } const { scenario, imgs, only_text, quick, join_id } = props const [pics, setPics] = useState(imgs ? JSON.parse(imgs) : []) const [focus, setFocus] = useState(only_text ? true : false) const [inputFocus, setInputFocus] = useState(false) if (process.env.TARO_ENV == 'weapp') { useShareAppMessage((e) => { var path; if (result && result.event_id) { var sharePath = `/_health/pages/timeline_detail?type=recent&fast_type=IF&event_id=${result.event_id}&uid=${user.id}&isfastsleep=${0}&disable_edit=1&enter_type=share` if (user.isLogin) { sharePath += `&share_uid=${user.id}` } path = sharePath } else { path = 'pages/clock/Clock' } return { title: '分享标题', path: path, // imageUrl: shareUrl } }) } useEffect(() => { global.set_time = new Date().getTime() getTags() if (props.check_in == 1) { setStep(0) } // if (router.params.quick) { // quickSave() // } if (props.edit) { eventDetail(props.id).then(res => { setTitle((res as any).title) setChooseTitle((res as any).title) if ((res as any).moment) { setDesc((res as any).moment.description) if ((res as any).moment.media && (res as any).moment.media.length > 0) { setPics((res as any).moment.media) } } if ((res as any).time) { setSelDate(dayjs((res as any).time.start_timestamp).format('YYYY-MM-DD')) setTime(dayjs((res as any).time.start_timestamp).format('HH:mm')) } }) } }, []) useEffect(() => { if (step == 1) { setTimeout(() => { setInputFocus(true) }, 300) } }, [step]) function getTags() { setTags(props.tags) // userTags({ scenario: scenario }).then(res => { // if (chooseTitle == '' && !props.edit) { // var current = dayjs().format('HH:mm'); // var isFind = false; // (res as any).tags.map(item => { // if (item.time_from && item.time_to) { // if (isInTimeRange(current, item.time_from, item.time_to)) { // isFind = true; // setTitle(item.title) // setChooseTitle(item.title) // setPostCount(item.log_count + 1) // } // } // }) // if (!isFind) { // setTitle((res as any).tags[0].title) // setChooseTitle((res as any).tags[0].title) // setPostCount((res as any).tags[0].log_count + 1) // } // } // setTags((res as any).tags) // }) } function isInTimeRange(currentTime, startTime, endTime) { // 将时间字符串转换为 Date 对象 const current = new Date(`1970-01-01T${currentTime}:00`); const start = new Date(`1970-01-01T${startTime}:00`); const end = new Date(`1970-01-01T${endTime}:00`); // 如果结束时间小于开始时间,说明时间段跨越了午夜 if (end < start) { end.setDate(end.getDate() + 1); // 将结束时间加一天 if (current < start) { current.setDate(current.getDate() + 1); // 如果当前时间在午夜之前,加一天 } } // 判断当前时间是否在时间段内 return current >= start && current < end; } function addTag() { addUserTag({ scenario: scenario, title: title }).then(res => { getTags() }) } function tapPic() { //, t('health.delete') var list = process.env.TARO_ENV == 'weapp' ? [t('health.add_photos'), t('health.camera2'), t('health.import_chat')] : [t('health.add_photos'), t('health.camera2')] showActionSheet({ title: '', showActionSheetWithOptions: showActionSheetWithOptions, itemList: list, success: function (res) { switch (res) { case 0: addImage(false) break; case 1: addImage(true) break; case 2: Taro.chooseMessageFile({ count: 9 - pics.length, type: 'image', success: async function (res) { const results = await Promise.all(res.tempFiles.map(getImageInfo)); chooseSuccess(results, true) }, fail(res) { }, }) break; case 3: // setImgUrl('') break; } } }) } function addImage(isCamera) { var source: any = isCamera ? ['camera'] : ['album'] Taro.chooseImage({ count: 9 - pics.length, sizeType: ['compressed'], // mediaType: ['image'], sourceType: source, success: async function (res) { const results = await Promise.all(res.tempFiles.map(getImageInfo)); chooseSuccess(results, true) // checkAuthorized() }, fail: function (res) { } }) } async function chooseSuccess(res, isAlbum) { // const filePaths = res.map(file => file.path // // process.env.TARO_ENV === 'rn' || isFilePath ? file.path : file.tempFilePath // ) Taro.showLoading({ title: t('health.uploading') }) try { const uploadedUrls = await Promise.all(res.map(path => uploadFile2(path, isAlbum ? 'album' : 'camera'))) setPics([...pics, ...uploadedUrls]) Taro.hideLoading() } catch (error) { console.error('Error uploading files:', error) Taro.hideLoading() } } function uploadFile2(obj: any, source: string): Promise { return new Promise((resolve, reject) => { var path = obj.path const dot = path.lastIndexOf('.') const fileExt = dot > 0 ? path.substring(dot) : '' Taro.request({ method: 'GET', timeout: 30000, url: `${baseUrl}/api/thirdparty/aliyun/oss-form-upload`, header: { 'Authorization': 'bearer ' + global.token }, data: { type: 'FOOD_JOURNAL', file_ext: fileExt }, success: (rsp) => { if (rsp.statusCode !== 200) { reject(new Error(t('health.networkError'))) return } Taro.uploadFile({ timeout: 30000, url: rsp.data.upload_url, filePath: path, name: 'file', formData: rsp.data.fields, success: () => { var temp = JSON.parse(JSON.stringify(obj)) temp.url = rsp.data.view_url // resolve(rsp.data.view_url) resolve(temp) }, fail: (error) => { reject(error) } }) }, fail: reject }) }) } const getImageInfo = (src) => { const { tempFilePath, path } = src return new Promise((resolve) => { Taro.getImageInfo({ src: tempFilePath ? tempFilePath : path, success: (result) => resolve({ height: result.height, width: result.width, orientation: result.orientation, path: result.path, type: result.type }), fail: (error) => resolve({ height: 1024, width: 1024, orientation: 'up', path: tempFilePath, type: 'unknown' }), }); }); }; function quickSave() { } function save() { if (props.edit) { edit() return } var date = TimeFormatter.stringToDate(selDate, time) date.setMilliseconds(new Date(enterTimestmap).getMilliseconds()) var params: any = { scenario: scenario, //ACTIVITY type: 'POINT', sub_type: scenario, title: chooseTitle, time: { start_timestamp: date.getTime() } } if (join_id) { params.join_key = join_id } var moment: any = { description: desc, } if (pics.length > 0) { var picList: any = [] pics.map((item) => { picList.push({ url: item.url, type: item.url.indexOf('mp4') != -1 ? 'video' : 'image', source: 'album', width: item.width, height: item.height, format: item.format }) }) moment.media = picList } params.moment = moment // if (event_id && event_id != 'undefined') { // params.event_id = event_id // } // if (is_temp) { // params.event = window == 'EAT' ? 'EAT_CUSTOM' : 'ACTIVE_CUSTOM' // } // params.op_page = window == 'EAT' ? 'HOME_EAT' : 'HOME_ACTIVE' params.extra = { set_time: global.set_time ? global.set_time : new Date().getTime(), confirm_time: new Date().getTime() } if (posting) return setPosting(true) // Taro.showLoading({ // title: t('health.uploading') // }) addEvents(params).then(res => { setShowResult(true) setResult(res) setPosting(false) // Taro.hideLoading() Taro.reLaunch({ url: '/pages/moment/moment' }) }).catch(e => { setPosting(false) // Taro.hideLoading() }) // createMoment(params).then(res => { // // setTimeout(() => { // setPosting(false) // Taro.eventCenter.trigger('refreshMoments', '') // // }, 1000) // if (process.env.TARO_ENV == 'weapp') { // // Taro.navigateBack(); // Taro.redirectTo({ // url: '/_health/pages/post_result?data=' + JSON.stringify(res) // }) // // Taro.navigateTo({ // // url:'/_health/pages/post_result?data=' + JSON.stringify(res) // // }) // } // // global.refreshWindow() // // global.refreshHistory() // // if (global.postMomentSuccess) { // // global.postMomentSuccess() // // } // }).catch(e => { // setPosting(false) // }) } function edit() { var date = TimeFormatter.stringToDate(selDate, time) date.setMilliseconds(new Date(enterTimestmap).getMilliseconds()) var params: any = { id: router.params.id, scenario: scenario, //ACTIVITY type: 'POINT', sub_type: scenario, title: chooseTitle, time: { start_timestamp: date.getTime() } } if (join_id) { params.join_key = join_id } var moment: any = { description: desc, } if (pics.length > 0) { var picList: any = [] pics.map((item) => { picList.push({ url: item.url, type: item.url.indexOf('mp4') != -1 ? 'video' : 'image', source: 'album', width: item.width, height: item.height, format: item.format }) }) moment.media = picList } else { moment.media = [] } params.moment = moment params.extra = { set_time: global.set_time ? global.set_time : new Date().getTime(), confirm_time: new Date().getTime() } if (posting) return setPosting(true) // Taro.showLoading({ // title: t('health.uploading') // }) addEvents(params).then(res => { setShowResult(true) setResult(res) setPosting(false) Taro.eventCenter.trigger('refresh_timeline', (res as any).feed_item) if (global.refreshHistory) { global.refreshHistory() } process.env.TARO_ENV == 'weapp' ? Taro.navigateBack() : navigation.goBack() // Taro.hideLoading() // Taro.reLaunch({ // url: '/pages/moment/moment' // }) }).catch(e => { setPosting(false) // Taro.hideLoading() }) } function getDate() { var sel = dayjs(selDate) var now = dayjs().format('YYYY-MM-DD') const yesterday = dayjs().subtract(1, 'day'); if (sel.format('YYYY-MM-DD') == now) { return '' } if (yesterday.format('YYYY-MM-DD') == sel.format('YYYY-MM-DD')) { return global.language == 'en' ? 'Yesterday ' : '昨天 ' } else { return global.language == 'en' ? sel.format('MMM D ') : sel.format('MMMD日 ') } } function getBackground() { var time = record.time if (!time) return '#fff' const { background_colors } = time if (!background_colors) { return '#fff' } else if (background_colors.length == 1) { return background_colors[0] } return `linear-gradient(to bottom, ${background_colors[0]}, ${background_colors[1]})` } if (quick) { // return { // }} /> } return { step == 0 && { props.showPublish(scenario, item, tags, addTag) } } /> } { step == 1 && { setInputFocus(false) }} onInput={(e: any) => { setTitle(e.target.value) setChooseTitle(e.target.value) }} /> { if (!user.isLogin) { jumpPage('/_account/pages/ChooseAuth', 'ChooseAuth', navigation) return } setStep(0) }} > {t('health.cancel')} { if (title.length == 0) return if (!user.isLogin) { jumpPage('/_account/pages/ChooseAuth', 'ChooseAuth', navigation) return } props.showPublish(props.scenario, { title: title }, tags, false) setStep(0) // setChooseTitle(title) // setPostCount(1) // setStep(2) // addTag() }} > {t('health.confirm')} } { step == 2 && { if (!user.isLogin) { jumpPage('/_account/pages/ChooseAuth', 'ChooseAuth', navigation) return } setStep(0) setFocus(false) }}> {chooseTitle}