import { useEffect, useState } from 'react'
import './DayLight.scss'
import { View, Text, Switch, Image } from '@tarojs/components'
import Taro from '@tarojs/taro'
import { useDispatch, useSelector } from 'react-redux'
import { updateMember } from '@/store/day'
import { systemLocation } from '@/services/common'
import { clearLocation, getPerm, latestLocation, uploadPerm } from '@/services/user'
import { TimeFormatter } from '@/utils/time_format'
import { ColorType } from '@/context/themes/color'
import { rpxToPx } from '@/utils/tools'
import { useTranslation } from 'react-i18next'
export default function DayLight() {
    const [showRing, setShowRing] = useState(false)
    const [isTomorrow, setIsTomorrow] = useState(false)
    const [isMember, setIsMember] = useState(false)
    const [isNight, setIsNight] = useState(false)
    const [authInfo, setAuthInfo] = useState(null)
    const [sunriseTime, setSunriseTime] = useState('06:00')
    const [sunsetTime, setSunsetTime] = useState('18:00')
    const [showLocatin, setShowLocation] = useState(true)
    const dayNight = useSelector((state: any) => state.dayNight);
    const user = useSelector((state: any) => state.user);
    const {t} = useTranslation()
    const dispatch = useDispatch();

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

    useEffect(() => {
        setIsMember(user.test_user)
        if (authInfo)
            dispatch(updateMember({ isMember: user.test_user, gpsInfo: authInfo }))
        if (user.test_user && authInfo) {
            if ((authInfo as any).daylights.length == 1) {
                setSunriseTime((authInfo as any).daylights[0].sunrise)
            }
            else {
                setSunriseTime((authInfo as any).daylights[1].sunrise)
            }

            setSunsetTime((authInfo as any).daylights[0].sunset)
        }
        else {
            setSunriseTime('06:00')
            setSunsetTime('18:00')
        }
    }, [user.test_user, authInfo])

    useEffect(() => {
        latestLocation().then(data => {
            if ((data as any).lat) {
                (data as any).latitude = (data as any).lat;
                (data as any).longitude = (data as any).lng;
                setAuthInfo(data as any)

                if ((data as any).daylights.length == 1) {
                    setSunriseTime((data as any).daylights[0].sunrise)
                }
                else {
                    setSunriseTime((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) }))
            }
        })

        if (user.isLogin) {
            getPerm({}).then(res => {
                setShowRing((res as any).show_night_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('showLightRing') || false
        setShowRing(isShow)

        const hideLocation = await getStorage('hideLocation') || false
        setShowLocation(!hideLocation)

        global.showNightRing = isShow
        global.refreshIndex()
        setTimeout(()=>{
            global.refreshIndex()
        },200)

        const gpsInfo = await getStorage('gps') || null
        if (gpsInfo) {
            setAuthInfo(JSON.parse(gpsInfo))
            dispatch(updateMember({ isMember: user.test_user, gpsInfo: JSON.parse(gpsInfo) }))
        }
        else {
            setAuthInfo(null)
        }


        checkData()
    }


    function checkData() {
        var date = new Date()
        var minutes = date.getHours() * 60 + date.getMinutes()
        var riseMinutes = parseInt(sunriseTime.split(':')[0]) * 60 + parseInt(sunriseTime.split(':')[1])
        var setMinutes = parseInt(sunsetTime.split(':')[0]) * 60 + parseInt(sunsetTime.split(':')[1])
        if (minutes >= riseMinutes && minutes < setMinutes) {
            setIsNight(false)
        }
        else {
            setIsNight(true)
        }
        if (minutes >= setMinutes) {
            setIsTomorrow(true)
        }
        else {
            setIsTomorrow(false)
        }
    }

    function buy() {
        Taro.navigateTo({
            url: '/pages/account/Member'
        })
    }

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

                systemLocation({ lat: res.latitude, lng: res.longitude, date_start: strToday, date_end: strTomorrow }).then(data => {
                    console.log(data);
                    (data as any).latitude = res.latitude;
                    (data as any).longitude = res.longitude;
                    setAuthInfo(data as any)
                    setSunriseTime((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 clearData() {
        Taro.showModal({
            title: '提示',
            content: '确认清除位置数据?',
            success: function (res) {
                if (res.confirm) {
                    clearLocation().then(res => {
                        Taro.removeStorage({ key: 'gps' })
                        setAuthInfo(null)
                        dispatch(updateMember({ isMember: user.test_user, gpsInfo: null }))
                    })
                } else if (res.cancel) {
                    console.log('用户点击取消')
                }
            }
        })
    }


    var split = new Date().toString().split(' ');
    var timezone = split[split.length - 2];



    return <View>
        <View className='cell_bg'>
            <View className='cell_full'>
                <Text className="cell_title">{t('feature.track_time_duration.third_ring.night_ring')}</Text>
                <Switch checked={showRing}
                    color={ColorType.night}
                    onChange={(e) => {
                        setShowRing(e.detail.value)
                        global.showNightRing = e.detail.value
                        global.refreshIndex()
                        Taro.setStorage({
                            key: 'showLightRing',
                            data: e.detail.value
                        })

                        uploadPerm({ show_night_ring: 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.sunset_today')}</Text>
                    <Text className="cell_value">{sunsetTime}</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.sunrise_tomorrow')}</Text>
                    <Text className="cell_value">{sunriseTime}</Text>
                </View>
            }
        </View>
        {
            showRing && <Text className='cell_footer' >{
                !isMember ? t('feature.track_time_duration.third_ring.member_desc'):
                    authInfo ? t('feature.track_time_duration.third_ring.base_location_desc'):
                    t('feature.track_time_duration.third_ring.enter_location_desc')
            }</Text>
        }
 
        {
            showRing && <View style={{marginTop:rpxToPx(40)}}>



                {/* <Text className='daylight_note'>{isMember && authInfo ? 'Calculated based on your location.' : 'Sunset and sunrise times are global average. For actual times at your location, join our Pro program.'}</Text> */}
                {
                    isMember ? <View className="cell_bg">
                        {
                            showLocatin && <View className="cell_full" onClick={auth}>
                                <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>
                                <Image className="cell_arrow" src={require('@/assets/images/arrow3.png')} />
                            </View>
                        }
                        {
                            authInfo && showLocatin && <View className="cell_line" style={{ height: 1 }} />
                        }

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

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


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

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

                            </View>
                        }
                        {
                            authInfo && showLocatin && <View className="cell_line" style={{ height: 1 }} />
                        }
                        {
                            authInfo && showLocatin && <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 className='become_vip' onClick={buy}>
                            <Text style={{ color: '#000' }}>{t('feature.common.become_pro')}</Text>
                        </View>
                }

                {
                    authInfo && <Text className='cell_footer' onClick={() => {
                        var enable = !showLocatin
                        setShowLocation(enable)
                        Taro.setStorage({
                            key: 'hideLocation',
                            data: !enable
                        })
                    }}>{showLocatin ? 'Hide my location' : 'Show my location'}</Text>
                }
                {
                    authInfo && showLocatin && user.test_user && <Text className='cell_footer' onClick={clearData}>清除位置数据</Text>
                }

            </View>
        }

    </View>

}