import { PageContainer, Switch, Text, View, Image } from '@tarojs/components'
import Modal from '@/components/layout/Modal.weapp'
import { useEffect, useState } from 'react'
import DayNightDetailPopup from './DayNightDetailPopup'
import { useTranslation } from 'react-i18next'
import Taro from '@tarojs/taro'
import { systemLocation } from '@/services/common'
import showAlert from '@/components/basic/Alert'
import { getTimezone, rpxToPx } from '@/utils/tools'
import { clearLocation } from '@/services/user'
import { TimeFormatter } from '@/utils/time_format'


let Linking;
if (process.env.TARO_ENV == 'rn') {
    // useNavigation = require("@react-navigation/native").useNavigation
    Linking = require('react-native').Linking;
}
export default function DayNightSwiperPopup(props: { authInfo: any }) {
    const [showDetailModal, setShowDetailModal] = useState(false)
    const [showDetailPopup, setShowDetailPopup] = useState(false)
    const [authInfo, setAuthInfo] = useState<any>(props.authInfo)
    const [dayDate, setDayDate] = useState<any>('')
    const [nightDate, setNightDate] = useState<any>('')
    const [isNight, setIsNight] = useState(false)

    useEffect(() => {
        setAuthInfo(props.authInfo)
    }, [props.authInfo])

    const { t } = useTranslation()

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

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

    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 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>{t('feature.location.no_location')}</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 }}>{t('feature.location.clear_info')}</Text>
        </View>
    }

    function clearData() {
        showAlert({
            title:t('feature.location.clear_alert_title'),
            content:t('feature.location.clear_alert_content'),
            cancelText:t('feature.location.clear_alert_cancel'),
            confirmText:t('feature.location.clear_alert_confirm'),
            showCancel:true,
            confirm:()=>{
                clearLocation().then(res => {
                    global.swiperDayNightRefresh()
                    global.refreshNight()
                    global.refreshDay()
                })
            }
        })
    }

    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 => {
                        global.swiperDayNightRefresh()
                        global.refreshNight()
                        global.refreshDay()
                        // updateDate(data);
                        global.locationDetail = data
                        setAuthInfo(data as any)
                        Taro.setStorage({
                            key: 'gps',
                            data: JSON.stringify(data as any)
                        })
                        // dispatch(updateMember({ isMember: isMember, gpsInfo: (data as any) }))
                        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_updated'),
                                showCancel: false
                            })
                            // Taro.showToast({
                            //     title: t('feature.day_night.location_failed'),
                            //     icon: 'none'
                            // })
                        }
                    }
                    console.log(res)
                },
                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 => {
                    // updateDate(data);
                    global.locationDetail = data
                    setAuthInfo(data as any)
                    Taro.setStorage({
                        key: 'gps',
                        data: JSON.stringify(data as any)
                    })
                    // dispatch(updateMember({ isMember: isMember, gpsInfo: (data as any) }))

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

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

            }
        })

    }

    global.showDayNightSwiperPop = (isNight, strNight, strDay) => {
        setNightDate(strNight)
        setDayDate(strDay)
        setIsNight(isNight)
        setShowDetailPopup(true)
    }

    global.showDayNightSwiperModal = () => {
        setShowDetailModal(true)
    }

    return <View>
        {
            showDetailPopup && modalContent()
        }
        {
            showDetailModal && modalContent2()
        }
    </View>
}