import { PageContainer, Switch, Text, View } from '@tarojs/components'
import './DayNightCard.scss'
import { ColorType } from '@/context/themes/color'
import { useEffect, useState } from 'react'
import Box from '@/components/layout/Box'
import Taro, { useDidShow } from '@tarojs/taro'
import { clearLocation, getPerm, latestLocation, uploadPerm } from '@/services/user'
import { useDispatch, useSelector } from 'react-redux'
import { useTranslation } from 'react-i18next'
import { TimeFormatter } from '@/utils/time_format'
import { systemLocation } from '@/services/common'
import { setDayRingData, setNightRingData, updateMember } from '@/store/day_night'
import Modal from '@/components/layout/Modal.weapp'
import { rpxToPx } from '@/utils/tools'
import { jumpPage } from '@/features/trackTimeDuration/hooks/Common'

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

let locationDetail;

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 DayNightCard(props: { isNight: boolean, switchChanged: Function }) {
    const [expand, setExpand] = useState(false)
    const user = useSelector((state: any) => state.user);
    const [authInfo, setAuthInfo] = useState(null)
    const [count, setCount] = useState(0)
    const [sunriseTime, setSunriseTime] = useState('06:00')
    const [sunriseTmrTime, setSunriseTmrTime] = useState('06:00')
    const [sunsetTime, setSunsetTime] = useState('18:00')



    const [sunriseDate, setSunriseDate] = useState<any>(sunriseA)
    const [sunriseTmrDate, setSunriseTmrDate] = useState<any>(new Date(sunriseB.getTime() + 24 * 3600 * 1000))
    const [sunsetDate, setSunsetDate] = useState<any>(sunsetA)


    const [showDetailModal, setShowDetailModal] = useState(false)
    // const [locationDetail, setLocationDetail] = useState(null)

    const [nightDate, setNightDate] = useState(new Date())
    const [dayDate, setDayDate] = useState(new Date())
    const dispatch = useDispatch();
    const { t } = useTranslation()
    let navigation;
    if (useNavigation) {
        navigation = useNavigation()
    }

    useEffect(() => {
        if (user.isLogin) {
            getPerm({}).then(res => {
                setExpand(props.isNight ? (res as any).show_night_ring : (res as any).show_day_ring)
            })

            var today = new Date()
            var yesterday = new Date(today.getTime() - 24 * 3600 * 1000)
            var tomorrow = new Date(today.getTime() + 24 * 3600 * 1000 * 3)
            var strYesterday = `${yesterday.getFullYear()}-${TimeFormatter.padZero(yesterday.getMonth() + 1)}-${TimeFormatter.padZero(yesterday.getDate())}`
            var strTomorrow = `${tomorrow.getFullYear()}-${TimeFormatter.padZero(tomorrow.getMonth() + 1)}-${TimeFormatter.padZero(tomorrow.getDate())}`
            latestLocation({
                date_start: strYesterday, date_end: strTomorrow
            }).then(data => {
                debugger
                setAuthInfo(data as any)
                updateDate(data)
                locationDetail = data
                console.log(data)
                // setLocationDetail(data as any)
            })

        }
        getContent()
    }, [user.isLogin])

    useEffect(() => {
        if (props.isNight) {
            global.clearNightLocation = () => {
                clearCacheData()
            }
        }
        else {
            global.clearDayLocation = () => {
                clearCacheData()
            }
        }
        setInterval(() => {
            setCount((prevCounter) => prevCounter + 1)

            if (locationDetail) {
                var detail: any = locationDetail
                var now = new Date()
                if (now.getHours() == 0 && now.getMinutes() == 0 && now.getSeconds() == 0) {
                    detail.daylights.splice(0, 1)
                }
                locationDetail = detail

                // setLocationDetail(detail)
                updateDate(detail)
            }
            else {
            }
        }, 1000)
    }, [])

    // useDidShow(() => {
    //     getContent()
    // })

    function updateDate(data) {

        var today = new Date()
        // var yesterday = new Date(today.getTime() - 24 * 3600 * 1000)
        var tomorrow = new Date(today.getTime() + 24 * 3600 * 1000)
        // var strYesterday = `${yesterday.getFullYear()}-${TimeFormatter.padZero(yesterday.getMonth() + 1)}-${TimeFormatter.padZero(yesterday.getDate())}`
        // var strTomorrow = `${tomorrow.getFullYear()}-${TimeFormatter.padZero(tomorrow.getMonth() + 1)}-${TimeFormatter.padZero(tomorrow.getDate())}`
        if (data && data.daylights && data.daylights.length > 0) {
            var yesterdayDate = new Date(data.daylights[0].date + 'T' + data.daylights[0].sunset)
            var todaySunriseDate = new Date(data.daylights[1].date + 'T' + data.daylights[1].sunrise)
            var todaySunsetDate = new Date(data.daylights[1].date + 'T' + data.daylights[1].sunset)
            var tomorrowSunriseDate = new Date(data.daylights[2].date + 'T' + data.daylights[2].sunrise)
            var tomorrowSunsetDate = new Date(data.daylights[2].date + 'T' + data.daylights[2].sunset)

            // var tomorrowSunsetDate = new Date(data.daylights[2].date + 'T' + data.daylights[2].sunset)
            //今天凌晨日出前
            if (yesterdayDate.getTime() < today.getTime() && today.getTime() < todaySunriseDate.getTime()) {
                setNightDate(yesterdayDate)
                setDayDate(today)
                if (props.isNight) {
                    setSunsetTime(data.daylights[0].sunset)
                    setSunriseTmrTime(data.daylights[1].sunrise)
                    setSunsetDate(yesterdayDate)
                    setSunriseTmrDate(todaySunriseDate)

                }
                else {
                    setSunriseTime(data.daylights[1].sunrise)
                    setSunsetTime(data.daylights[1].sunset)
                    setSunriseDate(todaySunriseDate)
                    setSunsetDate(todaySunsetDate)
                }

                dispatch(setNightRingData({
                    date: yesterdayDate.getTime(),
                    sunrise: data.daylights[1].sunrise,
                    sunset: data.daylights[0].sunset
                }))
                dispatch(setDayRingData({
                    date: today.getTime(),
                    sunrise: data.daylights[1].sunrise,
                    sunset: data.daylights[1].sunset
                }))
            }
            //今天白天（今天出日后-日落前）
            else if (todaySunriseDate.getTime() < today.getTime() && today.getTime() < todaySunsetDate.getTime()) {
                setNightDate(todaySunsetDate)
                setDayDate(todaySunriseDate)
                if (props.isNight) {
                    setSunsetTime(data.daylights[1].sunset)
                    setSunriseTmrTime(data.daylights[2].sunrise)
                    setSunsetDate(todaySunsetDate)
                    setSunriseTmrDate(tomorrowSunriseDate)
                }
                else {
                    setSunriseTime(data.daylights[1].sunrise)
                    setSunsetTime(data.daylights[1].sunset)
                    setSunsetDate(todaySunsetDate)
                    setSunriseDate(todaySunriseDate)
                }
                dispatch(setNightRingData({
                    date: today.getTime(),
                    sunrise: data.daylights[2].sunrise,
                    sunset: data.daylights[1].sunset
                }))
                dispatch(setDayRingData({
                    date: today.getTime(),
                    sunrise: data.daylights[1].sunrise,
                    sunset: data.daylights[1].sunset
                }))
            }
            //今天夜晚
            else if (today.getTime() > todaySunsetDate.getTime() && today.getTime() < tomorrowSunriseDate.getTime()) {
                setNightDate(todaySunsetDate)
                setDayDate(tomorrowSunriseDate)
                if (props.isNight) {
                    setSunsetTime(data.daylights[1].sunset)
                    setSunriseTmrTime(data.daylights[2].sunrise)
                    setSunsetDate(todaySunsetDate)
                    setSunriseTmrDate(tomorrowSunriseDate)
                }
                else {
                    setSunriseTime(data.daylights[2].sunrise)
                    setSunsetTime(data.daylights[2].sunset)
                    setSunriseDate(tomorrowSunriseDate)
                    setSunsetDate(tomorrowSunsetDate)
                }
                dispatch(setNightRingData({
                    date: today.getTime(),
                    sunrise: data.daylights[2].sunrise,
                    sunset: data.daylights[1].sunset
                }))
                dispatch(setDayRingData({
                    date: tomorrowSunriseDate.getTime(),
                    sunrise: data.daylights[2].sunrise,
                    sunset: data.daylights[2].sunset
                }))
            }
        }
        else {
        }

    }

    async function getContent() {
        const isShow = await getStorage(props.isNight ? 'showNightRing' : 'showDayRing') || false
        setExpand(isShow)

        const gpsInfo = await getStorage('gps') || null
        if (gpsInfo) {
            var data = JSON.parse(gpsInfo)
            setAuthInfo(data)
            setSunriseTime((data as any).daylights[0].sunrise)
            setSunriseTmrTime((data as any).daylights[1].sunrise)
            setSunsetTime((data as any).daylights[0].sunset)
            dispatch(updateMember({ isMember: user.test_user, gpsInfo: data }))
        }
        else {
            setSunriseTime('06:00')
            setSunriseTmrTime('06:00')
            setSunsetTime('18:00')
            setAuthInfo(null)
        }
        if (props.isNight) {
            global.showNightRing = isShow
            global.refreshIndex()
        }
        else {
            props.switchChanged(isShow)
        }
    }

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

    function footer() {
        return <View className='day_night_card_footer'>
            <Text style={{ color: '#9E9E9E', fontSize: rpxToPx(20) }}>{
                // !isMember ? t('feature.track_time_duration.third_ring.member_desc') :
                authInfo && (authInfo as any).lat ? t('feature.track_time_duration.third_ring.base_location_desc') :
                    t('feature.track_time_duration.third_ring.enter_location_desc')
            }</Text>
            {
                authInfo && (authInfo as any).lat && <Text style={{ color: '#9E9E9E', fontSize: rpxToPx(20) }} onClick={(e) => {
                    e.stopPropagation()
                    auth()
                }}>Edit Location</Text>
            }
        </View>
    }

    function tapCard(e) {
        if (!user.isLogin) {
            jumpPage('/pages/account/ChooseAuth', 'ChooseAuth', navigation)
            return
        }
        if (!expand) {
            return
        }
        var list = ['Current location Info',
            'Choose a new location']
        if (user.test_user) {
            list.push('clear location data')
        }
        Taro.showActionSheet({
            itemList: list
        }).then(res => {
            switch (res.tapIndex) {
                case 0:
                    setShowDetailModal(true)
                    break
                case 1:
                    auth()
                    break;
                case 2:
                    clearData()
                    break;
            }
        })
    }

    function auth() {
        Taro.chooseLocation({
            success: function (res) {
                console.log(res)
                var today = new Date()
                var yesterday = new Date(today.getTime() - 24 * 3600 * 1000)
                var tomorrow = new Date(today.getTime() + 24 * 3600 * 1000 * 3)
                var strYesterday = `${yesterday.getFullYear()}-${TimeFormatter.padZero(yesterday.getMonth() + 1)}-${TimeFormatter.padZero(yesterday.getDate())}`
                var strTomorrow = `${tomorrow.getFullYear()}-${TimeFormatter.padZero(tomorrow.getMonth() + 1)}-${TimeFormatter.padZero(tomorrow.getDate())}`

                systemLocation({ lat: res.latitude, lng: res.longitude, date_start: strYesterday, date_end: strTomorrow }).then(data => {
                    console.log(data);
                    updateDate(data);
                    locationDetail = data;
                    // setLocationDetail(data as any);
                    // (data as any).latitude = res.latitude;
                    // (data as any).longitude = res.longitude;
                    setAuthInfo(data as any)
                    setSunriseTime((data as any).daylights[0].sunrise)
                    setSunriseTmrTime((data as any).daylights[1].sunrise)
                    setSunsetTime((data as any).daylights[0].sunset)
                    Taro.setStorage({
                        key: 'gps',
                        data: JSON.stringify(data as any)
                    })
                    dispatch(updateMember({ isMember: user.test_user, gpsInfo: (data as any) }))
                })

            },
            fail(res) {
                Taro.showToast({
                    title: '位置修改失败!\n请重新选择就近位置',
                    icon: 'none'
                })
            },
        })

    }

    function getLocation() {
        if ((authInfo as any).address.city.length > 0) {
            return (authInfo as any).address.city
        }
        if ((authInfo as any).address.province.length > 0) {
            return (authInfo as any).address.province
        }
        if ((authInfo as any).address.country.length > 0) {
            return (authInfo as any).address.country
        }
        return t('feature.track_time_duration.third_ring.unknown')

    }

    function timeCount() {
        var now = new Date()
        if (props.isNight) {
            if (now.getTime() < sunriseTmrDate.getTime()) {
                return TimeFormatter.countdown(sunsetDate.getTime())
            }
            return TimeFormatter.countdown(sunsetDate.getTime())
        } else {

            if (now.getTime() < sunsetDate.getTime()) {
                return TimeFormatter.countdown(sunriseDate.getTime())
            }
            return TimeFormatter.countdown(sunriseTmrDate.getTime())


        }
    }

    function timeCount2() {
        var now = new Date()
        if (props.isNight) {

            if (now.getTime() < sunsetDate.getTime()) {
                return TimeFormatter.countdown(sunriseTmrDate.getTime())
            }
            return TimeFormatter.countdown(sunriseTmrDate.getTime())

        } else {
            return TimeFormatter.countdown(sunsetDate.getTime())
        }
    }

    function showExtraData() {
        var now = new Date()
        if (props.isNight) {
            if (sunsetDate.getTime() > now.getTime()) {
                return false
            }
            return true
        }
        if (sunriseDate.getTime() < now.getTime() && now.getTime() < sunsetDate.getTime()) {
            return true;
        }
        return false
    }

    function timeDesc() {
        var now = new Date()
        if (props.isNight) {
            var list = sunsetTime.split(':')
            var hour = parseInt(list[0])
            var min = parseInt(list[1])
            var second = list.length == 3 ? parseInt(list[2]) : 0
            now.setHours(hour)
            now.setMinutes(min)
            now.setSeconds(second)

            var sunriseDate = new Date()
            var list2 = sunriseTmrTime.split(':')
            var hour2 = parseInt(list2[0])
            var min2 = parseInt(list2[1])
            var second2 = list2.length == 3 ? parseInt(list2[2]) : 0
            sunriseDate.setHours(hour2)
            sunriseDate.setMinutes(min2)
            sunriseDate.setSeconds(second2)
            if (sunriseDate.getTime() > new Date().getTime()) {
                return 'Time past Sunset'
            }

            if (now.getTime() < new Date().getTime()) {
                return 'Time past Sunset'
            }
            return 'Time to Sunset'
        }
        else {
            var list = sunriseTime.split(':')
            var hour = parseInt(list[0])
            var min = parseInt(list[1])
            var second = list.length == 3 ? parseInt(list[2]) : 0
            now.setHours(hour)
            now.setMinutes(min)
            now.setSeconds(second)

            var sunsetDate = new Date()
            var list2 = sunsetTime.split(':')
            var hour2 = parseInt(list2[0])
            var min2 = parseInt(list2[1])
            var second2 = list2.length == 3 ? parseInt(list2[2]) : 0
            sunsetDate.setHours(hour2)
            sunsetDate.setMinutes(min2)
            sunsetDate.setSeconds(second2)

            if (new Date().getTime() > sunsetDate.getTime()) {
                return 'Time to Sunrise'
            }
            if (now.getTime() < new Date().getTime()) {
                return 'Time past Sunrise'
            }
            return 'Time to Sunrise'
        }
    }

    function timeDesc2() {
        if (props.isNight) {
            return 'Time to Sunrise'
        }
        return 'Time to Sunset'
    }

    function clearData() {
        Taro.showModal({
            title: '提示',
            content: '确认清除位置数据?',
            success: function (res) {
                if (res.confirm) {
                    clearLocation().then(res => {
                        if (global.clearNightLocation) {
                            global.clearNightLocation()
                        }
                        if (global.clearDayLocation) {
                            global.clearDayLocation()
                        }
                    })
                } else if (res.cancel) {
                    console.log('用户点击取消')
                }
            }
        })
    }





    function clearCacheData() {
        locationDetail = null
        Taro.removeStorage({ key: 'gps' })
        setAuthInfo(null)
        setSunriseTime('06:00')
        setSunriseTmrTime('06:00')
        setSunsetTime('18:00')
        dispatch(updateMember({ isMember: user.test_user, gpsInfo: null }))


        dispatch(setDayRingData({
            date: new Date().getTime(),
            sunrise: '06:00',
            sunset: '18:00'
        }))
        dispatch(setNightRingData({
            date: new Date().getTime(),
            sunrise: '06:00',
            sunset: '18:00'
        }))
    }

    function detailModalContent() {
        var split = new Date().toString().split(' ');
        var timezone = split[split.length - 2];
        if (!authInfo || !(authInfo as any).lat) {
            return <View style={{ height: 100, display: 'flex', alignItems: 'center', justifyContent: 'center', width: rpxToPx(750) }}>
                <Text>暂无位置信息</Text>
            </View>
        }
        return <View>
            {
                <View className="cell_bg">
                    {
                        <View className="cell_full">
                            <Text className="cell_title">{t('feature.track_time_duration.third_ring.location')}</Text>
                            <Text className="cell_value">{authInfo ? getLocation() : t('feature.track_time_duration.third_ring.enter')}</Text>
                        </View>
                    }
                    <View className="cell_line" style={{ height: 1 }} />


                    {
                        <View className="cell_full" >
                            <Text className="cell_title">{t('feature.track_time_duration.third_ring.latitude')}</Text>

                            <Text className="cell_value">{(authInfo as any).lat}</Text>


                        </View>
                    }
                    <View className="cell_line" style={{ height: 1 }} />

                    <View className="cell_full">
                        <Text className="cell_title" >{t('feature.track_time_duration.third_ring.longitude')}</Text>

                        <Text className="cell_value">{(authInfo as any).lng}</Text>

                    </View>
                    <View className="cell_line" style={{ height: 1 }} />
                    <View className="cell_full">
                        <Text className="cell_title">{t('feature.track_time_duration.third_ring.timezone')}</Text>

                        <Text className="cell_value">{timezone}</Text>

                    </View>



                </View>
            }
        </View>
    }

    function modalContent() {
        if (process.env.TARO_ENV == 'weapp') {
            return <Modal
                testInfo={null}
                dismiss={() => {
                    setShowDetailModal(false)
                }}
                confirm={() => { }}>
                {
                    detailModalContent()
                }
            </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={() => { setShowDetailModal(false) }}
                show={showDetailModal} round={true} overlay={true} position='bottom'
            >
                {
                    detailModalContent()
                }
            </PageContainer>
        }
    }

    function nightDurationDesc() {
        if (!authInfo || !(authInfo as any).lat) {
            if (new Date().getHours() >= 6) {
                return `Today ${sunsetTime} - Tomorrow ${sunriseTmrTime}`
            }
            return `Yesterday ${sunsetTime} - Today ${sunriseTmrTime}`
        }
        if (nightDate.getDate() == new Date().getDate()) {
            return `Today ${sunsetTime} - Tomorrow ${sunriseTmrTime}`
        }
        return `Yesterday ${sunsetTime} - Today ${sunriseTmrTime}`
    }

    function dayDurationDesc() {
        if (!authInfo || !(authInfo as any).lat) {
            if (new Date().getHours() >= 18) {
                return `Tomorrow ${sunriseTime} - ${sunsetTime}`
            }
            return `Today ${sunriseTime} - ${sunsetTime}`
        }
        if (dayDate.getDate() == new Date().getDate()) {
            return `Today ${sunriseTime} - ${sunsetTime}`
        }
        return `Tomorrow ${sunriseTime} - ${sunsetTime}`
    }



    return <View style={{ color: '#fff' }}>
        <Box onClick={tapCard}>
            <View>
                <View className='day_night_top'>
                    <Text className='day_night_title'>{props.isNight ? 'Overnight' : 'Day'}</Text>
                    <View className='free' style={{ backgroundColor: props.isNight ? ColorType.night : ColorType.day, color: props.isNight ? '#fff' : '#1C1C1C' }}>限时免费</View>
                    <View style={{ flex: 1 }} />
                    <Switch checked={expand}
                        color={props.isNight ? ColorType.night : ColorType.day}
                        onClick={(e) => { e.stopPropagation() }}
                        onChange={(e) => {
                            props.switchChanged(e.detail.value)
                            e.stopPropagation()
                            setExpand(e.detail.value)
                            if (props.isNight) {
                                global.showNightRing = e.detail.value
                                global.refreshIndex()
                            }

                            Taro.setStorage({
                                key: props.isNight ? 'showNightRing' : 'showDayRing',
                                data: e.detail.value
                            })

                            if (user.isLogin) {
                                if (props.isNight) {
                                    uploadPerm({ show_night_ring: e.detail.value })
                                }
                                else {
                                    uploadPerm({ show_day_ring: e.detail.value })
                                }
                            }


                        }}
                    />
                </View>
                {
                    expand && <View>
                        <View style={{ display: 'flex', flexDirection: 'column' }}>
                            <Text className='day_night_value' style={{ color: props.isNight ? ColorType.night : ColorType.day }}>{props.isNight ? nightDurationDesc() : dayDurationDesc()}</Text>
                            <Text className='day_night_desc'>{props.isNight ? 'Sunset to Sunrise' : 'Sunrise to Sunset'}</Text>
                            <View style={{ display: 'flex', flexDirection: 'row', marginTop: rpxToPx(32) }}>
                                <View style={{ display: 'flex', flexDirection: 'column', width: rpxToPx(300) }}>
                                    <Text className='day_night_value' style={{ color: props.isNight ? ColorType.night : ColorType.day }}>{timeCount()}</Text>
                                    <Text className='day_night_desc'>{timeDesc()}</Text>
                                </View>
                                {
                                    showExtraData() && <View style={{ display: 'flex', flexDirection: 'column', width: rpxToPx(300) }}>
                                        <Text className='day_night_value' style={{ color: props.isNight ? ColorType.night : ColorType.day, opacity: 0.6 }}>{timeCount2()}</Text>
                                        <Text className='day_night_desc'>{timeDesc2()}</Text>
                                    </View>
                                }
                            </View>

                        </View>
                        {
                            footer()
                        }
                    </View>
                }

            </View>
        </Box>
        {
            showDetailModal && modalContent()
        }
    </View>
}