import { PageContainer, Switch, Text, View, Image } 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, showDay } from '@/store/day'
import { setNightRingData, showNight, updateMember } from '@/store/night'
import Modal from '@/components/layout/Modal.weapp'
import { getTimezone, rpxToPx } from '@/utils/tools'
import { jumpPage } from '@/features/trackTimeDuration/hooks/Common'
import DayNightDetailPopup from './DayNightDetailPopup'
import '@/utils/ring_card.scss';
import { IconNight, IconSunrise, IconSunset } from '@/components/basic/Icons'
import DayNightRing from './DayNightRing'
import dayjs from 'dayjs'
import DayNightStatus from './DayNightStatus'
import showAlert from '@/components/basic/Alert'
// import checkLocation from '@/utils/native_permission_check'

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

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 utc = require('dayjs/plugin/utc')
const timezone = require('dayjs/plugin/timezone')
var advanced = require("dayjs/plugin/advancedFormat")

dayjs.extend(utc)
dayjs.extend(timezone)
dayjs.extend(advanced)


let noTimestampData = false;
export default function DayNightCard(props: { isNight: boolean, count: number, detailPop?: Function }) {
    const user = useSelector((state: any) => state.user);
    const dayStore = useSelector((state: any) => state.day);
    const nightStore = useSelector((state: any) => state.night);
    const [authInfo, setAuthInfo] = useState(global.locationDetail ? global.locationDetail : null)

    const [sunriseDate, setSunriseDate] = useState<any>(sunriseA)
    const [sunsetDate, setSunsetDate] = useState<any>(sunsetA)


    const [showDetailModal, setShowDetailModal] = useState(false)
    const [showDetailPopup, setShowDetailPopup] = useState(false)

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

    useEffect(() => {
        if (user.isLogin) {
            if (global.locationDetail) {
                locationDetail = global.locationDetail

                setAuthInfo(locationDetail)
            }

            getLatestLocation()

            if (props.isNight) {
                global.refreshNight = () => {
                    getLatestLocation()
                }
            }
            else {
                global.refreshDay = () => {
                    getLatestLocation()
                }
            }

        } else {
            setSunriseDate(sunriseA)
            setSunsetDate(sunsetA)

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

            setAuthInfo(null)
            global.locationDetail = null
            updateUnloginData()
        }
    }, [user.isLogin])

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

    useEffect(() => {
        if (locationDetail)
            updateDate(locationDetail)
    }, [])

    useEffect(() => {
        if (!locationDetail && global.locationDetail){
            locationDetail = global.locationDetail
        }
        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

            if (detail && (detail as any).daylights) {
                (detail as any).daylights.map(item => {
                    if (noTimestampData) {
                        item.sunrise_ts = new Date(item.date + 'T' + item.sunrise + ':00').getTime()
                        item.sunset_ts = new Date(item.date + 'T' + item.sunset + ':00').getTime()
                    }
                })
            }


            // setLocationDetail(detail)
            updateDate(detail)
        }
    }, [props.count])

    useDidShow(() => {
        if (!user.isLogin) {
            dispatch(showNight(false))
            dispatch(showDay(false))
            Taro.setStorage({
                key: 'showNightRing',
                data: false
            })
            Taro.setStorage({
                key: 'showDayRing',
                data: false
            })
        }
    })

    function getLatestLocation() {
        var today = new Date()
        var yesterday = new Date(today.getTime() - 24 * 3600 * 1000)
        var tomorrow = new Date(today.getTime() + 24 * 3600 * 1000 * 50)
        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 => {
            // (data as any).timezone = 'GMT-1000'
            if (data && (data as any).daylights) {
                (data as any).daylights.map(item => {
                    if (!item.sunrise_ts) {
                        noTimestampData = true
                        item.sunrise_ts = new Date(item.date + 'T' + item.sunrise + ':00').getTime()
                        item.sunset_ts = new Date(item.date + 'T' + item.sunset + ':00').getTime()
                    }
                    else {
                        noTimestampData = false
                    }
                })
            }
            setAuthInfo(data as any)
            updateDate(data)
            locationDetail = data
            global.locationDetail = locationDetail
            Taro.setStorage({
                key: 'gps',
                data: JSON.stringify(data as any)
            })
        })
    }

    function updateDate(data) {
        var today = new Date()
        if (user.isLogin && isMember && data && data.daylights && data.daylights.length > 0) {
            // var sunriseObj,sunsetObj;
            var list = data.daylights
            for (var i = 0; i < (list.length - 1); i++) {
                //夜间
                if (list[i].sunset_ts < today.getTime() && list[i + 1].sunrise_ts > today.getTime()) {
                    if (props.isNight) {
                        global.nightObj = {
                            is_polar_night: list[i].is_polar_night,
                            sunrise: {
                                timestamp: list[i + 1].sunrise_ts,
                                time: list[i + 1].sunrise
                            },
                            sunset: {
                                timestamp: list[i].sunset_ts,
                                time: list[i].sunset
                            }
                        }
                    }
                    else {
                        global.dayObj = {
                            is_polar_day: list[i + 1].is_polar_day,
                            sunrise: {
                                timestamp: list[i + 1].sunrise_ts,
                                time: list[i + 1].sunrise
                            },
                            sunset: {
                                timestamp: list[i + 1].sunset_ts,
                                time: list[i + 1].sunset
                            }
                        }
                    }
                }
                //白天
                else if (list[i].sunrise_ts < today.getTime() && list[i].sunset_ts > today.getTime()) {
                    if (props.isNight) {
                        global.nightObj = {
                            is_polar_night: list[i].is_polar_night,
                            sunrise: {
                                timestamp: list[i + 1].sunrise_ts,
                                time: list[i + 1].sunrise
                            },
                            sunset: {
                                timestamp: list[i].sunset_ts,
                                time: list[i].sunset
                            }
                        }
                    }
                    else {
                        global.dayObj = {
                            is_polar_day: list[i].is_polar_day,
                            sunrise: {
                                timestamp: list[i].sunrise_ts,
                                time: list[i].sunrise
                            },
                            sunset: {
                                timestamp: list[i].sunset_ts,
                                time: list[i].sunset
                            }
                        }
                    }
                }
            }
        }
        else {
            locationDetail = null
            setAuthInfo(null)
            dispatch(updateMember({ isMember: isMember, gpsInfo: null }))

            dispatch(setDayRingData({
                date: sunriseDate.getTime(),
                sunrise: '06:00',
                sunset: '18:00'
            }))
            dispatch(setNightRingData({
                date: sunsetDate.getTime(),
                sunrise: '06:00',
                sunset: '18:00'
            }))
            debugger
            updateUnloginData()

        }

    }

    function updateUnloginData() {
        var now = new Date()
        var sunriseT = 0
        var sunsetT = 0
        var sunriseTDay = 0
        var sunsetTDay = 0
        if (now.getHours() < 6) {
            var temp1 = new Date(now.getTime() - 24 * 3600 * 1000)
            temp1.setHours(18)
            temp1.setMinutes(0)
            temp1.setSeconds(0)
            temp1.setMilliseconds(0)
            sunsetT = temp1.getTime()
            sunriseT = sunsetT + 12 * 3600 * 1000
            sunriseTDay = sunriseT
            sunsetTDay = sunriseTDay + 12 * 3600 * 1000
        }
        else if (now.getHours() < 18) {
            var temp1 = new Date()
            temp1.setHours(6)
            temp1.setMinutes(0)
            temp1.setSeconds(0)
            temp1.setMilliseconds(0)

            sunriseTDay = temp1.getTime()
            sunsetTDay = sunriseTDay + 12 * 3600 * 1000
            sunsetT = sunsetTDay
            sunriseT = sunsetT + 12 * 3600 * 1000
        }
        else {
            var temp1 = new Date()
            temp1.setHours(18)
            temp1.setMinutes(0)
            temp1.setSeconds(0)
            temp1.setMilliseconds(0)
            sunsetT = temp1.getTime()
            sunriseT = sunsetT + 12 * 3600 * 1000
            sunriseTDay = sunriseT
            sunsetTDay = sunriseTDay + 12 * 3600 * 1000
        }
        global.nightObj = {
            sunrise: {
                timestamp: sunriseT,
                time: '06:00'
            },
            sunset: {
                timestamp: sunsetT,
                time: '18:00'
            }
        }

        global.dayObj = {
            sunrise: {
                timestamp: sunriseTDay,
                time: '06:00'
            },
            sunset: {
                timestamp: sunsetTDay,
                time: '18:00'
            }
        }
    }


    function tapCard(e) {
        // if (process.env.TARO_ENV == 'weapp') {
        //     e.stopPropagation()
        // }
        if (!user.isLogin) {
            jumpPage('/pages/account/ChooseAuth', 'ChooseAuth', navigation)
            return
        }
        global.showDayNightSwiperPop(props.isNight, nightDate, dayDate)
        // if (!dayStore.showDayRing) {
        //     return
        // }
        // setShowDetailPopup(true)
        // if (props.detailPop)
        //     props.detailPop(props.isNight, nightDate, dayDate)
    }

    function auth(e?: any) {
        if (e && process.env.TARO_ENV == 'weapp') {
            e.stopPropagation()
        }
        var today = new Date()
        var yesterday = new Date(today.getTime() - 24 * 3600 * 1000)
        var tomorrow = new Date(today.getTime() + 24 * 3600 * 1000 * 5)
        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 (process.env.TARO_ENV == 'rn') {
            Taro.getLocation({
                success(res) {
                    systemLocation({
                        lat: res.latitude,
                        lng: res.longitude,
                        date_start: strYesterday,
                        date_end: strTomorrow,
                        coordinate_system_standard: 'WGS-84'
                    }).then(data => {
                        noTimestampData = false
                        console.log('get Location', data)
                        updateDate(data);
                        locationDetail = data;
                        global.locationDetail = locationDetail
                        setAuthInfo(data as any)
                        Taro.setStorage({
                            key: 'gps',
                            data: JSON.stringify(data as any)
                        })
                        dispatch(updateMember({ isMember: isMember, gpsInfo: (data as any) }))
                        showRing()
                        if (Taro.getSystemInfoSync().platform == 'android' && process.env.TARO_ENV == 'rn') {
                            var ToastAndroid = require('react-native').ToastAndroid;
                            ToastAndroid.show(t('feature.day_night.location_updated'), ToastAndroid.LONG);
                        }
                        else {
                            showAlert({
                                title:'Success',
                                content:t('feature.day_night.location_updated'),
                                showCancel:false
                            })
                            // Taro.showToast({
                            //     title: t('feature.day_night.location_updated'),
                            //     icon: 'none'
                            // })
                        }

                    })
                },
                fail(res) {
                    if (res.errMsg == 'Permissions denied!') {
                        showAlert({
                            title: t('feature.auth_sys.location_title'),
                            content: t('feature.auth_sys.location_desc'),
                            showCancel: true,
                            cancelText: t('feature.auth_sys.location_cancel'),
                            confirmText: t('feature.auth_sys.location_confirm'),
                            confirm: () => {
                                Linking.openURL('app-settings:')
                            }
                        })
                    }
                    else {
                        if (Taro.getSystemInfoSync().platform == 'android' && process.env.TARO_ENV == 'rn') {
                            var ToastAndroid = require('react-native').ToastAndroid;
                            ToastAndroid.show(t('feature.day_night.location_failed'), ToastAndroid.LONG);
                        }
                        else {
                            showAlert({
                                title:'Error',
                                content:t('feature.day_night.location_failed'),
                                showCancel:false
                            })
                            // Taro.showToast({
                            //     title: t('feature.day_night.location_failed'),
                            //     icon: 'none'
                            // })
                        }
                    }
                    console.log(res)
                    showRing()
                },
                complete(res) {

                }
            })
            return
        }
        Taro.chooseLocation({
            latitude: authInfo && authInfo.lat ? authInfo.lat : undefined,
            longitude: authInfo && authInfo.lat ? authInfo.lng : undefined,
            success: function (res) {

                systemLocation({
                    lat: res.latitude,
                    lng: res.longitude,
                    name: res.name,
                    address: res.address,
                    date_start: strYesterday,
                    date_end: strTomorrow,
                    coordinate_system_standard: 'GCJ-02'
                }).then(data => {
                    noTimestampData = false;
                    updateDate(data);
                    locationDetail = data;
                    global.locationDetail = locationDetail
                    setAuthInfo(data as any)
                    Taro.setStorage({
                        key: 'gps',
                        data: JSON.stringify(data as any)
                    })
                    showRing()
                    dispatch(updateMember({ isMember: isMember, gpsInfo: (data as any) }))

                    if (global.swiperDayNightRefresh) {
                        global.swiperDayNightRefresh()
                    }
                })

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

            }
        })

    }

    function showRing() {
        dispatch(showNight(true))
        dispatch(showDay(true))
        Taro.setStorage({
            key: 'showNightRing',
            data: true
        })
        Taro.setStorage({
            key: 'showDayRing',
            data: true
        })
    }

    function getLocation() {
        if (!authInfo) {
            return ''
        }
        return `${getCity()} | ${Math.abs(parseInt(authInfo.lat))}°${parseInt(authInfo.lat) < 0 ? 'S' : 'N'} ${Math.abs(parseInt(authInfo.lng))}°${parseInt(authInfo.lng) < 0 ? 'W' : 'E'}`
    }

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

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

    function detailModalContent() {
        var timezone = getTimezone()
        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 style={{ display: 'flex', flexDirection: 'column' }}>
            {
                <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>

            }

            <Text onClick={() => {
                clearData()
                setShowDetailModal(false)
            }} style={{ width: '100%', textAlign: 'center', marginBottom: 50, color: '#fff', marginTop: 20 }}>清除位置</Text>
        </View>
    }

    function modalContent2() {
        return <Modal
            testInfo={null}
            dismiss={() => {
                setShowDetailModal(false)
            }}
            confirm={() => { }}>
            {
                detailModalContent()
            }
        </Modal>
    }

    function modalContent() {
        return <Modal
            testInfo={null}
            dismiss={() => {
                setShowDetailPopup(false)
            }}
            confirm={() => { }}>
            <DayNightDetailPopup
                isNight={props.isNight}
                authInfo={authInfo}
                nightDate={nightDate}
                dayDate={dayDate}
                updateLocation={auth}
                onClose={() => { setShowDetailPopup(false) }}
            />
        </Modal>
    }


    function longClick() {
        if (user.isLogin && user.test_user && authInfo)
            global.showDayNightSwiperModal()
        // setShowDetailModal(true)
    }

    function showLocationAlert(e) {
        if (process.env.TARO_ENV == 'weapp') {
            e.stopPropagation()
        }
        tapCard(e)
    }

    function nightRing() {
        return <DayNightRing
            isNight={true}
            isThirdRing={false}
            canvasId={'day_night_card_night_ring'}
            authInfo={authInfo}
        />
    }

    function localNow(now: Date) {
        if (authInfo && authInfo.timezone) {
            return new Date(TimeFormatter.transferTimestamp(now.getTime(), authInfo.timezone.gmt))
        }
        return now
    }

    function dayRing() {
        return <DayNightRing
            isNight={false}
            isThirdRing={false}
            canvasId={'day_night_card_big_day'}
            authInfo={authInfo}
        />
    }

    function getSunsetDuration() {

        if (authInfo && authInfo.night_completed && new Date().getTime() > authInfo.night_completed.sunrise_ts) {
            global.sunsetDuration = TimeFormatter.durationFormate(authInfo.night_completed.sunrise_ts, authInfo.night_completed.sunset_ts, true)
            return TimeFormatter.durationFormate(authInfo.night_completed.sunrise_ts, authInfo.night_completed.sunset_ts, true)
        }

        var now = new Date()
        if (authInfo && global.nightObj) {
            var nightObj = global.nightObj
            if (nightObj.sunset.timestamp < now.getTime() && nightObj.sunrise.timestamp > now.getTime()) {
                global.sunsetDuration = TimeFormatter.countdown(nightObj.sunset.timestamp, now.getTime(), true)
                return TimeFormatter.countdown(nightObj.sunset.timestamp, now.getTime(), true)
            }
            global.sunsetDuration = TimeFormatter.calculateTimeDifference(nightObj.sunset.timestamp, nightObj.sunrise.timestamp);
            return TimeFormatter.calculateTimeDifference(nightObj.sunset.timestamp, nightObj.sunrise.timestamp);
        }

        now = localNow(now)
        if (props.isNight && sunsetDate) {
            if (now.getTime() > sunsetDate.getTime()) {
                global.sunsetDuration = TimeFormatter.countdown(sunsetDate.getTime(), now.getTime(), true)
                return TimeFormatter.countdown(sunsetDate.getTime(), now.getTime(), true)
            }
            // return TimeFormatter.countdown(sunsetDate.getTime())
        }


        var sunRiseObj = nightStore.nightRingSunrise
        var sunSetObj = nightStore.nightRingSunset
        var sunRise = 24 * 60 + 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 = (sunRise - sunSet) * 60 * 1000
        global.sunsetDuration = TimeFormatter.calculateTimeDifference(now.getTime(), now.getTime() + duration);
        return TimeFormatter.calculateTimeDifference(now.getTime(), now.getTime() + duration);
    }

    function getSunriseDuration() {
        if (authInfo && authInfo.day_completed && new Date().getTime() > authInfo.day_completed.sunset_ts) {
            global.sunriseDuration = TimeFormatter.durationFormate(authInfo.day_completed.sunrise_ts, authInfo.day_completed.sunset_ts, true)
            return TimeFormatter.durationFormate(authInfo.day_completed.sunrise_ts, authInfo.day_completed.sunset_ts, true)
        }

        var now = new Date()
        var now = new Date()
        if (global.dayObj) {
            var dayObj = global.dayObj
            if (dayObj.sunrise.timestamp < now.getTime() && dayObj.sunset.timestamp > now.getTime()) {
                global.sunriseDuration = TimeFormatter.countdown(dayObj.sunrise.timestamp, now.getTime(), true)
                return TimeFormatter.countdown(dayObj.sunrise.timestamp, now.getTime(), true)
            }
            global.sunriseDuration = TimeFormatter.calculateTimeDifference(dayObj.sunrise.timestamp, dayObj.sunset.timestamp, true);
            return TimeFormatter.calculateTimeDifference(dayObj.sunrise.timestamp, dayObj.sunset.timestamp, true);
        }
        return ''




        // now = localNow(now)
        // if (!props.isNight && sunriseDate) {
        //     if (now.getTime() > sunriseDate.getTime()) {
        //         global.sunriseDuration = TimeFormatter.countdown(sunriseDate.getTime())
        //         return TimeFormatter.countdown(sunriseDate.getTime(), now.getTime())
        //     }
        // }


        // var sunRiseObj = dayStore.dayRingSunrise
        // var sunSetObj = dayStore.dayRingSunset
        // 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
        // global.sunriseDuration = TimeFormatter.calculateTimeDifference(now.getTime(), now.getTime() + duration);
        // return TimeFormatter.calculateTimeDifference(now.getTime(), now.getTime() + duration);
    }

    function completedDate() {
        if (props.isNight) {
            if (authInfo && authInfo.night_completed && new Date().getTime() > authInfo.night_completed.sunrise_ts) {
                if (localNow(new Date()).getTime() != new Date().getTime()) {
                    return TimeFormatter.getMonthAndDayByTimestamp(authInfo.night_completed.sunrise_ts, true)
                }
                return TimeFormatter.dateDescription(authInfo.night_completed.sunrise_ts, true)
            }
            return ''
        }
        if (authInfo && authInfo.day_completed && new Date().getTime() > authInfo.day_completed.sunset_ts) {
            if (localNow(new Date()).getTime() != new Date().getTime()) {
                return TimeFormatter.getMonthAndDayByTimestamp(authInfo.day_completed.sunset_ts, true)
            }
            return TimeFormatter.dateDescription(authInfo.day_completed.sunset_ts, true)
        }
        return ''
    }

    function showArrow() {
        if (props.isNight) {
            if (authInfo && authInfo.night_completed && new Date().getTime() > authInfo.night_completed.sunrise_ts) {
                return true
            }
            return false
        }
        if (authInfo && authInfo.day_completed && new Date().getTime() > authInfo.day_completed.sunset_ts) {
            return true
        }
        return false
    }

    function currentStatus() {
        if (showArrow()) {
            if (props.isNight) {
                if (authInfo.day_completed && new Date().getTime() > authInfo.day_completed.sunset_ts) {
                    return t('feature.day_night.last_updated')
                }
                return t('feature.day_night.ended')
            }
            return t('feature.day_night.last_updated')
        }
        var strTime = props.isNight ? getSunsetDuration() : getSunriseDuration()
        return (strTime.indexOf('小时') != -1 || strTime.indexOf('分钟') != -1) ? t('feature.day_night.upcoming') : t('feature.day_night.in_real_time')
    }

    function footerDesc() {
        var now = new Date()
        if (props.isNight) {
            if (global.nightObj) {
                if (now.getTime() < global.nightObj.sunset.timestamp) {
                    return TimeFormatter.countdown(global.nightObj.sunset.timestamp, now.getTime(), true)
                }
                return TimeFormatter.countdown(global.nightObj.sunrise.timestamp, now.getTime(), true)
            }
        }
        else {
            if (global.dayObj) {
                if (now.getTime() < global.dayObj.sunrise.timestamp) {
                    return TimeFormatter.countdown(global.dayObj.sunrise.timestamp, now.getTime(), true)
                }
                return TimeFormatter.countdown(global.dayObj.sunset.timestamp, now.getTime(), true)
            }
        }

        return ''
    }

    function footerIcon() {
        var now = new Date()
        if (props.isNight) {
            if (now.getTime() < sunsetDate.getTime()) {
                return <IconSunset color={ColorType.white + '66'} width={rpxToPx(28)} />

            }
            return <IconSunrise color={ColorType.white + '66'} width={rpxToPx(28)} />
        }

        if (now.getTime() > sunriseDate.getTime() && now.getTime() < sunsetDate.getTime()) {

            return <IconSunset color={ColorType.white + '66'} width={rpxToPx(28)} />
        }
        return <IconSunrise color={ColorType.white + '66'} width={rpxToPx(28)} />

    }

    function currentTime() {
        var now = new Date()
        if (authInfo && authInfo.timezone) {
            var t1 = TimeFormatter.tzLocalTime(now.getTime(), authInfo.timezone.id)////dayjs(now.getTime()).tz(authInfo.timezone.id)
            if (now.getHours() == t1.hour() && now.getMinutes() == t1.minute()) {
                return <View />
            }
        }

        var now2 = localNow(now)
        if (now.getTime() == now2.getTime()) {
            return ''
        }
        let offset = 0;
        if (authInfo && authInfo.timezone) {
            var current1 = dayjs()
            var current = TimeFormatter.tzLocalTime(now.getTime(), authInfo.timezone.id)//dayjs().tz(authInfo.timezone.id)
            offset = current.date() * 24 * 60 + current.hour() * 60 + current.minute() - current1.date() * 24 * 60 - current1.hour() * 60 - current1.minute()
        }
        var hour = Math.floor(Math.abs(offset) / 60)
        var minute = Math.abs(offset) % 60
        var time = ''
        if (global.language == 'en') {
            time = `${hour} h`
            if (minute > 0) {
                time += ` ${minute} m`
            }
        }
        else {
            time = `${hour}小时`
            if (minute > 0) {
                time += `${minute}分钟`
            }
        }
        // const ccc = dayjs().tz('Arctic/Longyearbyen').format('YYYY-MM-DD HH:mm:ss')
        // const current = dayjs().utcOffset(offset).format('YYYY-MM-DD HH:mm:ss')
        var current;
        if (authInfo && authInfo.timezone) {
            current = TimeFormatter.tzTimeFormateLocalTime(new Date().getTime(), authInfo.timezone.id, 'HH:mm')//dayjs().tz(authInfo.timezone.id).format('HH:mm')
        }
        else {
            current = dayjs().format('HH:mm')
        }

        return <View style={{ display: 'flex', flexDirection: 'column', alignItems: 'center' }}>
            <Text className='ring_city' numberOfLines={1}>{getCity()}</Text>
            <Text className='ring_clock' style={{ color: props.isNight ? ColorType.night : ColorType.day }}>{current}</Text>
            <Text className='ring_timezone'>{
                offset > 0 ? t('feature.day_night.ahead_desc', { time: time }) : t('feature.day_night.behind_desc', { time: time })
            }</Text>
        </View>
    }

    function cardContent() {
        return <View style={{ position: 'relative' }}>
            <View style={{ display: 'flex', flexDirection: 'column', zIndex: 1 }} onClick={showLocationAlert} onLongPress={longClick}>
                <View className="ring_full_container" style={{ paddingBottom: 0 }}>
                    <View style={{
                        display: 'flex',
                        flexDirection: 'row',
                        marginTop: 0,
                        marginBottom: 0,
                        padding: 0,
                        alignItems: 'center'
                    }}>
                        <View style={{ display: 'flex', position: 'relative' }}>
                            {
                                props.isNight ? nightRing() : dayRing()
                            }
                            <View style={{ color: '#fff', position: 'absolute', left: 0, right: 0, top: 0, bottom: 0, alignItems: 'center', justifyContent: 'center', display: 'flex' }}>{currentTime()}</View>
                        </View>
                        <View style={{ display: 'flex', flexDirection: 'column', flexShrink: 0, flex: 1, marginLeft: rpxToPx(52) }}>
                            <View style={{ display: 'flex', flexDirection: 'row', alignItems: 'center' }}>
                                <Text className='ring_card_duration_title'>{props.isNight ? t('feature.common.overnight') : t('feature.common.day')}</Text>
                                {
                                    !props.isNight && global.dayObj && global.dayObj.is_polar_day && <View className='polar_tag'>{t('feature.day_night.polar_day')}</View>
                                }
                                {
                                    props.isNight && global.nightObj && global.nightObj.is_polar_night && <View className='polar_tag'>{t('feature.day_night.polar_night')}</View>
                                }
                            </View>

                            <Text className='ring_card_duration_value' style={{ color: props.isNight ? ColorType.night : ColorType.day }}>{props.isNight ? getSunsetDuration() : getSunriseDuration()}</Text>

                        </View>
                        {/* {
                        !showArrow() && <Image className="card_arrow2" src={require('@/assets/images/arrow3.png')} />
                    } */}
                        <View className='day_card_header'>
                            {
                                props.isNight && global.nightObj && <DayNightStatus
                                    authInfo={authInfo}
                                    isNight={props.isNight}
                                    sunrise_ts={global.nightObj.sunrise.timestamp}
                                    sunset_ts={global.nightObj.sunset.timestamp}
                                />
                            }
                            {
                                !props.isNight && global.dayObj && <DayNightStatus
                                    authInfo={authInfo}
                                    isNight={props.isNight}
                                    sunrise_ts={global.dayObj.sunrise.timestamp}
                                    sunset_ts={global.dayObj.sunset.timestamp}
                                />
                            }
                        </View>
                        <Image className="card_arrowaaa"
                                style={{ backgroundColor: global.isDebug ? 'blue' : 'transparent' }}
                                src={require('@/assets/images/arrow3.png')} />
                        {/* <View className='day_night_card_footer1' style={{ backgroundColor: global.isDebug ? 'red' : 'transparent' }}>
                            {
                                !showArrow() && <View className='footer_sun_icon_bg' style={{ backgroundColor: global.isDebug ? 'pink' : 'transparent' }}>
                                    {
                                        footerIcon()
                                    }
                                </View>
                            }
                            <Text className='footer_desc_text' style={{ backgroundColor: global.isDebug ? 'black' : 'transparent' }}>{showArrow() ? completedDate() : footerDesc()}</Text>
                            <Image className="card_arrowaaa"
                                style={{ backgroundColor: global.isDebug ? 'blue' : 'transparent' }}
                                src={require('@/assets/images/arrow3.png')} />
                        </View> */}
                    </View>
                </View>
            </View>
            {
                showDetailPopup && modalContent()
            }
            {
                showDetailModal && modalContent2()
            }
        </View>
    }

    function detail() {
        return <View>
            {cardContent()}
            <View className='day_night_card_footer_btn'
                onClick={(e) => {
                    if (process.env.TARO_ENV == 'weapp') {
                        e.stopPropagation()
                    }
                    if (props.isNight) {
                        global.tapShowThirdRing(false)
                    }
                    else {
                        global.tapShowThirdRing(true)
                    }
                }}
                style={{ backgroundColor: props.isNight ? ColorType.night : ColorType.day }}>
                <Text style={{ color: props.isNight ? ColorType.white : ColorType.black, fontWeight: 'bold' }}>{t('feature.day_night.sync')}</Text>
            </View>
        </View>
    }

    return process.env.TARO_ENV == 'weapp' ? <Box style={{marginBottom:0}}>{detail()}</Box> :
        <View className='rn_card_bg'>{detail()}</View>
}