import Box from '@/components/layout/Box'
import './AllRings.scss'
import { PageContainer, View, Text } from '@tarojs/components'
import { useEffect, useState } from 'react'
import Modal from '@/components/layout/Modal.weapp'
import { rpxToPx } from '@/utils/tools'
import { ColorType } from '@/context/themes/color'
import Rings from "@/features/trackTimeDuration/components/Rings";
import { bigRingRadius, getBgRing, getCommon, getDot, ringWidth, smallRingRadius, thirdRingRadius } from '../hooks/RingData'
import { RealRing } from './Rings'
import { useSelector } from 'react-redux'
import { useTranslation } from 'react-i18next'
import { TimeFormatter } from '@/utils/time_format'
import '@/utils/ring_card.scss';
import DayNightRing from './DayNightRing'

let sunriseA = new Date()
sunriseA.setHours(6)
sunriseA.setMinutes(0)
sunriseA.setSeconds(0)
sunriseA.setMilliseconds(0)
const sunsetA = new Date()
sunsetA.setHours(18)
sunsetA.setMinutes(0)
sunsetA.setSeconds(0)
sunsetA.setMilliseconds(0)

const sunriseB = new Date()
sunriseB.setHours(6)
sunriseB.setMinutes(0)
sunriseB.setSeconds(0)
sunriseB.setMilliseconds(0)

export default function AllDayRings(props: { schedule: any }) {
    const [authInfo, setAuthInfo] = useState(global.locationDetail ? global.locationDetail : null)
    const [showRing, setShowRing] = useState(false)
    const user = useSelector((state: any) => state.user);
    const ring = useSelector((state: any) => state.ring);
    const day = useSelector((state: any) => state.day);
    const [schedule] = useState(props.schedule)
    const { t } = useTranslation()

    useEffect(() => {
        setAuthInfo(global.locationDetail)
    }, [global.locationDetail])

    function tapShow() {
        setShowRing(true)
    }

    function getFoodTime() {
        if (ring.schedule) {
            return [ring.schedule.fast.end_time, ring.schedule.fast.start_time]
        }
        var obj;
        (schedule as any).map(item => {
            if (item.name == 'FAST') {
                obj = item
            }
        })
        if (!obj) {
            console.log('报错', schedule)
            return ['16:00', '08:00'];
        }
        return [obj.schedule.fast.end_time, obj.schedule.fast.start_time]
    }

    function getActivityTime() {
        if (ring.schedule) {
            return [ring.schedule.sleep.end_time, ring.schedule.sleep.start_time]
        }
        var obj;
        (schedule as any).map(item => {
            if (item.name == 'SLEEP') {
                obj = item
            }
        })
        return [obj.schedule.sleep.end_time, obj.schedule.sleep.start_time]
    }

    function bigRing() {
        var common = getCommon(null, true)
        common.radius = bigRingRadius;
        common.lineWidth = ringWidth;
        var bgRing = getBgRing()
        const targetRing: RealRing = {
            color: (ring.current_record && ring.current_record.scenario == 'SLEEP') ? ColorType.activity + '66' : ColorType.food + '66',
            startArc: 0,
            durationArc: 2
        }
        var list = getFoodTime()
        var start;
        var end;

        if (ring.current_record && ring.current_record.scenario == 'SLEEP') {
            var list2 = getActivityTime()
            start = parseInt(list2[0].split(':')[0]) * 60 + parseInt(list2[0].split(':')[1])
            end = parseInt(list2[1].split(':')[0]) * 60 + parseInt(list2[1].split(':')[1])
            if (ring.current_record.status != 'WAIT_FOR_START') {
                var startDate = new Date(ring.current_record.sleep.target_start_time)
                var endDate = new Date(ring.current_record.sleep.target_end_time)
                end = startDate.getHours() * 60 + startDate.getMinutes()
                start = endDate.getHours() * 60 + endDate.getMinutes()
            }
        }
        else {
            start = parseInt(list[0].split(':')[0]) * 60 + parseInt(list[0].split(':')[1])
            end = parseInt(list[1].split(':')[0]) * 60 + parseInt(list[1].split(':')[1])
            if (ring.current_record && ring.current_record.status != 'WAIT_FOR_START') {
                var startDate = new Date(ring.current_record.fast.target_start_time)
                var endDate = new Date(ring.current_record.fast.target_end_time)
                end = startDate.getHours() * 60 + startDate.getMinutes()
                start = endDate.getHours() * 60 + endDate.getMinutes()
            }
        }

        if (end < start) {
            end += 24 * 60
        }
        var duration = end - start
        targetRing.startArc = (start * 60) / (24 * 3600) * 2 * Math.PI - Math.PI / 2.0;
        targetRing.durationArc = (duration * 60) / (24 * 3600) * 2 * Math.PI;

        var currentDot = getDot(null, false)
        var date = new Date()
        var minutes = date.getHours() * 60 + date.getMinutes()
        if (minutes < start) {
            minutes += 1440
        }

        currentDot.color = ColorType.food


        var now = new Date()
        var t = now.getHours() * 60 + now.getMinutes()
        var duration2 = t - start
        if (duration2 < 0) {
            duration2 += 24 * 60
        }

        let realRing: RealRing = {
            color: ColorType.food,
            startArc: (start * 60) / (24 * 3600) * 2 * Math.PI - Math.PI / 2.0,
            durationArc: (duration2 * 60) / (24 * 3600) * 2 * Math.PI
        }

        if (ring.current_record && ring.current_record.scenario == 'SLEEP') {
            realRing.color = ColorType.activity
            currentDot.color = ColorType.activity
        }

        if (!user.isLogin) {
            currentDot = null
            realRing = null
        }

        if (ring.current_record.status == 'ONGOING1') {
            realRing = null
        }

        return <Rings common={common} bgRing={bgRing} targetRing={targetRing} realRing={duration2 <= duration ? realRing : null} currentDot={currentDot} canvasId={'pop_day_big'} />
    }
    function smallRing() {
        var common = getCommon(null, false)
        common.radius = smallRingRadius;
        common.lineWidth = ringWidth;
        var bgRing = getBgRing()
        const realRingBig: RealRing = {
            color: ColorType.activity + '66',
            startArc: 0,
            durationArc: 2
        }
        var list = getActivityTime()
        var start = parseInt(list[0].split(':')[0]) * 60 + parseInt(list[0].split(':')[1])
        var end = parseInt(list[1].split(':')[0]) * 60 + parseInt(list[1].split(':')[1])
        if (ring.current_record) {
            if (ring.current_record.scenario == 'SLEEP') {
                if (ring.current_record.status == 'ONGOING') {
                    var startDate = new Date(ring.current_record.sleep.target_start_time)
                    var endDate = new Date(ring.current_record.sleep.target_end_time)
                    end = startDate.getHours() * 60 + startDate.getMinutes()
                    start = endDate.getHours() * 60 + endDate.getMinutes()
                }
            }
            else {
                if (ring.current_record.status == 'ONGOING2') {
                    var startDate = new Date(ring.current_record.sleep.target_start_time)
                    var endDate = new Date(ring.current_record.sleep.target_end_time)
                    end = startDate.getHours() * 60 + startDate.getMinutes()
                    start = endDate.getHours() * 60 + endDate.getMinutes()
                }
                else if (ring.current_record.status == 'ONGOING3') {
                    //睡眠已完成时，睡眠小于24小时，使用真实的real_end_time-real_start_time
                    //大于24小时，使用real_end_time+sleep_duration
                    if (ring.current_record.sleep.real_end_time - ring.current_record.sleep.real_start_time < 24 * 3600 * 1000) {
                        var startDate = new Date(ring.current_record.sleep.real_start_time)
                        var endDate = new Date(ring.current_record.sleep.real_end_time)
                        end = startDate.getHours() * 60 + startDate.getMinutes()
                        start = endDate.getHours() * 60 + endDate.getMinutes()
                    }
                    else {
                        var startDate = new Date(ring.current_record.sleep.real_end_time)
                        var durationTemp = end - start//ring.current_record.sleep.target_end_time-ring.current_record.sleep.target_start_time
                        if (durationTemp < 0) {
                            durationTemp += 24 * 60
                        }
                        var endDate = new Date(startDate.getTime() + durationTemp * 60 * 1000)
                        start = startDate.getHours() * 60 + startDate.getMinutes()
                        end = endDate.getHours() * 60 + endDate.getMinutes()
                    }
                }
            }

        }
        if (end < start) {
            end += 24 * 60
        }
        var duration = end - start
        realRingBig.startArc = (start * 60) / (24 * 3600) * 2 * Math.PI - Math.PI / 2.0;
        realRingBig.durationArc = (duration * 60) / (24 * 3600) * 2 * Math.PI;

        var currentDot = getDot(null, false)
        var date = new Date()
        var minutes = date.getHours() * 60 + date.getMinutes()
        if (minutes < start) {
            minutes += 1440
        }

        currentDot.color = ColorType.activity


        var now = new Date()
        var t = now.getHours() * 60 + now.getMinutes()
        var duration2 = t - start
        if (duration2 < 0) {
            duration2 += 24 * 60
        }
        let realRing: RealRing = {
            color: ColorType.activity,
            startArc: (start * 60) / (24 * 3600) * 2 * Math.PI - Math.PI / 2.0,
            durationArc: (duration2 * 60) / (24 * 3600) * 2 * Math.PI
        }

        if (!user.isLogin) {
            currentDot = null
            realRing = null
        }

        if (ring.current_record.status == 'ONGOING2') {
            realRing = null
        }

        return <Rings common={common} bgRing={bgRing} targetRing={realRingBig} realRing={duration2 <= duration ? realRing : null} currentDot={currentDot} canvasId={'pop_day_small'} />
    }
    function dayRing() {
        return <DayNightRing
            isNight={false}
            isThirdRing={true}
            canvasId={'day_night_card_big_day_ring111'}
            authInfo={authInfo}
        />
        // var common = getCommon(null, true)
        // common.radius = thirdRingRadius;
        // common.lineWidth = ringWidth;
        // var bgRing = getBgRing()

        // const realRingBig: RealRing = {
        //     color: ColorType.day + '66',
        //     startArc: 0,
        //     durationArc: 2
        // }

        // var now = new Date().getTime()
        

        // if (authInfo && authInfo.day_completed && now > authInfo.day_completed.sunset_ts) {
        //     realRingBig.color = ColorType.day
        //     var duration = (authInfo.day_completed.sunset_ts - authInfo.day_completed.sunrise_ts) / 1000
        //     // var start = new Date(authInfo.day_completed.sunrise_ts)
        //     // var start = new Date(authInfo.night_completed.sunset_ts)
        //     var newT = TimeFormatter.transferTimestamp(authInfo.day_completed.sunrise_ts,authInfo.timezone)
        //     var start = new Date(newT)
        //     realRingBig.startArc = (start.getHours() * 3600 + start.getMinutes() * 60) / (24 * 3600) * 2 * Math.PI - Math.PI / 2.0;
        //     realRingBig.durationArc = (duration) / (24 * 3600) * 2 * Math.PI;
        //     return <Rings common={common} bgRing={bgRing} targetRing={realRingBig} canvasId={'ddddsss_day1111' + 'index_day'} />

        // }

        // if (authInfo && authInfo.timezone) {
        //     now = TimeFormatter.transferTimestamp(now, authInfo.timezone)
        // }


        // var sunRise = 6 * 60
        // var sunSet = 18 * 60

        // var sunRiseObj = day.dayRingSunrise
        // var sunSetObj = day.dayRingSunset
        // sunRise = parseInt(sunRiseObj.split(':')[0]) * 60 + parseInt(sunRiseObj.split(':')[1])
        // sunSet = parseInt(sunSetObj.split(':')[0]) * 60 + parseInt(sunSetObj.split(':')[1])


        // var duration = sunSet - sunRise

        // realRingBig.startArc = (sunRise * 60) / (24 * 3600) * 2 * Math.PI - Math.PI / 2.0;
        // realRingBig.durationArc = (duration * 60) / (24 * 3600) * 2 * Math.PI;

        // var currentDot = getDot(null, false)
        // if (authInfo && authInfo.timezone){
        //     currentDot.offset = TimeFormatter.timeZoneOffset(authInfo.timezone)
        // }
        // var date = new Date(now)
        // var minutes = date.getHours() * 60 + date.getMinutes()
        // if (minutes < sunRise) {
        //     minutes += 1440
        // }

        // currentDot.color = ColorType.day

        // var t = date.getHours() * 60 + date.getMinutes()
        // var duration2 = t - sunRise
        // if (duration2 < 0) {
        //     duration2 += 24 * 60
        // }
        // var realRing: RealRing = {
        //     color: ColorType.day,
        //     startArc: (sunRise * 60) / (24 * 3600) * 2 * Math.PI - Math.PI / 2.0,
        //     durationArc: (duration2 * 60) / (24 * 3600) * 2 * Math.PI
        // }
        // if (day.dayRingDate) {
        //     if (new Date(day.dayRingDate).getDate() != new Date().getDate()) {
        //         realRing = null;
        //     }
        // }

        // if (!user.isLogin) {
        //     currentDot = null
        //     realRing = null
        // }

        // return <Rings common={common} bgRing={bgRing} targetRing={realRingBig} realRing={duration2 <= duration ? realRing : null} currentDot={currentDot} canvasId={'day111_day2'} />
    
    }


    function rings() {
        return <View style={{
            position: 'relative', zIndex: 1,
            marginLeft: -6,
        }}>
            {
                bigRing()
            }
            {
                ring.current_record && ring.current_record.scenario == 'FAST_SLEEP' &&
                <View style={{ display: 'flex', position: 'absolute', left: 0, right: 0, top: 0, bottom: 0, alignItems: 'center', justifyContent: 'center' }}>
                    {
                        smallRing()
                    }
                </View>
            }
            {
                <View style={{ display: 'flex', position: 'absolute', left: -14, top: -14, right: -14, bottom: -14 }}>
                    {
                        dayRing()
                    }
                </View>
            }

        </View>
    }

    function dayDuration() {
        return global.sunriseDuration
    }

    function eatDuration() {
        var list = getFoodTime()
        var start = parseInt(list[0].split(':')[0]) * 60 + parseInt(list[0].split(':')[1])
        var end = parseInt(list[1].split(':')[0]) * 60 + parseInt(list[1].split(':')[1])
        if (ring.current_record && ring.current_record.status != 'WAIT_FOR_START' && ring.current_record.scenario != 'SLEEP') {
            var startDate = new Date(ring.current_record.fast.target_start_time)
            var endDate = new Date(ring.current_record.fast.target_end_time)
            end = startDate.getHours() * 60 + startDate.getMinutes()
            start = endDate.getHours() * 60 + endDate.getMinutes()
        }
        if (end < start) {
            end += 24 * 60
        }
        var duration = (end - start) * 60 * 1000
        return TimeFormatter.calculateTimeDifference(new Date().getTime(), new Date().getTime() + duration);
    }

    function activityDuration() {
        var list = getActivityTime()
        var start = parseInt(list[0].split(':')[0]) * 3600 + parseInt(list[0].split(':')[1]) * 60
        var end = parseInt(list[1].split(':')[0]) * 3600 + parseInt(list[1].split(':')[1]) * 60
        if (ring.current_record) {
            if (ring.current_record.scenario == 'SLEEP') {
                if (ring.current_record.status == 'ONGOING') {
                    var startDate = new Date(ring.current_record.sleep.target_start_time)
                    var endDate = new Date(ring.current_record.sleep.target_end_time)
                    end = startDate.getHours() * 3600 + startDate.getMinutes() * 60 + startDate.getSeconds()
                    start = endDate.getHours() * 3600 + endDate.getMinutes() * 60 + endDate.getSeconds()
                }
            }
            else {
                if (ring.current_record.status == 'ONGOING2') {
                    var startDate = new Date(ring.current_record.sleep.target_start_time)
                    var endDate = new Date(ring.current_record.sleep.target_end_time)
                    end = startDate.getHours() * 3600 + startDate.getMinutes() * 60 + startDate.getSeconds()
                    start = endDate.getHours() * 3600 + endDate.getMinutes() * 60 + endDate.getSeconds()
                }
                else if (ring.current_record.status == 'ONGOING3') {
                    //睡眠已完成时，睡眠小于24小时，使用真实的real_end_time-real_start_time
                    //大于24小时，使用real_end_time+sleep_duration
                    if (ring.current_record.sleep.real_end_time - ring.current_record.sleep.real_start_time < 24 * 3600 * 1000) {
                        var startDate = new Date(ring.current_record.sleep.real_start_time)
                        var endDate = new Date(ring.current_record.sleep.real_end_time)
                        end = startDate.getHours() * 3600 + startDate.getMinutes() * 60 + startDate.getSeconds()
                        start = endDate.getHours() * 3600 + endDate.getMinutes() * 60 + endDate.getSeconds()
                    }
                    else {
                        var startDate = new Date(ring.current_record.sleep.real_end_time)
                        var durationTemp = start - end//ring.current_record.sleep.target_end_time-ring.current_record.sleep.target_start_time

                        if (durationTemp < 0) {
                            durationTemp += 24 * 3600
                        }
                        var endDate = new Date(startDate.getTime() + durationTemp * 1000)
                        end = startDate.getHours() * 3600 + startDate.getMinutes() * 60 + startDate.getSeconds()
                        start = endDate.getHours() * 3600 + endDate.getMinutes() * 60 + endDate.getSeconds()
                        debugger
                        console.log('active', end, start, durationTemp)
                    }
                }
            }

        }
        if (end < start) {
            end += 24 * 3600
        }
        var duration = (end - start) * 1000
        return TimeFormatter.calculateTimeDifference(new Date().getTime(), new Date().getTime() + duration);
    }

    function popDetail() {
        return <Box>
            <View className="ring_full_container">
                <View className="time_operate_item1">
                    <View className='fast_sleep_item three_ring_card_detail'>
                        {
                            rings()
                        }
                        <View className="duration_bg3"
                            style={{ marginLeft: rpxToPx(68), height: bigRingRadius * 2, overflow: 'visible' }}>
                            <Text className="duration_title2">{t('feature.common.day')}</Text>
                            <Text className="duration_value2" style={{ color: ColorType.day }}>{dayDuration()}</Text>

                            {
                                ring.current_record && ring.current_record.scenario != 'SLEEP' && <Text className="duration_title2">进食</Text>
                            }
                            {
                                ring.current_record && ring.current_record.scenario != 'SLEEP' && <Text className="duration_value2" style={{ color: ColorType.food }}>{eatDuration()}</Text>
                            }
                            {
                                ring.current_record && ring.current_record.scenario != 'FAST' && <Text className="duration_title2">活动</Text>
                            }
                            {
                                ring.current_record && ring.current_record.scenario != 'FAST' && <Text className="duration_value2" style={{ color: ColorType.activity, marginBottom: 0 }}>{activityDuration()}</Text>
                            }
                        </View>


                    </View>
                </View>
            </View>
        </Box>
    }

    function modalContent() {
        if (process.env.TARO_ENV == 'weapp') {
            return <Modal
                testInfo={null}
                dismiss={() => {
                    setShowRing(false)
                }}
                confirm={() => { }}>
                {popDetail()}
            </Modal>
        }
        else if (process.env.TARO_ENV == 'rn') {
            return <PageContainer style={{ backgroundColor: '#1c1c1c' }}
                // overlayStyle='background-color:rgba(0,0,0,0.9)'
                // custom-style='background-color:#1c1c1c'
                overlayStyle={{ backgroundColor: 'rgba(0,0,0,0.9)' }}
                customStyle={{ backgroundColor: '#1c1c1c' }}
                closeOnSlideDown={false}
                onBeforeEnter={() => {

                }}
                onBeforeLeave={() => {
                }}
                onClick={() => { alert('b') }}
                onClickOverlay={() => { alert('a') }}
                onAfterLeave={() => { setShowRing(false) }}
                show={showRing} round={true} overlay={true} position='bottom'
            >
                {popDetail()}
            </PageContainer>
        }
    }

    return <Box onClick={tapShow}>
        <View style={{ color: '#fff' }}>同步显示生物钟</View>
        {
            showRing && modalContent()
        }
    </Box>
}