import { View, Text, Image, Switch } from "@tarojs/components";
import { dotIsOuterRange, getBgRing, getCommon, getDot, getReal, getSchedule, getTarget } from "@/features/trackTimeDuration/hooks/RingData";
import { RealRing, CurrentDot } from "@/features/trackTimeDuration/components/Rings";
import { ColorType } from "@/context/themes/color";
import { useSelector } from "react-redux";
import Rings from "@/features/trackTimeDuration/components/Rings";
import { jumpPage } from "@/features/trackTimeDuration/hooks/Common";
import { rpxToPx } from "@/utils/tools";
import { useEffect, useState } from "react";
import Taro from "@tarojs/taro";
import './Discovery.scss'
import { useTranslation } from "react-i18next";
import { TimeFormatter } from "@/utils/time_format";
import { getPerm, uploadPerm } from "@/services/user";
import Box from "@/components/layout/Box";


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

export default function Discovery() {
    const user = useSelector((state: any) => state.user);
    const dayNight = useSelector((state: any) => state.dayNight);
    const [showRing, setShowRing] = useState(false)
    const [schedule, setSchedule] = useState(null)
    const { t } = useTranslation()

    let navigation;
    let timeStamp = new Date().getTime()
    if (useNavigation) {
        navigation = useNavigation()
    }

    useEffect(() => {
        getContent()
    }, [])

    useEffect(() => {
        setSchedule(global.homeData.scenarios)
    }, [global.homeData])

    useEffect(() => {
        if (user.isLogin) {
            getPerm({}).then(res => {
                setShowRing((res as any).show_day_ring)
            })
        }
    }, [user.isLogin])

    async function getStorage(key: string) {
        try {
            const res = await Taro.getStorage({ key });
            return res.data;
        } catch {
            return '';
        }
    }

    async function getContent() {
        const isShow = await getStorage('showDayRing') || false
        setShowRing(isShow)
    }

    function getFoodTime() {
        var obj;
        (schedule as any).map(item => {
            if (item.name == 'FAST') {
                obj = item
            }
        })
        return [obj.schedule.fast.end_time, obj.schedule.fast.start_time]
    }

    function getActivityTime() {
        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 = 42;
        common.lineWidth = 9;
        var bgRing = getBgRing()
        const realRingBig: RealRing = {
            color: ColorType.food,
            startArc: 0,
            durationArc: 2
        }
        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 (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
        }

        if (start <= minutes && end > minutes) {
            currentDot.color = ColorType.food
        }
        else {
            currentDot.color = ColorType.ring
        }
        return <Rings common={common} bgRing={bgRing} realRing={realRingBig} currentDot={currentDot} canvasId={timeStamp + '_big'} />
    }
    function smallRing() {
        var common = getCommon(null, false)
        common.radius = 28;
        common.lineWidth = 9;
        var bgRing = getBgRing()
        const realRingBig: RealRing = {
            color: ColorType.activity,
            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 (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
        }

        if (start <= minutes && end > minutes) {
            currentDot.color = ColorType.activity
        }
        else {
            currentDot.color = ColorType.ring
        }
        return <Rings common={common} bgRing={bgRing} realRing={realRingBig} currentDot={currentDot} canvasId={timeStamp + '_small'} />
    }
    function dayRing() {
        var common = getCommon(null, true)
        common.radius = 56;
        common.lineWidth = 9;
        var bgRing = getBgRing()

        const realRingBig: RealRing = {
            color: ColorType.day,
            startArc: 0,
            durationArc: 2
        }
        var sunRise = 6 * 60
        var sunSet = 18 * 60


        if (dayNight.gpsInfo && user.test_user) {
            var sunRiseObj = dayNight.gpsInfo.daylights[0].sunrise
            var sunSetObj = dayNight.gpsInfo.daylights[0].sunset
            sunRise = parseInt(sunRiseObj.split(':')[0]) * 60 + parseInt(sunRiseObj.split(':')[1])
            sunSet = parseInt(sunSetObj.split(':')[0]) * 60 + parseInt(sunSetObj.split(':')[1])
            if (sunSetObj.indexOf('PM') != -1) {
                sunSet += 12 * 60
            }
        }

        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)
        var date = new Date()
        var minutes = date.getHours() * 60 + date.getMinutes()
        if (minutes < sunRise) {
            minutes += 1440
        }

        if (sunRise <= minutes && sunSet > minutes) {
            currentDot.color = ColorType.day
        }
        else {
            currentDot.color = ColorType.ring
        }

        return <Rings common={common} bgRing={bgRing} realRing={realRingBig} currentDot={currentDot} canvasId={timeStamp + '_day'} />
    }

    function goAcitivity() {
        if (user.isLogin) {
            jumpPage('/pages/workout/Workout', 'Workout', navigation)
            return
        }
        jumpPage('/pages/account/ChooseAuth', 'ChooseAuth', navigation)
    }

    function goFood() {
        if (user.isLogin) {
            jumpPage('/pages/food/Food', 'Food', navigation)
            return
        }
        jumpPage('/pages/account/ChooseAuth', 'ChooseAuth', navigation)
    }

    function dayDuration() {
        if (dayNight.gpsInfo && dayNight.isMember) {
            var sunRiseObj = dayNight.gpsInfo.daylights[0].sunrise
            var sunSetObj = dayNight.gpsInfo.daylights[0].sunset
            var sunRise = parseInt(sunRiseObj.split(':')[0]) * 60 + parseInt(sunRiseObj.split(':')[1])
            var sunSet = parseInt(sunSetObj.split(':')[0]) * 60 + parseInt(sunSetObj.split(':')[1])
            if (sunSetObj.indexOf('PM') != -1) {
                sunSet += 12 * 60
            }

            var duration = (sunSet - sunRise) * 60 * 1000

            return TimeFormatter.calculateTimeDifference(new Date().getTime(), new Date().getTime() + duration);
        } else {
            return '12小时'
        }
    }

    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 (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]) * 60 + parseInt(list[0].split(':')[1])
        var end = parseInt(list[1].split(':')[0]) * 60 + parseInt(list[1].split(':')[1])
        if (end < start) {
            end += 24 * 60
        }
        var duration = (end - start) * 60 * 1000
        return TimeFormatter.calculateTimeDifference(new Date().getTime(), new Date().getTime() + duration);
    }

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

        </View>
    }
    return <View style={{ display: 'flex', flexDirection: 'column' }}>
        <Box>
            <View>
                <View style={{ display: 'flex', flexDirection: 'row',  marginBottom: rpxToPx(60), alignItems: 'center' }}>
                    {
                        schedule && rings()
                    }
                    {schedule && <View className="duration_bg">
                        {
                            showRing && <Text className="duration_title">{t('feature.common.day')}</Text>
                        }
                        {
                            showRing &&
                            <Text className="duration_value" style={{ color: ColorType.day }}>{dayDuration()}</Text>
                        }
                        {
                            <Text className="duration_title">{t('feature.common.eat')}</Text>
                        }
                        {
                            <Text className="duration_value" style={{ color: ColorType.food }}>{eatDuration()}</Text>
                        }
                        {
                            <Text className="duration_title">{t('feature.common.move')}</Text>
                        }
                        {
                            <Text className="duration_value" style={{ color: ColorType.activity }}>{activityDuration()}</Text>
                        }
                    </View>
                    }
                </View>
                <View className="food_btn1" style={{ backgroundColor: ColorType.food }} onClick={goFood}>
                    <Text style={{ fontWeight: 'bold' }}>食物日记</Text>
                </View>
                <View className="food_btn1" style={{ backgroundColor: ColorType.activity,marginBottom:0 }} onClick={goAcitivity}>
                    <Text style={{ fontWeight: 'bold' }}>运动训练</Text>
                </View>
            </View>
        </Box>


        <View className="cell_bg" style={{ marginTop: 20 }}>
            <View className="cell_full">
                <Text className="cell_title">{t('feature.common.day')}</Text>
                <Switch checked={showRing}
                    color={ColorType.day}
                    onChange={(e) => {
                        setShowRing(e.detail.value)
                        uploadPerm({ show_day_ring: e.detail.value })
                        Taro.setStorage({
                            key: 'showDayRing',
                            data: e.detail.value
                        })
                    }}
                />
            </View>
            {
                showRing && <View className="cell_line" style={{ height: 1 }} />
            }
            {
                showRing && <View className="cell_full">
                    <Text className="cell_title">{t('feature.track_time_duration.third_ring.sunrise_today')}</Text>
                    <Text className="cell_value" style={{ color: '#fff' }}>{
                        dayNight.isMember && dayNight.gpsInfo ? dayNight.gpsInfo.daylights[0].sunrise : '06:00'
                    }</Text>
                </View>
            }
            {
                showRing && <View className="cell_line" style={{ height: 1 }} />
            }
            {
                showRing && <View className="cell_full">
                    <Text className="cell_title">{t('feature.track_time_duration.third_ring.sunset_today')}</Text>
                    <Text className="cell_value" style={{ color: '#fff' }}>{
                        dayNight.isMember && dayNight.gpsInfo ? dayNight.gpsInfo.daylights[0].sunset : '18:00'
                    }</Text>
                </View>
            }


            {/* <View className="cell_line" style={{ height: 1 }} />
            <View className="cell_full">
                <Text className="cell_title">{t('feature.track_time_duration.third_ring.sunset_today')}</Text>
                <Text className="cell_value" style={{ color: '#fff' }}>{
                    dayNight.isMember && dayNight.gpsInfo ? dayNight.gpsInfo.daylights[0].sunset : '18:00'
                }</Text>
            </View> */}
        </View>

    </View>
}