import { View, Text, Image } from "@tarojs/components";
import './log_time.scss'
import './fast_sleep.scss'
import { useSelector } from "react-redux";
import { useEffect, useRef, useState } from "react";
import NewButton, { NewButtonType } from "../base/new_button";
import { rpxToPx } from "@/utils/tools";
import { getScenario, getThemeColor } from "@/features/health/hooks/health_hooks";
import NewTimePicker from "../base/new_timepicker";
import { IconCalendar, IconError } from "@/components/basic/Icons";
import dayjs from "dayjs";
import { useRouter } from "@tarojs/taro";
import Card from "../components/card";
import { MainColorType } from "@/context/themes/color";
import Taro from "@tarojs/taro";
import { clockTimes, fastWithSleep } from "@/services/health";
import NewDurationPicker, { DurationPickerType } from "../base/new_durationpicker";
import showAlert from "@/components/basic/Alert";
import NewDatePicker, { NewDatePickerType } from "../base/new_date_picker";
import ChooseDateTime from "../components/choose_date_time";
import { TimeFormatter } from "@/utils/time_format";
import StatusIndicator, { StatusType } from "../base/status_indicator";
import { t } from "i18next";

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

export default function LogTime() {
    let router
    let navigation;
    if (useNavigation) {
        navigation = useNavigation()
    }

    if (process.env.TARO_ENV == 'rn') {
        router = useRoute()
    }
    else {
        router = useRouter()
    }
    const [enterTime] = useState(new Date().getTime())
    const [requestId, setRequestId] = useState(new Date().getTime())

    const isSingle = router.params.single == '1'
    const isFast = router.params.window == 'FAST'
    const isStart = router.params.is_start == '1'
    const isFastWithSleep = router.params.is_fast_with_sleep == '1'
    const type = router.params.type
    const [data, setData] = useState<any>(null)
    const health = useSelector((state: any) => state.health);
    const [showGoal, setShowGoal] = useState(router.params.longfast)
    const tapIndex = router.params.index ?? 0
    const [longDuration, setLongDuration] = useState(24)

    const [expandIndex, setExpandIndex] = useState(router.params.initIndex ? router.params.initIndex : tapIndex)
    const [chooseDate, setChooseDate] = useState(false)
    const [array, setArray] = useState<any>([])
    const [errors, setErrors] = useState<any>([])
    const [showSuccess, setShowSuccess] = useState(false)
    const [conflicts, setConflicts] = useState<any>([])
    const [loaded, setLoaded] = useState(false)
    const [autoCheck, setAutoCheck] = useState(false)
    const [initCheck, setInitCheck] = useState(router.params.initCheck == '1')
    const [initSeconds,setInitSeconds] = useState(router.params.initCheck == '1') //初始化时，带入打卡时的秒数
    const [count, setCount] = useState(0)

    const [ignoreCheck, setIgnoreCheck] = useState(false)
    const [posting, setPosting] = useState(false)



    useEffect(() => {
        loadData()

        var now = new Date()
        var t = now.getTime()
        now.setHours(0)
        now.setMilliseconds(0)
        now.setSeconds(0)
        now.setMinutes(0)
        var t2 = now.getTime()
        t2 += 24 * 3600 * 1000
        var left = t2 - t + 500

        setTimeout(() => {
            setCount(count => count + 1)
            setArray(array => {
                array.map((item) => {
                    item.today = false
                })
                return array;
            })
        }, left)

        if (process.env.TARO_ENV == 'rn') {
            AppState.addEventListener('change', handleAppStateChange);
        }
        Taro.onAppShow(() => {
            setCount(count => count + 1)
        })

    }, [])

    const handleAppStateChange = (nextAppState) => {
        if (nextAppState != 'active') {
            return
        }
        if (nextAppState == 'active') {
            setCount(count => count + 1)
        }

    };

    useEffect(() => {
        if (autoCheck) {
            if (ignoreCheck) {
                setIgnoreCheck(false)
            }
            else {
                tapCommit(true)
            }

        }
        if (initCheck && array.length > 0) {
            tapCommit(true, true)
            setInitCheck(false)
        }
    }, [array])

    function loadData() {
        fastWithSleep().then(res => {
            setData(res)
            initDatas(res)
        })

    }

    function getLongDuration() {
        var day = Math.floor(longDuration / 24)
        var hour = longDuration % 24
        var str = ''
        if (day > 0)
            str = day + '天'
        if (hour > 0)
            str += hour + '小时'
        return str
    }

    function initDatas(res = data) {
        const { fast, sleep, status } = res

        var list: any = []
        if (isSingle) {
            var timeline: any;
            var time = dayjs().format('HH:mm')
            var date = dayjs().format('YYYY-MM-DD')

            if (isFast) {
                timeline = isStart ? fast.timeline[0] : fast.timeline[1]
                Taro.setNavigationBarTitle({
                    title: isStart ? fast.timeline[0].title : fast.timeline[1].title
                });

                //特殊处理单场景下，结束，超过24小时，picker设置为target_end_time
                if (!isStart && new Date().getTime() - fast.timeline[0].target.timestamp >= 24 * 3600 * 1000) {
                    time = dayjs(fast.timeline[1].target.timestamp).format('HH:mm')
                    date = dayjs(fast.timeline[1].target.timestamp).format('YYYY-MM-DD')
                }
            }
            else {
                timeline = isStart ? sleep.timeline[0] : sleep.timeline[1]
                Taro.setNavigationBarTitle({
                    title: isStart ? sleep.timeline[0].title : sleep.timeline[1].title
                });

                //特殊处理单场景下，结束，超过24小时，picker设置为target_end_time
                if (!isStart && new Date().getTime() - sleep.timeline[0].target.timestamp >= 24 * 3600 * 1000) {
                    time = dayjs(sleep.timeline[1].target.timestamp).format('HH:mm')
                    date = dayjs(sleep.timeline[1].target.timestamp).format('YYYY-MM-DD')
                }
            }
            if (router.params.longfast) {
                Taro.setNavigationBarTitle({
                    title: t('health.long_fast')
                })
            }




            list.push({
                event_id: timeline.event_id,
                schedule_id: timeline.schedule_id,
                time: time,
                date: date,
                extra: {
                    set_time: enterTime,
                    confirm_time: enterTime
                }
            })
            setExpandIndex(0)
        }
        else {
            for (var i = 0; i <= tapIndex; i++) {
                // if (type == 'home'){
                //     if (tapIndex == 2){
                //         if (i == 0 || i==3){
                //             continue;
                //         }
                //     }
                //     else if (tapIndex ==3){
                //         if (i==1||i==2){
                //             continue;
                //         }
                //     }
                // }
                var timeline: any;
                if (i == 0 || i == 3) {
                    timeline = i == 0 ? fast.timeline[0] : fast.timeline[1]
                    Taro.setNavigationBarTitle({
                        title: i == 0 ? fast.timeline[0].title : fast.timeline[1].title
                    });
                }
                else {
                    timeline = i == 1 ? sleep.timeline[0] : sleep.timeline[1]
                    Taro.setNavigationBarTitle({
                        title: i == 1 ? sleep.timeline[0].title : sleep.timeline[1].title
                    });
                }
                list.push({
                    event_id: timeline.event_id,
                    schedule_id: timeline.schedule_id,
                    time: dayjs().format('HH:mm'),
                    date: dayjs().format('YYYY-MM-DD'),
                    extra: {
                        set_time: enterTime,
                        confirm_time: enterTime
                    }
                })
            }

            //逆推初始化时间
            var fastStartTime = new Date().getTime()
            var fastEndTime = new Date().getTime()
            var sleepStartTime = new Date().getTime()
            var sleepEndTime = new Date().getTime()

            fastStartTime = fastEndTime - fast.target.duration

            var fastEndtoWakeDuration = 0
            var time1 = fast.period.end_time
            var time2 = sleep.period.end_time

            var t1 = parseInt(time1.split(':')[0]) * 60 + parseInt(time1.split(':')[1])
            var t2 = parseInt(time2.split(':')[0]) * 60 + parseInt(time2.split(':')[1])
            fastEndtoWakeDuration = t1 - t2 > 0 ? (t1 - t2) * 60 * 1000 : (t1 - t2) * 60 * 1000 + 24 * 3600 * 1000

            sleepEndTime = fastEndTime - fastEndtoWakeDuration//(fast.target.end_timestamp-sleep.target.end_timestamp)
            sleepStartTime = sleepEndTime - sleep.target.duration

            var isConflict = false;
            if (fast.real && fast.real.start_timestamp && fast.real.start_timestamp > fastStartTime) {
                isConflict = true;
            }
            else if (sleep.real && sleep.real.start_timestamp && sleep.real.start_timestamp > sleepStartTime) {
                isConflict = true;
            }
            else if (sleep.real && sleep.real.end_timestamp && sleep.real.end_timestamp > sleepEndTime) {
                isConflict = true;
            }

            if (!isConflict) {
                list[0].date = dayjs(fastStartTime).format('YYYY-MM-DD')
                list[0].time = dayjs(fastStartTime).format('HH:mm')

                list[1].date = dayjs(sleepStartTime).format('YYYY-MM-DD')
                list[1].time = dayjs(sleepStartTime).format('HH:mm')

                if (list.length > 2) {
                    list[2].date = dayjs(sleepEndTime).format('YYYY-MM-DD')
                    list[2].time = dayjs(sleepEndTime).format('HH:mm')

                }

            }

            if (fast.real && fast.real.start_timestamp) {
                list[0].date = dayjs(fast.real.start_timestamp).format('YYYY-MM-DD')
                list[0].disable = true
                list[0].time = dayjs(fast.real.start_timestamp).format('HH:mm')
            }

            if (sleep.real && sleep.real.start_timestamp) {
                list[1].date = dayjs(sleep.real.start_timestamp).format('YYYY-MM-DD')
                list[1].disable = true
                list[1].time = dayjs(sleep.real.start_timestamp).format('HH:mm')
            }

            if (list.length > 2 && sleep.real && sleep.real.end_timestamp) {
                list[2].date = dayjs(sleep.real.end_timestamp).format('YYYY-MM-DD')
                list[2].disable = true
                list[2].time = dayjs(sleep.real.end_timestamp).format('HH:mm')
            }
        }

        if (status == 'OG2_NO1' && isFastWithSleep) {
            list[0].time = ''
            list[0].date = ''
        }
        setArray(list)

        setLoaded(true)
    }

    function footerBtnColor() {
        if (isSingle) {
            return isFast ? MainColorType.fast : MainColorType.sleep
        }
        else {
            if (tapIndex == '1' || tapIndex == '2') return MainColorType.sleep
        }
        return MainColorType.fast
    }

    function getTimestamp(obj) {
        const {event_id} = obj
        var tempObj:any = null

        if (data.fast){
            data.fast.timeline.map((item)=>{
                if (item.event_id == event_id){
                    tempObj = item
                }
            })
        }
        if (data.sleep){
            data.sleep.timeline.map((item)=>{
                if (item.event_id == event_id){
                    tempObj = item
                }
            })
        }
        
        var time = obj.time
        if (tempObj && tempObj.real && dayjs(tempObj.real.timestamp).format('YYYY-MM-DDTHH:mm')==obj.date + 'T' + time){
            debugger
            return tempObj.real.timestamp
        }
        
        // var hour = parseInt(time.split(':')[0])
        // var minute = parseInt(time.split(':')[1])
        // var date = obj.date
        var now = new Date(obj.date + 'T' + time + ':' + dayjs(enterTime).format('ss'))
        now.setMilliseconds(new Date(enterTime).getMilliseconds())
        // now.setHours(hour)
        // now.setMinutes(minute)
        // now.setSeconds(0)
        // now.setMilliseconds(0)
        var timestamp = now.getTime()
        return timestamp
    }

    function tapDone() {
        var findError = false
        for (var i = 0; i < array.length; i++) {
            var obj = array[i]
            var str = dayjs().format('HH:mm')
            var date = new Date(obj.date + ' ' + obj.time + ':00')
            var now = new Date()
            if (date.getTime() > now.getTime()) {
                // setTime(str)
                array[i].time = str
                console.log(str)
                setArray(array)
                setCount(count => count + 1)
                findError = true

            }
        }
        if (findError) {
            Taro.showToast({
                title: '不能超过当前时间',
                icon: 'none'
            })
            return
        }
        tapCommit(false)
    }

    function tapCommit(onlyCheck, firstCheck = false, save_confirm = null) {

        for (var i = 0; i < array.length; i++) {
            var obj = array[i]
            if (obj.time == '' || obj.date == '') {
                Taro.showToast({
                    title: t('health.missing_date_time'),
                    icon: 'none'
                })
                return;
            }


        }




        var list: any = []
        if (isSingle) {
            var obj = array[0]
            var timestamp = getTimestamp(obj)
            var params: any = {
                schedule_id: obj.schedule_id,
                event_id: obj.event_id ? obj.event_id : null,
                extra: obj.extra,
                date: dayjs(timestamp).format('YYYYMMDD'),
                timestamp: timestamp,
            }
            if (isStart) {
                params.duration = isFast ? data.fast.target.duration : data.sleep.target.duration
            }
            list.push(params)

            if (router.params.longfast && isStart) {
                list = [{
                    schedule_id: health.long_fast.timeline[0].schedule_id,
                    date: dayjs(timestamp).format('YYYYMMDD'),
                    timestamp: timestamp,
                    extra: {
                        long_fast_goal: longDuration * 60,
                        set_time: global.set_time ? global.set_time : new Date().getTime(),
                        confirm_time: new Date().getTime()
                    }
                }]
            }
        }
        else {
            if (type == 'home') {
                if (parseInt(tapIndex + '') == 2) {
                    var obj = array[1]
                    var timestamp = getTimestamp(obj)
                    list.push({
                        schedule_id: obj.schedule_id,
                        event_id: obj.event_id ? obj.event_id : null,
                        extra: obj.extra,
                        date: dayjs(timestamp).format('YYYYMMDD'),
                        timestamp: timestamp,
                    })

                    var obj2 = array[2]
                    var timestamp2 = getTimestamp(obj2)
                    list.push({
                        schedule_id: obj2.schedule_id,
                        event_id: obj.event_id ? obj.event_id : null,
                        extra: obj2.extra,
                        date: dayjs(timestamp2).format('YYYYMMDD'),
                        timestamp: timestamp2,
                    })
                }
                if (parseInt(tapIndex + '') == 3) {
                    var obj = array[0]
                    var timestamp = getTimestamp(obj)
                    list.push({
                        schedule_id: obj.schedule_id,
                        event_id: obj.event_id ? obj.event_id : null,
                        extra: obj.extra,
                        date: dayjs(timestamp).format('YYYYMMDD'),
                        timestamp: timestamp,
                    })

                    var obj2 = array[3]
                    var timestamp2 = getTimestamp(obj2)
                    list.push({
                        schedule_id: obj2.schedule_id,
                        event_id: obj.event_id ? obj.event_id : null,
                        extra: obj2.extra,
                        date: dayjs(timestamp2).format('YYYYMMDD'),
                        timestamp: timestamp2,
                    })
                }
            }
            else {


                // const { status } = data
                for (var i = 0; i <= tapIndex; i++) {
                    if (firstCheck && i > 1) {

                    }
                    else {
                        var obj = array[i]
                        var timestamp = getTimestamp(obj)
                        list.push({
                            schedule_id: obj.schedule_id,
                            event_id: obj.event_id ? obj.event_id : null,
                            extra: obj.extra,
                            date: dayjs(timestamp).format('YYYYMMDD'),
                            timestamp: timestamp,
                        })
                    }
                }
            }
        }

        if (firstCheck && parseInt(router.params.initIndex) == 1) {
            var temps = [list[1], list[0]]
            commit(temps, onlyCheck, save_confirm)
        }
        else {
            commit(list, onlyCheck, save_confirm)
        }


    }

    function getLogMethod(list) {
        // if (isSingle) return 'LOG_ONCE'
        if (list.length == 1) return 'LOG_ONCE'
        const { status } = data
        if (status == 'OG2_MISALIGNED') return 'LOG_MULTIPLE'
        if (status == 'OG2_NO1') return 'LOG_MULTIPLE'
        if (status == 'WFS' && list.length > 1) return 'LOG_MULTIPLE'
        if (status == 'OG1' && list.length > 2) return 'LOG_MULTIPLE'
        if (status == 'OG2' && list.length > 3) return 'LOG_MULTIPLE'

        return 'LOG_ONCE'
    }

    function commit(list, onlyCheck, save_confirm) {
        debugger
        const sortedData = list.sort((a, b) => {
            return b.extra.confirm_time - a.extra.confirm_time; // 降序
        });
        var params: any = {
            check_items: sortedData,
            op_page: isFastWithSleep ? 'FAST_WITH_SLEEP' : null,
            only_check: onlyCheck,
            log_method: getLogMethod(list),
            extra: {
                set_time: enterTime,
                confirm_time: new Date().getTime()
            }
        }
        if (save_confirm) {
            params.save_confirm = save_confirm
        }
        // console.log(new Date().getTime())
        // console.log(params)

        // return
        if (onlyCheck) {
            var dt = new Date().getTime()
            params.requestId = dt
            setRequestId(dt)
        }
        else {
            params.requestId = requestId
        }



        if (posting) return
        setPosting(true)
        clockTimes(params).then(res => {
            if (onlyCheck){
                setRequestId(new Date().getTime())
            }

            if ((res as any).result) {
                setErrors([])
                setConflicts([])
                if (!onlyCheck) {
                    global.refreshWindow()
                    if (global.refreshHistory)
                        global.refreshHistory()
                    if (global.refreshOtherHistory)
                        global.refreshOtherHistory()
                    if (global.refreshFastSleep)
                        global.refreshFastSleep()

                    if (global.refreshLongFast) {
                        global.refreshLongFast()
                    }
                    Taro.redirectTo({
                        url: './post_result?data=' + JSON.stringify(res)
                    })
                    setTimeout(() => {
                        setPosting(false)
                    }, 1000)
                }
                else {
                    setPosting(false)
                }



            }
            else {
                setPosting(false)
                if ((res as any).warn_code == 'SAVE_AS_LF') {
                    showAlert({
                        title: 'Saving as Long Fast',
                        content: 'Fasting that lasts more than 24 hours will be saved as Long Fast. ',
                        showCancel: true,
                        cancelText: '取消',
                        confirmText: '保存',
                        cancel: () => {
                        },
                        confirm: () => {
                            tapCommit(false, false, (res as any).warn_code)
                        }
                    })
                    return
                }
                if ((res as any).warn_code == 'SAVE_AS_IF') {
                    showAlert({
                        title: 'Saving as Intermittent Fasting',
                        content: 'Fasting that lasts fewer than 24 hours will be saved as Intermittent Fasting.',
                        showCancel: true,
                        cancelText: '取消',
                        confirmText: '保存',
                        cancel: () => {
                        },
                        confirm: () => {
                            tapCommit(false, false, (res as any).warn_code)
                        }
                    })
                    return
                }
                setErrors((res as any).error_messages)
                setConflicts((res as any).conflict_schedule_ids)
                setShowSuccess(true)
                setAutoCheck(true)
                var tempList = JSON.parse(JSON.stringify(array))
                tempList.map(item => {
                    if ((res as any).conflict_schedule_ids.includes(item.schedule_id)) {
                        item.disable = false
                    }
                })
                setIgnoreCheck(true)
                setArray(tempList)

            }

            // Taro.navigateBack({
            //     delta: 1
            // })
        }).catch(e => {
            setPosting(false)
        })
    }

    function changeToScheduleTime(schedule_time, index) {
        var nowTime = parseInt(dayjs().format('HHmm'))
        var scheduleTime = parseInt(schedule_time.replace(':', ''))
        var date = dayjs().format('YYYY-MM-DD')
        if (scheduleTime > nowTime) {
            date = dayjs(new Date().getTime() - 24 * 3600 * 1000).format('YYYY-MM-DD')
        }
        var list = JSON.parse(JSON.stringify(array))
        list[index].date = date
        list[index].time = schedule_time
        list[index].extra.confirm_time = new Date().getTime()
        setArray(list)
    }

    function durationTime() {
        const { fast, sleep } = data
        var seconds = isFast ? fast.target.duration / 1000 : sleep.target.duration / 1000
        var hour = Math.floor(seconds / 3600)
        var minutes = Math.floor((seconds % 3600) / 60)
        var str = ''
        if (hour > 0) {
            str = hour + TimeFormatter.getHoursUnit(hour)
        }
        if (minutes > 0) {
            str += minutes + TimeFormatter.getMinutesUnit(minutes)
        }
        if (hour == 0 && minutes == 0) {
            str = 0 + TimeFormatter.getMinutesUnit(0)
        }
        return str
    }

    // function changeTimeText(schedule_time, time) {
    //     if (time == schedule_time) {
    //         return `Check in:Today ${dayjs(enterTime).format('HH:mm')}`
    //     }
    //     return `Scheduled for ${schedule_time}`
    // }

    // function changeTimeText(timestamp,date, time) {
    //     // if (new Date().getTime()>timestamp){
    //         return t('health.schedule_for',{time:dayjs(timestamp).format('HH:mm')})
    //     // }
    //     // if (time == schedule_time) {
    //     //     return `Check in:Today ${dayjs(enterTime).format('HH:mm')}`
    //     // }
    //     // return `Scheduled for ${schedule_time}`
    // }

    function tapChangeTime(schedule_time, time, index) {
        if (time == schedule_time) {
            changeToScheduleTime(dayjs(enterTime).format('HH:mm'), index)
        }
        else {
            changeToScheduleTime(schedule_time, index)
        }

    }

    function expectText() {
        var obj = array[0]
        var timestamp = getTimestamp(obj)
        var duration = isFast ? data.fast.target.duration : data.sleep.target.duration
        if (router.params.longfast) {
            duration = longDuration * 1000 * 3600
        }
        var time2 = timestamp + duration
        if (router.params.longfast) {
            return 'Expect to end fast at ' + dayjs(time2).format('MM-DD HH:mm')
        }
        var strTime = TimeFormatter.dayjsFormat(time2, false)
        if (isFast) {
            return 'Expect to end fast at ' + strTime
        }
        else {
            return 'Expect to wake up at ' + strTime
        }
    }

    function logItem(index: number, iFast: boolean, iStart: boolean, showLine: boolean) {
        const { fast, sleep, status } = data

        var schedule_time = ''
        var title = ''

        var date = array[index].date//array[index].today ? "Today" : "Yesterday"
        var time = array[index].time
        var min = enterTime
        var max = new Date().getTime()
        if (iFast) {
            var timeline = index == 0 ? fast.timeline[0] : fast.timeline[1]
            if (!isFastWithSleep) {
                //首页单场景进入时时间限制处理逻辑
                var fastScenario = getScenario(health.windows, 'FAST')
                timeline = iStart ? fastScenario.timeline[0] : fastScenario.timeline[1]
                if (fastScenario.status == 'WFS') {
                    min = enterTime - 24 * 3600 * 1000
                    max = new Date().getTime()
                }
                else {
                    min = timeline.picker.min_timestamp
                    max = timeline.picker.max_timestamp ?? new Date().getTime()
                }
            }
            else {
                //fast_sleep 进入时，除了wfs情况前端处理，其他case后端处理
                if (status == 'WFS') {
                    min = enterTime - 24 * 3600 * 1000
                    max = new Date().getTime()
                }
                else if (status == 'OG2_MISALIGNED') {
                    if (index == 0) {
                        min = sleep.real.start_timestamp - 24 * 3600 * 1000
                        max = sleep.real.start_timestamp
                    }
                    else {
                        min = fast.real.start_timestamp
                        max = new Date().getTime()
                    }

                }
                else {
                    min = timeline.picker.min_timestamp
                    max = timeline.picker.max_timestamp ?? new Date().getTime()
                }
            }

        }
        else {
            var timeline = index == 1 ? sleep.timeline[0] : sleep.timeline[1]
            if (status == 'WFS') {
                min = enterTime - 24 * 3600 * 1000
                max = new Date().getTime()
            }
            else if (status == 'OG2_MISALIGNED') {
                if (index == 1) {
                    min = fast.real.start_timestamp
                }
                else {
                    min = sleep.real.start_timestamp

                }
                max = new Date().getTime()
            }
            else {
                min = timeline.picker.min_timestamp
                max = timeline.picker.max_timestamp ?? new Date().getTime()
            }
        }

        const today = dayjs();
        var schedule_id = ''
        if (iFast) {
            schedule_time = iStart ? fast.period.start_time : fast.period.end_time
            schedule_id = iStart ? fast.timeline[0].schedule_id : fast.timeline[1].schedule_id
            if (!iStart && fast.status == 'OG') {
                schedule_time = dayjs(fast.target.end_timestamp).format('HH:mm')
            }
            title = iStart ? fast.timeline[0].title : fast.timeline[1].title



            if (array[index].disable) {
                var timestamp = iStart ? fast.real.start_timestamp : fast.real.end_timestamp
                date = dayjs(timestamp).format('YYYY-MM-DD')
                // const dt = dayjs(timestamp);
                // const yesterday = today.subtract(1, 'day');
                // time = dayjs(timestamp).format('HH:mm')

                // if (dt.isSame(today, 'day')) {
                //     date = global.language == 'en' ? 'Today' : '今天';
                // } else if (dt.isSame(yesterday, 'day')) {
                //     date = global.language == 'en' ? 'Yesterday' : '昨天';
                // } else {
                //     date = global.language == 'en' ? dt.format('MMM D') : dt.format('MMMD日');
                // }
            }
        }
        else {
            schedule_time = iStart ? sleep.period.start_time : sleep.period.end_time
            schedule_id = iStart ? sleep.timeline[0].schedule_id : sleep.timeline[1].schedule_id
            if (!iStart && sleep.status == 'OG') {
                schedule_time = dayjs(sleep.target.end_timestamp).format('HH:mm')
            }
            title = iStart ? sleep.timeline[0].title : sleep.timeline[1].title
            if (array[index].disable) {
                var timestamp = iStart ? sleep.real.start_timestamp : sleep.real.end_timestamp
                date = dayjs(timestamp).format('YYYY-MM-DD')
                // const dt = dayjs(timestamp);
                // const yesterday = today.subtract(1, 'day');
                // time = dayjs(timestamp).format('HH:mm')

                // if (dt.isSame(today, 'day')) {
                //     date = global.language == 'en' ? 'Today' : '今天';
                // } else if (dt.isSame(yesterday, 'day')) {
                //     date = global.language == 'en' ? 'Yesterday' : '昨天';
                // } else {
                //     date = global.language == 'en' ? dt.format('MMM D') : dt.format('MMMD日');
                // }
            }
        }
        var showError = false;
        if (conflicts.includes(schedule_id)) {
            showError = true
        }
        return <ChooseDateTime
            title={isSingle ? null : <StatusIndicator
                type={showError ? StatusType.img : StatusType.normal}
                color={showError ? MainColorType.error : iFast ? MainColorType.fast : MainColorType.sleep}
                fontColor="#000"
                fontSize={rpxToPx(34)}
                text={title}
                defaultSpace
            >
                {
                    showError && <IconError color="#fff" width={rpxToPx(26)} />
                }
            </StatusIndicator>}
            disable={array[index].disable}
            showError={showError}
            showLine={showLine}
            targetTimestamp = {timeline.target.timestamp}
            enterTimestamp={enterTime}
            // footerTitle=""
            // footerTitle={changeTimeText(timeline.target.timestamp,data, time)}
            // tapFooter={() => tapChangeTime(schedule_time, time, index)}
            color={iFast ? MainColorType.fast : MainColorType.sleep}
            minTimestamp={min}
            maxTimestamp={max}
            date={date}
            time={time}
            count={count}
            expand={expandIndex == index}
            choose={() => {
                setExpandIndex(index)
            }}
            change={(e) => {
                var list = JSON.parse(JSON.stringify(array))
                list[index].date = e[0]
                list[index].time = e[1]
                list[index].extra.confirm_time = new Date().getTime()
                setArray(list)
            }}
        // dateChange={(e) => {
        //     debugger
        //     var list = JSON.parse(JSON.stringify(array))
        //     list[index].date = e
        //     list[index].extra.confirm_time = new Date().getTime()
        //     setArray(list)
        // }}
        // timeChange={(e) => {
        //     debugger
        //     var list = JSON.parse(JSON.stringify(array))
        //     list[index].time = e
        //     list[index].extra.confirm_time = new Date().getTime()
        //     setArray(list)
        // }}
        />
    }

    function multiContent() {
        if (type == 'home') {
            switch (parseInt(tapIndex + '')) {
                case 2:
                    return <View style={{ position: 'relative' }}>
                        {
                            logItem(1, false, true, false)
                        }
                        {
                            logItem(2, false, false, false)
                        }
                    </View>
                case 3:
                    return <View style={{ position: 'relative' }}>
                        {
                            logItem(0, true, true, false)
                        }
                        {
                            logItem(3, true, false, false)
                        }
                    </View>
            }

        }
        const { status } = data
        switch (parseInt(tapIndex + '')) {
            case 1:
                return <View style={{ position: 'relative' }}>
                    {
                        logItem(0, true, true, true)
                    }
                    {
                        logItem(1, false, true, false)
                    }
                </View>
            case 2:
                return <View style={{ position: 'relative' }}>
                    {
                        logItem(0, true, true, true)
                    }
                    {
                        logItem(1, false, true, true)
                    }
                    {
                        logItem(2, false, false, false)
                    }
                </View>
            case 3:
                return <View style={{ position: 'relative' }}>
                    {
                        logItem(0, true, true, true)
                    }
                    {
                        logItem(1, false, true, true)
                    }
                    {
                        logItem(2, false, false, true)
                    }
                    {
                        logItem(3, true, false, false)
                    }
                </View>
        }
        return <View style={{ position: 'relative' }}></View>
    }

    function goalCard() {
        if (isSingle && isStart && showGoal) {
            if (router.params.longfast) {
                return <Card>
                    <View style={{ position: 'relative' }}>
                        <View className="card_header" style={{ justifyContent: 'space-between' }}>
                            <View className="h34" style={{ marginLeft: rpxToPx(12) }}>LongFast Goal</View>
                            <NewButton
                                type={expandIndex == -1 ? NewButtonType.alpha : NewButtonType.gray}
                                color={isFast ? MainColorType.fast : MainColorType.sleep}
                                height={rpxToPx(84)}
                                title={getLongDuration()}
                                fontNormal
                                onClick={() => { setExpandIndex(-1) }}
                            />
                            {/* </View> */}
                        </View>
                        {
                            expandIndex == -1 && <View style={{
                                display: 'flex',
                                flexDirection: 'column',
                                alignItems: 'center'
                            }}>
                                <NewDurationPicker color={MainColorType.fast}
                                    type={DurationPickerType.long}
                                    value={longDuration}
                                    onChange={(e) => {
                                        setLongDuration(e)
                                    }}
                                />
                            </View>
                        }

                    </View>
                </Card>
            }
            else {
                return <Card>
                    <View style={{ position: 'relative' }}>
                        <View className="card_header" style={{ justifyContent: 'space-between' }}>
                            <View className="h34" style={{ marginLeft: rpxToPx(12) }}>{isFast ? 'Fast Goal' : 'Sleep Goal'}</View>
                            {/* <View style={{
                            borderColor: expandIndex == -1 ? isFast ? MainColorType.fast : MainColorType.sleep : 'transparent',
                            borderWidth: rpxToPx(2),
                            borderRadius: rpxToPx(88 / 4),
                            borderStyle: 'solid'
                        }}> */}
                            <NewButton
                                type={expandIndex == -1 ? NewButtonType.alpha : NewButtonType.gray}
                                color={isFast ? MainColorType.fast : MainColorType.sleep}
                                height={rpxToPx(84)}
                                width={rpxToPx(238)}
                                title={durationTime()}
                                fontNormal
                                onClick={() => { setExpandIndex(-1) }}
                            />
                            {/* </View> */}
                        </View>
                        {
                            expandIndex == -1 && <View style={{
                                display: 'flex',
                                flexDirection: 'column',
                                alignItems: 'center'
                            }}>
                                <NewDurationPicker
                                    type={DurationPickerType.normal}
                                    value={isFast ? data.fast.target.duration : data.sleep.target.duration}
                                    onChange={e => {
                                        var temp = JSON.parse(JSON.stringify(data))
                                        if (isFast) {
                                            temp.fast.target.duration = e
                                        }
                                        else {
                                            temp.sleep.target.duration = e
                                        }
                                        setData(temp)
                                    }}
                                    color={isFast ? MainColorType.fast : MainColorType.sleep} />
                            </View>
                        }

                    </View>
                </Card>
            }
        }
        return <View />
    }

    if (!loaded) return <View />

    return <View className="page_container">
        <View style={{ height: rpxToPx(36) }} />
        <Card>
            <View style={{ display: 'flex', flexDirection: 'column' }}>
                {
                    errors.map((item, index) => {
                        return <View className="error_bg" key={index}>
                            <View className="error_icon_bg">
                                <IconError color="#fff" width={rpxToPx(26)} />
                            </View>
                            <Text className="h24" style={{ lineHeight: rpxToPx(36) + 'px' }}>{item}</Text>
                        </View>
                    })
                }
                {
                    autoCheck && showSuccess && errors.length == 0 && <View className="error_bg" style={{ backgroundColor: MainColorType.success + '1A' }}>
                        <View className="error_icon_bg" style={{ backgroundColor: MainColorType.success }}>
                            <Image src={require('@assets/_health/tip_check.png')} style={{ width: rpxToPx(26), height: rpxToPx(26) }} />
                        </View>
                        <Text className="h24" style={{ lineHeight: rpxToPx(36) + 'px' }}>成功提示</Text>
                    </View>
                }
                {
                    isSingle ? <View style={{ position: 'relative' }}>
                        {
                            logItem(0, isFast, isStart, false)
                        }
                    </View> : multiContent()
                }
            </View>

        </Card>
        <View style={{ height: rpxToPx(36) }} />
        {
            isSingle && isStart && !showGoal && <View style={{ height: rpxToPx(72), marginTop: rpxToPx(18) }}>
                <NewButton
                    type={NewButtonType.link}
                    title="Show More"
                    onClick={() => {
                        setShowGoal(true)
                    }}
                />
            </View>
        }
        {
            goalCard()
        }
        {
            isSingle && isStart && showGoal && <View className="h24 g02" style={{
                width: rpxToPx(750), height: rpxToPx(84),
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center'
            }}>{expectText()}</View>
        }
        <View style={{ flex: 1 }} />
        {/* <View style={{ marginBottom: rpxToPx(128), display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
            <NewButton
                color={footerBtnColor()}
                type={NewButtonType.fill}
                title={'Log'}
                width={rpxToPx(646)}
                height={rpxToPx(96)}
                disable={errors.length > 0}
                bold={true}
                onClick={() => tapCommit(false)} />
        </View> */}
        <View className="main_footer">
            <NewButton
                color={footerBtnColor()}
                type={NewButtonType.fill}
                title={isSingle?t('health.log_moment'):t('health.log_moments')}
                width={rpxToPx(646)}
                height={rpxToPx(96)}
                disable={errors.length > 0}
                bold={true}
                onClick={() => tapDone()} />
        </View>

    </View>
}