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, 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 { updateMember } from '@/store/day_night'
import Modal from '@/components/layout/Modal.weapp'
import { rpxToPx } from '@/utils/tools'

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 [showDetailModal, setShowDetailModal] = useState(false)
    const dispatch = useDispatch();
    const { t } = useTranslation()

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

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

    useEffect(() => {
        setInterval(() => {
            setCount((prevCounter) => prevCounter + 1)
        }, 1000)
    }, [])

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

    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 ? t('feature.track_time_duration.third_ring.base_location_desc') :
                    t('feature.track_time_duration.third_ring.enter_location_desc')
            }</Text>
        </View>
    }

    function tapCard(e) {
        if (!user.isLogin) {
            return
        }
        Taro.showActionSheet({
            itemList: [
                'Current location Info',
                'Choose a new location',
                'clear location data'
                //t('feature.track_time_duration.action_sheet.switch_scenario'),
                //t('feature.track_time_duration.action_sheet.change_schedule')
            ]
        }).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 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[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) {
            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)
            return TimeFormatter.countdown(now.getTime())
        } 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)
            return TimeFormatter.countdown(now.getTime())
        }
    }

    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)
            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)
            if (now.getTime() < new Date().getTime()) {
                return 'Time past Sunrise'
            }
            return 'Time to Sunrise'
        }
    }

    function clearData() {
        Taro.showModal({
            title: '提示',
            content: '确认清除位置数据?',
            success: function (res) {
                if (res.confirm) {
                    clearLocation().then(res => {
                        Taro.removeStorage({ key: 'gps' })
                        setAuthInfo(null)
                        setSunriseTime('06:00')
                        setSunriseTmrTime('06:00')
                        setSunsetTime('18:00')
                        dispatch(updateMember({ isMember: user.test_user, gpsInfo: null }))
                    })
                } else if (res.cancel) {
                    console.log('用户点击取消')
                }
            }
        })
    }

    function detailModalContent() {
        var split = new Date().toString().split(' ');
        var timezone = split[split.length - 2];
        if (!authInfo) {
            return <View>
                <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).latitude}</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).longitude}</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>
        }
    }

    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'>限时免费</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>
                <View style={{ display: 'flex', flexDirection: 'column' }}>
                    <Text style={{ color: props.isNight ? ColorType.night : ColorType.day }}>{props.isNight ? `Today ${sunsetTime} - Tomorrow ${sunriseTmrTime}` : `${sunriseTime} - ${sunsetTime}`}</Text>
                    <Text>{props.isNight ? 'Sunset to Sunrise' : 'Sunrise to Sunset'}</Text>
                    <Text style={{ color: props.isNight ? ColorType.night : ColorType.day }}>{timeCount()}</Text>
                    <Text>{timeDesc()}</Text>
                </View>
                {
                    footer()
                }
            </View>
        </Box>
        {
            showDetailModal && modalContent()
        }
    </View>
}