import Timeline from "@/components/view/Timeline";
import { TimeFormatter } from "@/utils/time_format";
import { View, Text } from "@tarojs/components";
import getStatus from "../hooks/Record";
import { ColorType } from "@/context/themes/color";
import { useTranslation } from "react-i18next";
import { useEffect, useState } from "react";
import { useSelector } from "react-redux";
import './TimelineFastSleep.scss'
import dayjs from 'dayjs'
import { rpxToPx } from "@/utils/tools";
import Taro from "@tarojs/taro";


const utc = require('dayjs/plugin/utc')
const timezone = require('dayjs/plugin/timezone')
var advanced = require("dayjs/plugin/advancedFormat")

dayjs.extend(utc)
dayjs.extend(timezone)
dayjs.extend(advanced)
export default function TimelineFastSleep(props: {
    data: any,
    title?: string,
    first_real_check_time?: number,
    multiTimeZone?: boolean,
    diffTimeZone?: boolean,
    scenario?: any,
}) {
    const { t } = useTranslation()
    const [diffTimeZone] = useState(props.diffTimeZone)
    const [multTimeZone] = useState(props.multiTimeZone)
    const scenario = props.scenario ? props.scenario : useSelector((state: any) => state.scenario);

    useEffect(() => {
        // var split = new Date().toString().split(' ');
        // var currentTZ = split[split.length - 2];
        // if (props.data.fast) {
        //     if (props.data.fast.real_start_time_zone && props.data.fast.real_start_time_zone != currentTZ) {
        //         setDiffTimeZone(true)
        //         return
        //     }
        //     if (props.data.fast.real_end_time_zone && props.data.fast.real_end_time_zone != currentTZ) {
        //         setDiffTimeZone(true)
        //         return
        //     }
        // }

        // if (props.data.sleep) {
        //     if (props.data.sleep.real_start_time_zone && props.data.sleep.real_start_time_zone != currentTZ) {
        //         setDiffTimeZone(true)
        //         return
        //     }
        //     if (props.data.sleep.real_end_time_zone && props.data.sleep.real_end_time_zone != currentTZ) {
        //         setDiffTimeZone(true)
        //         return
        //     }
        // }
        // setDiffTimeZone(false)

    }, [props.data])


    function formateTime(obj: any, isEnd: boolean, isFastMode?: boolean) {
        if (isEnd) {
            if (obj.real_end_time) {
                var newTimestamp = TimeFormatter.transferTimestamp(obj.real_end_time, obj.real_end_time_zone)
                return TimeFormatter.timelineFormatTime(newTimestamp)
                // return diffTimeZone ? TimeFormatter.timelineFullFormatTime(newTimestamp) : TimeFormatter.timelineFormatTime(obj.real_end_time)
            }
            else {

                var real_time_zone = props.data.last_time_zone

                var newTimestamp = TimeFormatter.transferTimestamp(obj.target_end_time, real_time_zone)
                return TimeFormatter.timelineFormatTime(newTimestamp)
                // return diffTimeZone ? TimeFormatter.timelineFullFormatTime(obj.target_end_time) : TimeFormatter.timelineFormatTime(obj.target_end_time)
            }
        }
        else {

            if (obj.real_start_time) {
                var newTimestamp = TimeFormatter.transferTimestamp(obj.real_start_time, obj.real_start_time_zone)
                return TimeFormatter.timelineFormatTime(newTimestamp)
                // return diffTimeZone ? TimeFormatter.timelineFullFormatTime(newTimestamp) : TimeFormatter.timelineFormatTime(obj.real_start_time)
            }
            else {
                var real_time_zone = props.data.last_time_zone
                var newTimestamp = TimeFormatter.transferTimestamp(obj.target_start_time, real_time_zone)

                return TimeFormatter.timelineFormatTime(newTimestamp)
                // return diffTimeZone ? TimeFormatter.timelineFullFormatTime(obj.target_start_time) : TimeFormatter.timelineFormatTime(obj.target_start_time)
            }
        }

    }

    function formateDate(currentStatus: string, obj: any, isEnd: boolean, isFastMode?: boolean) {
        var now = new Date()
        var seconds = now.getHours() * 3600 + now.getMinutes() * 60 + now.getSeconds()
        if (currentStatus == 'WAIT_FOR_START') {
            if (props.data.scenario == 'SLEEP') {
                if (isEnd) {
                    var count = TimeFormatter.timestringToSeconds(scenario.schedule.sleep.start_time)
                    var count2 = TimeFormatter.timestringToSeconds(scenario.schedule.sleep.end_time)
                    if (count2 < count) {
                        return global.language == 'en' ? 'Tomorrow' : '明天'
                    }
                    return global.language == 'en' ? 'Today' : '今天'
                }
            }
            else {
                var count = TimeFormatter.timestringToSeconds(scenario.schedule.fast.start_time)
                if (isFastMode) {
                    if (isEnd) {
                        var count2 = TimeFormatter.timestringToSeconds(scenario.schedule.fast.end_time)
                        if (count2 < count) {
                            return global.language == 'en' ? 'Tomorrow' : '明天'
                        }
                    }
                    return global.language == 'en' ? 'Today' : '今天'
                }
                else {
                    if (isEnd) {
                        var count2 = TimeFormatter.timestringToSeconds(scenario.schedule.sleep.end_time)
                        if (count2 < count) {
                            return global.language == 'en' ? 'Tomorrow' : '明天'
                        }
                    }
                    else {
                        var count2 = TimeFormatter.timestringToSeconds(scenario.schedule.sleep.start_time)
                        if (count2 < count) {
                            return global.language == 'en' ? 'Tomorrow' : '明天'
                        }
                    }

                    return global.language == 'en' ? 'Today' : '今天'
                }
            }
        }
        if (isEnd) {
            if (obj.real_end_time) {
                var newTimestamp = TimeFormatter.transferTimestamp(obj.real_end_time, obj.real_end_time_zone)
                if (diffTimeZone || multTimeZone) {
                    return TimeFormatter.getMonthAndDayByTimestamp(newTimestamp, true) + ' '
                }
                return TimeFormatter.dateDescription(newTimestamp, true, diffTimeZone || multTimeZone)
            }
            else {
                var real_time_zone = props.data.last_time_zone
                var newTimestamp = TimeFormatter.transferTimestamp(obj.target_end_time, real_time_zone)
                if (diffTimeZone || multTimeZone) {
                    return TimeFormatter.getMonthAndDayByTimestamp(newTimestamp, true) + ' '
                }
                return TimeFormatter.dateDescription(newTimestamp, true, diffTimeZone || multTimeZone)
            }
        }
        else {
            if (obj.real_start_time) {
                var newTimestamp = TimeFormatter.transferTimestamp(obj.real_start_time, obj.real_start_time_zone)
                if (diffTimeZone || multTimeZone) {
                    return TimeFormatter.getMonthAndDayByTimestamp(newTimestamp, true) + ' '
                }
                return TimeFormatter.dateDescription(newTimestamp, true, diffTimeZone || multTimeZone)
            }
            else {
                var real_time_zone = props.data.last_time_zone
                var newTimestamp = TimeFormatter.transferTimestamp(obj.target_start_time, real_time_zone)
                if (diffTimeZone || multTimeZone) {
                    return TimeFormatter.getMonthAndDayByTimestamp(newTimestamp, true) + ' '
                }
                return TimeFormatter.dateDescription(obj.target_start_time, true, diffTimeZone || multTimeZone)
            }
        }

    }

    var timelineItems: any = [];
    /*
    attention:
    status == 待开始时
    timeline的时间不以时间戳进行处理，而是以target时间字符串进行显示
    */
    if (props.data.fast && props.data.scenario != 'SLEEP') {
        var timeZone = ''
        if (props.data.fast.real_start_time_zone) {
            timeZone = ' ' + props.data.fast.real_start_time_zone
        }
        var desc = props.data.status == 'WAIT_FOR_START' ? '' : multTimeZone ? timeZone : ''
        if (props.data.status != 'WAIT_FOR_START' && props.data.status != 'COMPLETED' && diffTimeZone) {
            desc = timeZone
        }
        timelineItems.push(
            {
                status: getStatus(true, true, props.data),
                title: getStatus(true, true, props.data) == 'padding' ?
                    t('feature.track_time_duration.common.start_fast') :
                    t('feature.track_time_duration.common.started_fasting'),
                content: props.data.status == 'WAIT_FOR_START' ? formateDate(props.data.status, props.data.fast, false, true) + ' ' + scenario.schedule.fast.start_time : formateDate(props.data.status, props.data.fast, false, true) + ' ' + formateTime(props.data.fast, false, true),
                date: desc,
                // (diffTimeZone ? timeZone : showDate(props.data.fast, false) ? formateDate(props.data.fast, false) : ''),
                color: global.fastColor ? global.fastColor : ColorType.fast
            }
        )
    }
    if (props.data.sleep && props.data.scenario != 'FAST') {

        var status = getStatus(false, true, props.data)
        var strContent = props.data.status == 'WAIT_FOR_START' ? formateDate(props.data.status, props.data.sleep, false, false) + ' ' + scenario.schedule.sleep.start_time : formateDate(props.data.status, props.data.sleep, false, false) + ' ' + formateTime(props.data.sleep, false, false)


        var timeZone = ''
        if (props.data.sleep.real_start_time_zone) {
            timeZone = ' ' + props.data.sleep.real_start_time_zone
        }
        var strDate = multTimeZone ? timeZone : ''
        if (props.data.status != 'WAIT_FOR_START' && props.data.status != 'COMPLETED') {
            if ((!timeZone || timeZone.length == 0) && (multTimeZone || diffTimeZone)) {
                strDate = props.data.last_time_zone
            }
        }

        debugger

        timelineItems.push(
            {
                status: status,
                title: status == 'padding' ?
                    t('feature.track_time_duration.common.start_sleep') :
                    t('feature.track_time_duration.common.started_sleeping'),
                content: status == 'un_done' ? '' : strContent,
                date: status == 'un_done' ? '' : strDate,
                color: global.sleepColor ? global.sleepColor : ColorType.sleep
            }
        )
    }
    if (props.data.sleep && props.data.scenario != 'FAST') {
        var timeZone = ''
        if (props.data.sleep.real_end_time_zone) {
            timeZone = ' ' + props.data.sleep.real_end_time_zone
        }
        var status = getStatus(false, false, props.data)
        var strContent: string = props.data.status == 'WAIT_FOR_START' ? formateDate(props.data.status, props.data.sleep, true, false) + ' ' + scenario.schedule.sleep.end_time : formateDate(props.data.status, props.data.sleep, true) + ' ' + formateTime(props.data.sleep, true, false)
        var strDate = multTimeZone ? timeZone : ''

        if (props.data.status != 'WAIT_FOR_START' && props.data.status != 'COMPLETED') {
            if ((!timeZone || timeZone.length == 0) && (multTimeZone || diffTimeZone)) {
                strDate = props.data.last_time_zone
            }
        }


        // (diffTimeZone ? timeZone : showDate(props.data.sleep, true) ? formateDate(props.data.sleep, true) : '')
        timelineItems.push(
            {
                status: status,
                title: status == 'padding' ?
                    t('feature.track_time_duration.common.end_sleep') :
                    t('feature.track_time_duration.common.ended_sleeping'),
                content: status == 'un_done' ? '' : strContent,
                date: status == 'un_done' ? '' : strDate,
                color: global.sleepColor ? global.sleepColor : ColorType.sleep
            }
        )
    }
    if (props.data.fast && props.data.scenario != 'SLEEP') {
        var timeZone = ''
        if (props.data.fast.real_end_time_zone) {
            timeZone = ' ' + props.data.fast.real_end_time_zone
        }
        if (props.data.status != 'WAIT_FOR_START' && props.data.status != 'COMPLETED') {
            if ((!timeZone || timeZone.length == 0) && (multTimeZone || diffTimeZone)) {
                timeZone = props.data.last_time_zone
            }
        }

        if ((diffTimeZone && !multTimeZone) && props.data.status == 'COMPLETED') {
            timeZone = ''
        }
        if (!diffTimeZone && !multTimeZone && props.data.status == 'COMPLETED') {
            timeZone = ''
        }

        timelineItems.push(
            {
                status: getStatus(true, false, props.data),
                title: getStatus(true, false, props.data) == 'padding' ?
                    t('feature.track_time_duration.common.end_fast') :
                    t('feature.track_time_duration.common.ended_fasting'),
                content: props.data.status == 'WAIT_FOR_START' ? formateDate(props.data.status, props.data.fast, true, true) + ' ' + scenario.schedule.fast.end_time : formateDate(props.data.status, props.data.fast, true) + ' ' + formateTime(props.data.fast, true, true),
                // date: multTimeZone ? timeZone : '',
                date: timeZone,
                // (diffTimeZone ? timeZone : showDate(props.data.fast, true) ? formateDate(props.data.fast, true) : ''),
                color: global.fastColor ? global.fastColor : ColorType.fast
            }
        )
    }

    function getTZLocation() {
        if (props.data.fast) {
            if (props.data.fast.real_start_time_zone_id) {
                return `${dayjs().tz(props.data.fast.real_start_time_zone_id).format('z')} (${props.data.fast.real_start_time_zone_id})`
            }
            return props.data.fast.real_start_time_zone
        }
        else {
            if (props.data.sleep.real_start_time_zone_id) {
                return `${dayjs().tz(props.data.sleep.real_start_time_zone_id).format('z')} (${props.data.sleep.real_start_time_zone_id})`
                // return props.data.sleep.real_start_time_zone_id
            }
            return props.data.sleep.real_start_time_zone
        }
    }

    function getDeviceLocation(){
        if (Taro.getSystemInfoSync().platform == 'ios') {
            return `${dayjs().format('z')} (${dayjs.tz.guess()})`
        }
        return `${dayjs().format('z')}`
    }

    function getTZOffset() {

        let offset = 0;

        var current1 = dayjs()
        var current
        if (props.data.fast) {
            if (props.data.fast.real_start_time_zone_id) {
                current = dayjs().tz(props.data.fast.real_start_time_zone_id)
                offset = current.date() * 24 * 60 + current.hour() * 60 + current.minute() - current1.date() * 24 * 60 - current1.hour() * 60 - current1.minute()
            }
            else {
                offset = TimeFormatter.timeZoneOffset(props.data.fast.real_start_time_zone)
            }
        }
        else {
            if (props.data.sleep.real_start_time_zone_id) {
                current = dayjs().tz(props.data.sleep.real_start_time_zone_id)
                offset = current.date() * 24 * 60 + current.hour() * 60 + current.minute() - current1.date() * 24 * 60 - current1.hour() * 60 - current1.minute()
            }
            else {
                offset = TimeFormatter.timeZoneOffset(props.data.sleep.real_start_time_zone)
            }
        }
        // offset = current.date() * 24 * 60 + current.hour() * 60 + current.minute() - current1.date() * 24 * 60 - current1.hour() * 60 - current1.minute()

        var hour = Math.floor(Math.abs(offset) / 60)
        var minute = Math.abs(offset) % 60
        var time = ''
        if (global.language == 'en') {
            time = `${hour} h`
            if (minute > 0) {
                time += ` ${minute} m`
            }
        }
        else {
            time = `${hour}小时`
            if (minute > 0) {
                time += `${minute}分钟`
            }
        }
        return offset > 0 ? t('feature.day_night.ahead_desc', { time: time }) : t('feature.day_night.behind_desc', { time: time })
    }

    return <View style={{ display: 'flex', flexDirection: 'column' }}>
        <View style={{ display: 'flex', flexDirection: 'row' }}>
            <Timeline items={timelineItems} title={props.title} width={468} />
            <View>
            </View>
        </View>
        {
            multTimeZone && <Text className="tz_note_desc" style={{width:rpxToPx(538)}}>{t('feature.common.multi_tz_desc')}</Text>
        }
        {
            !multTimeZone && diffTimeZone && <Text className="tz_note_desc" style={{width:rpxToPx(538)}}>{t('feature.common.diff_tz_desc', { location: getTZLocation(), offset: getTZOffset(),device_location:getDeviceLocation() })}</Text>
        }
    </View>
}