import { View, Image, Text, Input, Textarea, Button } from "@tarojs/components";
import { useDispatch, useSelector } from "react-redux";
import './timeline_detail.scss'
import '@features/health/History.scss'
import { useEffect, useState } from "react";
import Taro, { useRouter, useShareAppMessage } from "@tarojs/taro";
import dayjs from "dayjs";
import { getScenario, getThemeColor } from "@/features/health/hooks/health_hooks";
import { baseUrl, SHARE_COVER_URL } from "@/services/http/api";
import { checkAuthorized } from "@/utils/check_authorized";
import { createMoment, delEvents, delRecord, getEvents, getRecordDetail, homeInfo, makeDone, windows } from "@/services/health";
import NewButton, { NewButtonType } from "../base/new_button";
import { IconClose, IconError, IconLongFast, IconShare } from "@/components/basic/Icons";
import { rpxToPx, vibrate } from "@/utils/tools";
import { MainColorType } from "@/context/themes/color";
import NewModal from "../base/new_modal";
import Card from "../components/card";
import ChooseDateTime from "../components/choose_date_time";
import TimeTitleDesc from "../components/time_title_desc";
import CoverList from "../components/cover_list";
import ListFooter from "../components/list_footer";
import showAlert from "@/components/basic/Alert";
import showActionSheet from "@/components/basic/ActionSheet";
import { useTranslation } from "react-i18next";
import { jumpPage } from "@/features/trackTimeDuration/hooks/Common";
import { TimeFormatter } from "@/utils/time_format";
import TargetProgress from "../components/target_progress";
import formatMilliseconds from "@/utils/format_time";
import SingleImage from "../components/single_img";
import { setFastWithSleep, setFirstActiveId, setFirstEatId, setLongFast, setShowActionTip, setWindows } from "@/store/health";
import FastSleepPopupContent from "../components/fast_sleep_popup_content";
import { StatusType } from "../base/status_indicator";
import 'dayjs/locale/zh-cn';
import 'dayjs/locale/en';
import { getInfoSuccess } from "@/store/user";
import LongCard from "@/_moment/components/long_card";
import { setFollow, setJoinData } from "@/store/long";
import MomentDetailShare from "@/pages/moment/moment_detail_share";
import { followUser } from "@/services/friend";
import { setActions, setEvents, setTimeData } from "@/store/record";
import ShareBtn from "@/components/basic/ShareBtn";

let useRoute;
let useNavigation;
if (process.env.TARO_ENV == 'rn') {
    useRoute = require("@react-navigation/native").useRoute
    useNavigation = require("@react-navigation/native").useNavigation
}

export default function TimelineDetail() {
    let showActionSheetWithOptions;
    const [enterTimestmap] = useState(new Date().getTime())
    const health = useSelector((state: any) => state.health);
    const user = useSelector((state: any) => state.user);
    const [list, setList] = useState<any>([])
    const [history, setHistory] = useState<any>([])
    const [detail, setDetail] = useState<any>(null)
    const [desc, setDesc] = useState('')
    const [imgUrl, setImgUrl] = useState('')
    const [btnDisable, setBtnDisable] = useState(true)
    const [showPop, setShowPop] = useState(false)
    const [publish, setPublish] = useState<any>(null)
    const [bottom, setBottom] = useState(20)
    const [loaded, setLoaded] = useState(false)
    const [showTimePicker, setShowTimePicker] = useState(false)
    const [time, setTime] = useState(dayjs().format('HH:mm'))
    const [selTime, setSelTime] = useState(dayjs().format('HH:mm'))
    const [selDate, setSelDate] = useState(dayjs().format('YYYY-MM-DD'))
    const [count, setCount] = useState(0)
    const [fastSleepPop, setFastSleepPop] = useState(false)
    const [shareUser, setShareUser] = useState<any>(null)
    const [join, setJoin] = useState<any>(null)
    const [showEmpty, setShowEmpty] = useState(false)
    const dispatch = useDispatch()

    const { t } = useTranslation()
    let router
    let navigation;
    if (useNavigation) {
        navigation = useNavigation()
    }

    if (process.env.TARO_ENV == 'rn') {
        router = useRoute()
    }
    else {
        router = useRouter()
    }

    const { schedule_id, event_id, window_id, isfastsleep, fast_type, disable_edit, uid, autoPost, op_page } = router.params

    console.log('进入页面获取参数')
    console.log(router.params)

    if (process.env.TARO_ENV == 'weapp') {
        const launchObj = Taro.getLaunchOptionsSync()
        console.log('launchObj', launchObj)

        if (launchObj.shareTicket) {
            Taro.getShareInfo({
                shareTicket: launchObj.shareTicket,
                success(result) {
                    console.log('share info', result)
                },
            })
        }
    }


    if (process.env.TARO_ENV == 'weapp'/* && global.allowShare*/) {
        Taro.updateShareMenu({
            withShareTicket: true,
            success() { }
        })

        useShareAppMessage((e) => {
            console.log(detail)
            var timestamp = detail.events ? detail.events[0].time.timestamp : detail.moments[0].time.timestamp
            console.log(timestamp)
            var shareDate = ''
            if (TimeFormatter.isToday(timestamp)) {
                shareDate = global.language == 'en' ? 'Today\'s' : '今日'
            }
            else if (TimeFormatter.isYesterday(timestamp)) {
                shareDate = global.language == 'en' ? 'Yesterday\'s' : '昨日'
            }
            else if (TimeFormatter.isTimestampInThisWeek(timestamp)) {
                shareDate = global.language == 'en' ? (dayjs(timestamp).format('dddd') + '\'s') : dayjs(timestamp).format('dddd')
            }
            else {
                shareDate = global.language == 'en' ? dayjs(timestamp).format('MMMM D') : dayjs(timestamp).format('MMMD日')
            }

            var title = ''
            var defaultImg = SHARE_COVER_URL + 'my_fast.jpg'
            if (isfastsleep == '1') {
                title = t('health.share_check_in', { date: shareDate, type: t('health.fasting_with_sleep') })
                defaultImg = SHARE_COVER_URL + 'my_fast_with_sleep.jpg'
            }
            else if (fast_type == 'LF') {
                title = t('health.share_check_in', { date: shareDate, type: t('health.long_fast') })
                defaultImg = SHARE_COVER_URL + 'my_long_fast.jpg'
            }
            else {

                if (detail.events && detail.events.length > 0)
                    switch (detail.events[0].window) {
                        case 'FAST':
                            title = t('health.share_check_in', { date: shareDate, type: t('health.fasting') })
                            defaultImg = SHARE_COVER_URL + 'my_fast.jpg'
                            break;
                        case 'EAT':
                            title = t('health.share_check_in', { date: shareDate, type: detail.title })
                            defaultImg = SHARE_COVER_URL + 'my_meal.jpg'
                            break;
                        case 'ACTIVE':
                            title = t('health.share_check_in', { date: shareDate, type: detail.title })
                            defaultImg = SHARE_COVER_URL + 'my_activity.jpg'
                            break;
                        case 'SLEEP':
                            title = t('health.share_check_in', { date: shareDate, type: t('health.sleep') })
                            defaultImg = SHARE_COVER_URL + 'my_sleep.jpg'
                            break;

                    }

                if (detail.window)
                    switch (detail.window) {
                        case 'FAST':
                            title = t('health.share_check_in', { date: shareDate, type: t('health.fasting') })
                            defaultImg = SHARE_COVER_URL + 'my_fast.jpg'
                            break;
                        case 'EAT':
                            title = t('health.share_check_in', { date: shareDate, type: detail.title })
                            defaultImg = SHARE_COVER_URL + 'my_meal.jpg'
                            break;
                        case 'ACTIVE':
                            title = t('health.share_check_in', { date: shareDate, type: detail.title })
                            defaultImg = SHARE_COVER_URL + 'my_activity.jpg'
                            break;
                        case 'SLEEP':
                            title = t('health.share_check_in', { date: shareDate, type: t('health.sleep') })
                            defaultImg = SHARE_COVER_URL + 'my_sleep.jpg'
                            break;

                    }

                // switch (op_page) {
                //     case 'HOME_FAST':
                //         title = t('health.share_my_fasting')
                //         defaultImg = SHARE_COVER_URL + 'my_fast.jpg'
                //         break;
                //     case 'HOME_FAST':
                //         title = t('health.share_my_eating')
                //         defaultImg = SHARE_COVER_URL + 'my_meal.jpg'
                //         break;
                //     case 'HOME_FAST':
                //         title = t('health.share_my_activity')
                //         defaultImg = SHARE_COVER_URL + 'my_activity.jpg'
                //         break;
                //     case 'HOME_FAST':
                //         title = t('health.share_my_sleep')
                //         defaultImg = SHARE_COVER_URL + 'my_sleep.jpg'
                //         break;

                // }
            }
            var imgs = imgList()
            var imageUrl = imgs.length > 0 ? imgs[0] : defaultImg
            if (global.momentdetail_share_url) {
                imageUrl = global.momentdetail_share_url
            }
            var sharePath = `/_health/pages/timeline_detail?type=${router.params.type}&fast_type=${fast_type}&schedule_id=${schedule_id}&window_id=${window_id}&event_id=${event_id}&uid=${uid ?? user.id}&op_page=${op_page}&isfastsleep=${isfastsleep}&disable_edit=1&enter_type=share`
            if (user.isLogin) {
                sharePath += `&share_uid=${user.id}`
            }
            var strWindowId = window_id ?? ''
            if (op_page == 'HOME_EAT' || op_page == 'HOME_ACTIVE') {
                strWindowId = ''
            }
            sharePath += `&window_id=${strWindowId}`
            var nickname = detail.share_user ? detail.share_user.nickname : user.nickname
            if (nickname.length > 10) {
                nickname.substring(0, 10) + '...'
            }
            console.log('share_title', title)
            console.log('sharePath', imageUrl)
            return {
                title: nickname + ': ' + title,
                path: sharePath,
                imageUrl: imageUrl
            }
        })
    }

    useEffect(() => {
        Taro.setNavigationBarColor({
            backgroundColor: showPop ? '#191919' : '#f5f5f5',
            frontColor: '#000000'
        })
        Taro.setBackgroundColor({
            backgroundColor: '#ffffff',
            backgroundColorBottom: '#ffffff'
        })

        // var title = ''
        // if (router.params.timestamp) {
        //     setTimeout(() => {
        //         setTitle(router.params.timestamp)
        //     }, 100)

        // }
        // Taro.setNavigationBarTitle({
        //     title: title
        // })
    }, [showPop])

    useEffect(() => {
        if (router.params.enter_type == 'share') {
            if (global.shareTicket) {
                Taro.getShareInfo({
                    shareTicket: global.shareTicket,
                    success(result) {
                        updateRelation(result)
                    },
                })
            }
            else {
                updateRelation(null)
            }
        }
    }, [user.isLogin])

    function updateRelation(obj) {
        if (!user.isLogin) {
            Taro.setStorageSync('share_uid', router.params.share_uid)
            Taro.setStorageSync('share_info', JSON.stringify(obj))
            return
        }
        if (user.id != router.params.share_uid && router.params.share_uid) {
            var params: any = {
                follow_origin: obj ? 'WECHAT_GROUP_CHAT' : 'WECHAT_PRIVATE_CHAT',
                user_id: router.params.share_uid,
            }
            if (obj) {
                params.wechat = obj
            }
            followUser(params).then(res => {
                // myFriends()
            })
        }
    }

    useEffect(() => {
        if (!user.isLogin) {
            //用户未登录读取cache
            var gps = Taro.getStorageSync('gps')
            if (gps) {
                global.locationDetail = JSON.parse(gps)
            }
            global.memberAlert = Taro.getStorageSync('memberAlert') || false
            var userData = Taro.getStorageSync('userData')
            if (userData) {
                dispatch(getInfoSuccess(JSON.parse(userData)));
            }
        }
    }, [])



    function setTitle(timestamp) {
        dayjs.locale(global.language == 'en' ? 'en' : 'zh-cn');
        require('moment/locale/en-gb')
        require('moment/locale/zh-cn')

        var title = ''
        var t = parseInt(timestamp + '')
        if (TimeFormatter.isToday(t)) {
            title = TimeFormatter.getTodayUnit()
        }
        else if (TimeFormatter.isYesterday(t)) {
            title = TimeFormatter.getYesterdayUnit()
        }
        else {
            console.log(global.language)
            if (global.language && global.language == 'zh') {
                title = dayjs(t).format('MMMD日 dddd')

            }
            else {
                title = dayjs(t).format('dddd, MMM D')
            }
        }
        Taro.setNavigationBarTitle({
            title: title//global.language
        })
    }

    useEffect(() => {
        if (router.params.timestamp) {

            setTitle(router.params.timestamp)

        }

    }, [global.language])

    useEffect(() => {
        Taro.onKeyboardHeightChange(res => {
            setBottom(res.height > 0 ? res.height : 20)
        })

        // getDatas()


        if (!window_id && ((health.mode != 'ACTIVE' && health.mode != 'EAT') || fast_type == 'LF') && autoPost == '1') {
            setShowPop(true)
        }

        Taro.eventCenter.on('refresh_timeline', getDatas)

        return () => {
            Taro.eventCenter.off('refresh_timeline')
        }
    }, [])

    useEffect(() => {
        getDatas()
        if (user.isLogin) {
            windows().then(res => {
                dispatch(setFastWithSleep((res as any).fast_with_sleep))
                dispatch(setWindows((res as any).windows))
                dispatch(setLongFast((res as any).long_fast))
            }).catch(e => {
            })

            homeInfo().then(res => {
                console.log('events', res)
                dispatch(setEvents((res as any).events))
                dispatch(setActions((res as any).actions))

                dispatch(setTimeData(getTime(res)))
            }).catch(e => {
            })
        }
    }, [user.isLogin])

    function getTime(res) {
        var now = dayjs().format('HH:mm')
        for (var i = 0; i < res.time_messages.length; i++) {
            var obj = res.time_messages[i]
            if (now >= obj.start_time && now < obj.end_time) {
                return obj
            }
        }
        return res.time_messages[res.time_messages.length - 1]
    }

    useEffect(() => {
        if (desc.length > 0 || imgUrl.length > 0) {
            setBtnDisable(false)
        }
        else {
            setBtnDisable(true)
        }
    }, [desc, imgUrl])

    global.refreshMoment = () => {
        getDatas()
    }

    function getDatas() {
        var showWindow = true

        if (!window_id || op_page == 'HOME_EAT' || op_page == 'HOME_ACTIVE') showWindow = false
        if (window_id == 'undefined') showWindow = false
        if (showWindow) {
            var params: any = {}
            if (router.params.isfastsleep == '1') {
                params.op_page = 'FAST_WITH_SLEEP'
            }
            if (router.params.uid) {
                params.share_user_id = router.params.uid
            }
            console.log('获取window数据')
            getRecordDetail(window_id, params).then(res => {
                if ((res as any).events && (res as any).events.length > 0 && (res as any).events[0].time)
                    setTitle((res as any).events[0].time.timestamp)
                setLoaded(true)
                setDetail(res)
                setHistory((res as any).events)
                // setList((res as any).moments)
                setPublish((res as any).publish)
                setJoin((res as any).join)
                if ((res as any).share_user) {
                    setShareUser((res as any).share_user)
                    dispatch(setFollow((res as any).share_user))
                }
                console.log('获取window数据成功')
            }).catch(e => {
                console.log('request failed', e)
                setLoaded(true)
                setShowEmpty(true)
            })
        }
        else {
            var params: any = {}
            if (router.params.uid) {
                params.share_user_id = router.params.uid
            }
            console.log('获取event数据')
            getEvents(event_id, params).then(res => {
                if ((res as any).time)
                    setTitle((res as any).time.timestamp)
                setLoaded(true)
                setDetail(res)
                setList((res as any).moments)
                setPublish((res as any).publish)
                setJoin((res as any).join)
                if ((res as any).share_user) {
                    setShareUser((res as any).share_user)
                    dispatch(setFollow((res as any).share_user))
                }
                console.log('获取event数据成功')
            }).catch(e => {
                console.log('request failed', e)
                setLoaded(true)
                setShowEmpty(true)
            })
        }

    }

    function addImage(isCamera: boolean) {
        Taro.chooseMedia({
            count: 1,
            sizeType: ['compressed'],
            mediaType: ['image'],
            sourceType: [isCamera ? 'camera' : 'album'],
            success: function (res) {
                chooseSuccess(res, true)
                // checkAuthorized()
            },
            fail: function (res) {
            }
        })
    }

    async function chooseSuccess(res, isAlbum) {
        var params = {
            event: 'add_a_picture',
            value: isAlbum ? 'choose_from_album_confirm' : 'use_camera_confirm',
        }

        // saveFoodCache('create', params)

        var savedFilePath = process.env.TARO_ENV == 'rn' ? res.tempFiles[0].path : res.tempFiles[0].tempFilePath

        // var savedFilePath = res.savedFilePath
        // await Taro.setStorage({ key: 'pic', data: savedFilePath })
        // setImgUrl(savedFilePath as any)

        uploadFile(savedFilePath, isAlbum ? 'album' : 'camera')


    }

    function uploadFile(path, source) {
        Taro.showLoading({
            title: t('health.loading')
        })
        var dot = path.lastIndexOf('.')
        var fileExt = dot > 0 ? path.substring(dot) : ''
        Taro.request({
            method: 'GET',
            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) {
                    Taro.showToast({
                        title: global.language == 'en' ? 'Posting failed. Please check your network.' : '操作失败，请检查网络',
                        icon: 'none'
                    })
                    return
                }
                Taro.uploadFile({
                    url: rsp.data.upload_url,
                    filePath: path,
                    name: 'file',
                    formData: rsp.data.fields,
                    success: rlt => {
                        setImgUrl(rsp.data.view_url)
                        Taro.hideLoading()
                        // createData(rsp.data.view_url, source)

                        // uploadAvatar(rsp.data.view_url)
                        // _this.changeAvatar(rsp.data.view_url);
                    },
                    fail: rlt => {
                        Taro.hideLoading()
                        Taro.showModal({
                            content: rlt.errMsg
                        })
                    }
                })
            }
        })
    }

    function tapPost() {
        if (desc.length == 0 && imgUrl.length == 0) {
            Taro.showToast({
                icon: 'none',
                title: '请输入描述或添加图片'
            })
            return
        }
        // var dt = new Date(selDate + 'T' + time + ':' + dayjs(enterTimestmap).format('ss'))
        var dt = TimeFormatter.stringToDate(selDate, time)
        dt.setSeconds(parseInt(dayjs(enterTimestmap).format('ss')))
        dt.setMilliseconds(new Date(enterTimestmap).getMilliseconds())
        var params: any = {
            schedule_id: schedule_id,
            description: desc,
            start: {
                date: dayjs(dt.getTime()).format('YYYYMMDD'),
                timestamp: dt.getTime()
            },

            // real_end_time: meal.target_end_time,
        }


        if (imgUrl.length > 0) {
            params.media = [{
                url: imgUrl,
                type: imgUrl.indexOf('mp4') != -1 ? 'video' : 'image',
                source: 'album'
            }]
        }

        params.event_id = event_id
        createMoment(params).then(res => {
            getDatas()
            setImgUrl('')
            setDesc('')
            if (global.refreshWindow) {
                global.refreshWindow()
            }
            if (global.refreshHistory)
                global.refreshHistory()
            setShowPop(false)
        })

    }

    function mediaCount() {
        // let count = 0;
        // list && list.map(moment => {
        //     moment.media.map((obj) => {
        //         count++
        //     })
        // })
        // return count;
        return imgList().length;
    }

    function imgList() {
        var array: any = []
        list && list.map(moment => {
            moment.media.map((obj) => {
                array.push(obj.url)
            })
        })

        history && history.map(item => {
            item.moments && item.moments.map(moment => {
                moment.media && moment.media.map((obj) => {
                    array.push(obj.url)
                })
            })
        })
        return array;
    }

    function edit() {
        if (list.length == 0) return
        var id = list[0].id
        // global.edit_timeline = detail
        // jumpPage(`./add_moment?edit=1&event_id=${event_id}&id=${id}`)
        jumpPage(`/_record/pages/log_record?edit=1&id=${detail.id}&scenario=${detail.scenario}`)
    }

    function del() {
        showAlert({
            title: t('health.del_title'),
            content: '',
            cancelText: t('health.del_cancel'),
            confirmText: t('health.del_confirm'),
            showCancel: true,
            confirm: () => {
                delEvents(event_id).then(res => {
                    Taro.eventCenter.trigger('refreshMoments', '')
                    Taro.navigateBack()
                    if (global.refreshWindow) {
                        global.refreshWindow()
                    }
                    if (global.refreshHistory)
                        global.refreshHistory()
                    if (global.refreshOtherHistory)
                        global.refreshOtherHistory()
                    if ((res as any).status_change) {
                        if ((res as any).status_change.previous != (res as any).status_change.current) {
                            //灵动岛弹窗
                            setTimeout(() => {
                                dispatch(setShowActionTip({
                                    isShow: true,
                                    isCompleted: false
                                }))
                            }, 1000)

                        }
                    }
                    // global.refreshHistory()
                })
            }
        })
    }

    function delHistory() {
        var ids: any = [window_id]
        if (isfastsleep == '1') {
            ids = [detail.windows[0].id, detail.windows[1].id]
        }
        showAlert({
            title: t('health.del_title'),
            content: '',
            cancelText: t('health.del_cancel'),
            confirmText: t('health.del_confirm'),
            showCancel: true,
            confirm: () => {
                delRecord({ ids: ids }).then(res => {
                    if (global.refreshWindow) {
                        global.refreshWindow()
                    }
                    if (global.refreshHistory)
                        global.refreshHistory()
                    if (global.refreshOtherHistory)
                        global.refreshOtherHistory()
                    Taro.navigateBack()

                })
            }
        })
    }

    function tapMarkdone() {
        makeDone(window_id).then(res => {
            Taro.showToast({
                title: '操作成功',
                icon: 'none'
            })
            getDatas()
            global.refreshHistory()
            if (global.refreshArchiveHistory) {
                global.refreshArchiveHistory()
            }
        })
    }

    function tapMore() {
        var list: any = []
        if (window_id && window_id != 'undefined' && (op_page != 'HOME_EAT' && op_page != 'HOME_ACTIVE')) {
            if (detail.archived) {
                list = [t('health.delete'), 'Mark Done']
            }
            else {
                list = [t('health.delete')]
            }
            showActionSheet({
                showActionSheetWithOptions: showActionSheetWithOptions,
                title: t('health.more_actions'),
                itemList: list,
                success: (res) => {
                    if (res == 0) {
                        dispatch(setFirstEatId(''))
                        dispatch(setFirstActiveId(''))
                        if (event_id) {
                            del()
                        }
                        else {
                            delHistory()
                        }

                    }
                    else if (res == 1) {
                        tapMarkdone()
                    }
                }
            })
            return
        }
        if (detail.window != 'ACTIVE' && detail.window != 'EAT') {
            list = [t('health.delete')]
        }
        else {
            list = [t('health.edit'), t('health.delete')]
        }
        showActionSheet({
            showActionSheetWithOptions: showActionSheetWithOptions,
            title: t('health.more_actions'),
            itemList: list,
            success: (res) => {
                if (res >= 0) {
                    if (list[res] == t('health.delete')) {
                        dispatch(setFirstEatId(''))
                        dispatch(setFirstActiveId(''))
                        del()
                    }
                    else if (list[res] == t('health.edit')) {
                        edit()
                    }
                }
            }
        })

    }

    function dayTag(obj) {
        var begin = history[0].time.timestamp
        var end = obj.time.timestamp
        return TimeFormatter.dayTagText(begin, end)
    }

    function showFastSleepPopDetail() {
        setFastSleepPop(true)
    }

    if (!loaded) return <View />


    function fastSleepPopContent() {

        function stepContent(str, index) {
            return <View className="bold h30" style={{ color: index == 1 ? MainColorType.sleep : MainColorType.fast }}>{str}</View>
        }
        if (fastSleepPop) {
            var fast = detail.windows[0]
            var sleep = detail.windows[1]
            return <FastSleepPopupContent
                close={() => { setFastSleepPop(false) }}
                beforeStatus={StatusType.normal}
                sleepStatus={StatusType.normal}
                afterStatus={StatusType.normal}
                title={t('health.my_fast_journal')}
                isFixed
                showStep={true}
                total={''}
                // total1={total1()}
                // total2={total2()}
                // total3={total3()}
                step1={stepContent(TimeFormatter.calculateTimeDifference(fast.window_range.start_timestamp, sleep.window_range.start_timestamp, false, true), 0)}
                step2={stepContent(TimeFormatter.calculateTimeDifference(sleep.window_range.start_timestamp, sleep.window_range.end_timestamp, false, true), 1)}
                step3={stepContent(TimeFormatter.calculateTimeDifference(sleep.window_range.end_timestamp, fast.window_range.end_timestamp, false, true), 2)}
            />
        }
        return null
    }


    function footerTime(publish) {
        if (publish.edited) {
            //dayjs(publish.timestamp).format('M月D日 HH:mm')
            return t('health.log_updated', {
                date_time: global.language == 'en' ?
                    dayjs(publish.timestamp).format('MMM D HH:mm') :
                    dayjs(publish.timestamp).format('M月D日 HH:mm')
            })
        }
        else {
            return t('health.log_created', {
                date_time: global.language == 'en' ?
                    dayjs(publish.timestamp).format('MMM D HH:mm') :
                    dayjs(publish.timestamp).format('M月D日 HH:mm')
            })
        }
    }

    function backHome() {
        Taro.reLaunch({
            url: '/pages/moment/moment'
        })
        // Taro.reLaunch({
        //     url: '/pages/clock/Clock'
        // })
    }

    function postBtnColor() {
        if (detail.window)
            return getThemeColor(detail.window)
        if (detail.events) {
            return getThemeColor(detail.events[0].window)
        }
    }

    function goHome() {
        if (!user.isLogin) {
            jumpPage('/_account/pages/ChooseAuth')
            return
        }
        if (router.params.source == 'home') {
            Taro.navigateBack()
            return
        }
        jumpPage('/_moment/pages/home?uid=' + (shareUser ? shareUser.id : detail.share_user ? detail.share_user.id : user.id))
    }

    function moreBtn() {
        if (!detail.share_user || user.id == detail.share_user.id) {
            return <NewButton
                type={NewButtonType.more}
                onClick={tapMore}
            />
        }
    }

    function addNoteBtn() {
        if (!detail) return null
        if (!uid && (detail && detail.share_user && user.id != detail.share_user.id)) {
            return null
        }
        if (detail.windows && detail.windows[0].status != 'DONE' && ((health.mode != 'ACTIVE' && health.mode != 'EAT') || fast_type == 'LF'))

            return <View className="add_note"><NewButton type={NewButtonType.link} title={t('health.add_note')} onClick={() => {
                setShowPop(true)

            }} /></View>

    }

    return <View style={{ display: 'flex', flex: 1, flexDirection: 'column', backgroundColor: '#fff', minHeight: '101vh' }}>
        {/* <View>测试图片原图</View>
        <Image src="https://fast-prod.oss-cn-beijing.aliyuncs.com/users/6b3dd3ee205561e227e9e3a6dd30a8d4/food-journal/2024/e5631780-a045-4384-8837-3f34a91f37e1_20241227144547_701.jpg"
            style={{width:100,height:100}}
        />
        <View>测试图片压缩</View>
        <Image src="https://fast-prod.oss-cn-beijing.aliyuncs.com/users/6b3dd3ee205561e227e9e3a6dd30a8d4/food-journal/2024/e5631780-a045-4384-8837-3f34a91f37e1_20241227144547_701.jpg?x-oss-process=image/resize,w_400"
            style={{width:100,height:100}}
        />
        <View>测试图片webp</View>
        <Image src="https://fast-prod.oss-cn-beijing.aliyuncs.com/users/6b3dd3ee205561e227e9e3a6dd30a8d4/food-journal/2024/e5631780-a045-4384-8837-3f34a91f37e1_20241227144547_701.jpg?x-oss-process=image/format,webp"
            style={{width:100,height:100}}
        />
        <View>测试图片png</View>
        <Image src="https://fast-prod.oss-cn-beijing.aliyuncs.com/users/6b3dd3ee205561e227e9e3a6dd30a8d4/food-journal/2024/e5631780-a045-4384-8837-3f34a91f37e1_20241227144547_701.jpg?x-oss-process=image/format,png"
            style={{width:100,height:100}}
        />
        <View>测试图片jpg</View>
        <Image src="https://fast-prod.oss-cn-beijing.aliyuncs.com/users/6b3dd3ee205561e227e9e3a6dd30a8d4/food-journal/2024/e5631780-a045-4384-8837-3f34a91f37e1_20241227144547_701.jpg?x-oss-process=image/format,jpg"
            style={{width:100,height:100}}
        />
        <View>测试图片jpg+压缩</View>
        <Image src="https://fast-prod.oss-cn-beijing.aliyuncs.com/users/6b3dd3ee205561e227e9e3a6dd30a8d4/food-journal/2024/e5631780-a045-4384-8837-3f34a91f37e1_20241227144547_701.jpg?x-oss-process=image/format,jpg/resize,w_400"
            style={{width:100,height:100}}
        /> */}
        {
            !showEmpty && <View className="detail_header">
                <Image className="detail_header_header"
                    onClick={goHome}
                    src={shareUser ? shareUser.avatar : detail.share_user ? detail.share_user.avatar : user.avatar}
                    mode="aspectFill"
                />
                <View className="detail_header_content">
                    <Text className="detail_nickname" onClick={goHome}>{shareUser ? shareUser.nickname : detail.share_user ? detail.share_user.nickname : user.nickname}</Text>
                    {
                        (!window_id || window_id == 'undefined') && (detail.scenario != 'MEAL' && detail.scenario != 'ACTIVITY') &&
                        <TimeTitleDesc
                            timeObj={detail.time}
                            time={dayjs(detail.time.timestamp).format('HH:mm')}
                            title={detail.title}
                        />
                    }
                    {
                        !window_id && detail.scenario == 'ACTIVITY' && !list &&
                        <TimeTitleDesc
                            timeObj={detail.time}
                            time={dayjs(detail.time.timestamp).format('HH:mm')}
                            title={detail.title}
                        />
                    }
                    {
                        list && list.map((item, index) => {
                            return <View key={index} style={{ flexDirection: 'column', display: 'flex' }}>
                                {
                                    (item.title || item.description) && <TimeTitleDesc
                                        showPoint={detail.show}
                                        timeObj={detail.time}
                                        time={dayjs(item.time.timestamp).format('HH:mm')}
                                        title={item.title}
                                        desc={item.description}
                                    />
                                }

                            </View>
                        })
                    }
                    {
                        history && history.map((item, index) => {
                            return <View key={index} style={{ flexDirection: 'column', display: 'flex' }}>
                                {
                                    item.show && <TimeTitleDesc
                                        timeObj={item.time}
                                        time={dayjs(item.time.timestamp).format('HH:mm')}
                                        title={item.title}
                                        dayTag={dayTag(item)}
                                        desc=''
                                    />
                                }
                                {
                                    item.moments && item.moments.map((moment, j) => {
                                        return (moment.title || moment.description) && <View key={j * 10} style={{ flexDirection: 'column', display: 'flex' }}>
                                            <TimeTitleDesc
                                                showPoint={item.show}
                                                timeObj={moment.time}
                                                time={dayjs(moment.time.timestamp).format('HH:mm')}
                                                title={moment.title}
                                                dayTag={dayTag(moment)}
                                                desc={moment.description}
                                            />
                                        </View>
                                    })
                                }

                                {/* {
                                item.moments && item.moments.map((moment, j) => {
                                    return <View key={j * 10} style={{ flexDirection: 'column', display: 'flex' }}>
                                        <TimeTitleDesc
                                            timeObj={moment.time}
                                            time={dayjs(item.time.timestamp).format('HH:mm')}
                                            title={moment.title ? moment.title : item.title}
                                            dayTag={dayTag(item)}
                                            desc={moment.description}
                                        />
                                    </View>
                                })
                            }
                            {
                                !item.moments && <TimeTitleDesc
                                    timeObj={item.time}
                                    time={dayjs(item.time.timestamp).format('HH:mm')}
                                    title={item.title}
                                    dayTag={dayTag(item)}
                                    desc=''
                                />
                            } */}
                            </View>
                        })
                    }
                    {/* {
                    <View className="media" style={{ marginRight: mediaCount() == 4 ? 80 : 0, marginTop: rpxToPx(24) }}>
                        {
                            list && list.map(moment => {
                                return moment.media.map((obj, j) => {
                                    return <Image className="media_item" mode="aspectFill" onClick={() => { }} src={obj.url} key={j * 10} />
                                })
                            })

                        }

                    </View>
                } */}
                    {
                        mediaCount() > 1 && <View style={{ marginTop: rpxToPx(17), display: 'flex', flexShrink: 0 }}>
                            <CoverList imgs={imgList()} count={mediaCount()} />
                        </View>
                    }
                    {
                        mediaCount() == 1 && <View style={{ marginTop: rpxToPx(17), display: 'flex', flexShrink: 0 }}>
                            <SingleImage url={imgList()[0]} />
                        </View>
                    }
                    <View style={{ height: rpxToPx(17), flexShrink: 0, display: 'flex' }} />

                    {
                        isfastsleep != '1' && history && detail.windows && detail.windows[0].status == 'DONE' && detail.windows.map((item, index) => {
                            return <TargetProgress key={index} showLine={index < detail.windows.length - 1}
                                onClick={() => {
                                    vibrate()
                                }}
                                color={getThemeColor(item.window)}
                                showRing={detail.fast_type == 'LF' ? false : true}
                                desc={item.description}
                                time_desc={item.time_desc}
                                icon={
                                    detail.fast_type == 'LF' ? <IconLongFast color={MainColorType.fast} width={rpxToPx(32)} /> : null
                                }
                                canvasId={`${item.window}${item.window_range.start_timestamp}${index}aa`}
                                startTimestamp={item.window_range.start_timestamp}
                                endTimerstamp={item.window_range.end_timestamp}
                            />
                        })
                    }
                    {
                        isfastsleep == '1' && history && detail.windows && detail.windows.length >= 2 && detail.windows[0].status == 'DONE' && <TargetProgress
                            onClick={showFastSleepPopDetail}
                            showRing={true}
                            doubleRing={true}
                            first={detail.windows[0]}
                            second={detail.windows[1]}
                            canvasId={`double_${detail.windows[0].window_range.start_timestamp}`}
                        />
                    }
                    {
                        join && <LongCard join={join} title={detail.title} />
                    }

                    {
                        publish && <View style={{ display: 'flex', flexDirection: 'row', height: rpxToPx(60), marginTop: rpxToPx(17), alignItems: 'center' }}>
                            {/* <Text className="h24 g02">{publish.edited ? '编辑于' : '发布于'}{dayjs(publish.timestamp).format('M月D日 HH:mm')}</Text> */}
                            <Text className="h24 g02">{footerTime(publish)}</Text>
                            <View style={{ flex: 1 }} />
                            {
                                join && join.status == 'JOIN' && <NewButton type={NewButtonType.custom} onClick={() => {
                                    if (!user.isLogin) {
                                        jumpPage('/_account/pages/ChooseAuth')
                                        return
                                    }
                                    dispatch(setFollow(shareUser ? shareUser : detail.share_user ? detail.share_user : user))
                                    dispatch(setJoinData(join))
                                    if (join.window == 'ACTIVE' || join.window == 'EAT') {
                                        jumpPage(`/_record/pages/log_record?scenario=${join.window == 'EAT' ? 'MEAL' : 'ACTIVITY'}&join_id=${join.key}`)
                                    }
                                    else if (join.window == 'FAST' || join.window == 'SLEEP') {
                                        jumpPage(`/_record/pages/time_record?scenario=${join.window}&join_id=${join.key}`)
                                    }

                                    // jumpPage(`/_moment/pages/long_detail?join_id=${join.key}&window=${join.window}&status=${join.status}`)
                                }}>
                                    <View className="h24" style={{ color: MainColorType.link, padding: rpxToPx(13) }}>跟卡</View>
                                </NewButton>
                            }
                            {/* <View className="share_btn_bg">

                                <View className="share_icon_bg" style={{ paddingLeft: rpxToPx(20), paddingRight: rpxToPx(20) }}>
                                    <IconShare color={MainColorType.link + 'cc'} width={rpxToPx(32)} />
                                </View>
                                <Button className="share_btn" openType="share">1</Button>
                            </View> */}
                            <ShareBtn>
                                <View className="share_icon_bg" >
                                    <IconShare color={MainColorType.link + 'cc'} width={rpxToPx(32)} />
                                </View>
                            </ShareBtn>


                            {
                                moreBtn()
                            }


                        </View>
                    }
                </View>
            </View>
        }
        {
            showEmpty && <View className="no_data_bg2" style={{ marginTop: rpxToPx(256) }}>
                <View style={{
                    backgroundColor: MainColorType.g04,
                    width: rpxToPx(108),
                    height: rpxToPx(108),
                    borderRadius: rpxToPx(54),
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'center'
                }}>
                    <IconError width={rpxToPx(88)} color="#fff" />
                </View>
                <Text className="h50 g01 bold" style={{ marginBottom: rpxToPx(92), marginTop: rpxToPx(24) }}>{t('health.no_content')}</Text>
            </View>
        }

        <Text style={{ opacity: 0 }}>{count}</Text>
        <ListFooter />
        {
            uid && <View style={{ height: 100 }} />
        }
        {/* {
            !uid && detail.windows && detail.windows[0].status != 'DONE' && ((health.mode != 'ACTIVE' && health.mode != 'EAT') || fast_type == 'LF') && <View className="add_note"><NewButton type={NewButtonType.link} title={t('health.add_note')} onClick={() => {
                setShowPop(true)

            }} /></View>
        } */}

        {
            addNoteBtn()
        }
        {
            uid && <View className="main_footer" style={{ backgroundColor: '#fff' }}>
                <NewButton
                    type={NewButtonType.fill}
                    color={MainColorType.success}
                    title={t('health.back_moment')}
                    width={rpxToPx(646)}
                    height={rpxToPx(96)}
                    onClick={backHome}
                />
            </View>
        }


        {
            showPop && <View className="publish_bg">
                <NewButton type={NewButtonType.img}
                    btnStyle={{
                        position: 'absolute', left: rpxToPx(52),
                        top: 0,
                        color: '#fff',
                        width: 32,
                        height: 32
                    }}
                    onClick={() => {
                        setShowPop(false)
                    }}>
                    <IconClose color="#fff" width={20} height={20} />
                </NewButton>
                <View onClick={() => setShowTimePicker(true)} style={{ height: rpxToPx(88), marginTop: rpxToPx(120), width: rpxToPx(80), color: MainColorType.link }}>{time}
                </View>
                <Textarea className="myTextarea" placeholder={t('health.how_feeling')} style={{ flex: 1, color: '#fff', caretColor: getThemeColor(detail.window) }} focus value={desc} onInput={(e) => {
                    setDesc(e.detail.value)
                }} />
                <View className="toolbar2">
                    {
                        imgUrl.length > 0 && <NewButton type={NewButtonType.img} onClick={() => addImage(false)}>
                            <Image src={imgUrl} mode="aspectFill" className="album" />
                        </NewButton>
                    }
                    {
                        imgUrl.length == 0 && <NewButton type={NewButtonType.img} onClick={() => addImage(false)}>
                            <Image src={require('@assets/_health/album.png')} className="album"
                            />
                        </NewButton>
                    }
                    {
                        imgUrl.length == 0 && <NewButton type={NewButtonType.img} onClick={() => addImage(true)}>
                            <Image src={require('@assets/_health/camera.png')} className="album"
                            /></NewButton>
                    }


                    <View style={{ flex: 1 }} />
                    <View className="btn" style={{ backgroundColor: btnDisable ? '#b2b2b2' : postBtnColor() }} onClick={tapPost}>{t('health.post')}</View>
                </View>

                <View style={{ height: bottom, flexShrink: 0 }} />
            </View>
        }
        {
            showTimePicker && <NewModal
                title={t('health.note_time')}
                dismiss={() => setShowTimePicker(false)}
                confirm={() => {
                    var str = dayjs().format('HH:mm')
                    var date = new Date(selDate + ' ' + selTime + ':00')
                    var now = new Date()
                    if (date.getTime() > now.getTime()) {
                        setTime(str)
                        setCount(count => count + 1)
                        Taro.showToast({
                            title: t('health.future_time_limit'),
                            icon: 'none'
                        })
                        return
                    }
                    // props.onChange({
                    //     date: selDate,
                    //     time: time,
                    //     duration: minutes,
                    //     isYesterday: isYesterday
                    // })
                    setTime(selTime)
                    setShowTimePicker(false)
                }}
                themeColor={getThemeColor(detail.window)}>
                <Card>
                    <ChooseDateTime title={null}
                        disable={false}
                        color={getThemeColor(detail.window)}
                        expand={true}
                        time={time}
                        hideFooter={true}
                        // timeChange={(e) => {
                        //     setSelTime(e)
                        // }}
                        minTimestamp={new Date().getTime()}
                        date={selDate}
                        change={e => {
                            setSelDate(e[0])
                            setSelTime(e[1])
                        }}
                    // dateChange={(e) => {
                    //     setSelDate(e)
                    // }}
                    />
                </Card>
            </NewModal>
        }
        {
            fastSleepPopContent()
        }
        <MomentDetailShare
            cover={mediaCount() > 0 ? imgList()[0] : null}
            user={shareUser ? shareUser : detail.share_user}
            btnColor={getThemeColor(detail.join ? detail.join.window : detail.window)} />

    </View>
}