import {  StyleSheet, Linking, StatusBar } from "react-native";
import { View,Image, Text } from "@tarojs/components";
import './map.scss'
import { useEffect, useRef, useState } from "react";
import Taro from "@tarojs/taro";
import { LeafletView } from 'react-native-leaflet-maps';
import { useNavigation, useRoute } from "@react-navigation/native";
import { TimeFormatter } from "@/utils/time_format";
import { systemLocation } from "@/services/common";
import { useTranslation } from "react-i18next";
import showAlert from "@/components/basic/Alert";
import { kIsAndroid, kIsIOS } from "@/utils/tools";
import { AtActivityIndicator } from "taro-ui";

// let LeafletView = require('react-native-leaflet-maps').LeafletView
let location: any = null
export default function map() {
    // const [location, setLocation] = useState<any>(null)
    const navigation = useNavigation()
    const [current, setCurrent] = useState<any>(null)
    const [centerLocation, setCenterLocation] = useState<any>(null)
    const { t } = useTranslation()
    const [show, setShow] = useState(false)
    const [isLoading, setIsLoading] = useState(false)
    const router = useRoute()
    const zoom = (router.params! as any).zoom || 12

    useEffect(() => {
        if (router.params && (router.params! as any).lat) {
            setCenterLocation({
                latitude: (router.params! as any).lat,
                longitude: (router.params! as any).lng
            })
        }
        else {
            setCenterLocation({
                latitude: 37.4221,
                longitude: -122.0853
            })
        }


        navigation.setOptions({
            headerTitle: t('time_of_day.index.pick_location'),
            headerRight: () => {
                return <View
                    onClick={confirmChoose}
                    style={{
                        height: 30, backgroundColor: '#eae9e9', marginRight: 20,
                        display: 'flex',
                        alignItems: 'center',
                        justifyContent: 'center',
                        paddingLeft: 10,
                        paddingRight: 10,
                        borderRadius: 10
                    }}>
                    <Text style={{ color: '#000', fontSize: 14, fontWeight: 'bold' }}>{t('time_of_day.index.done')}</Text>
                </View>
                // return <View style={{height:30,backgroundColor:'red',marginRight:20}}>
                //     <Text onClick={confirmChoose} style={{ color: (router.params! as any).source == 'time_of_day' ? '#000' : '#fff',fontSize:16,fontWeight:'bold', marginRight: 15, padding: 5 }}>{t('time_of_day.index.done')}</Text>
                // </View>
            }
        });
        // getCurrent()
    }, [])

    function confirmChoose() {
        if ((router.params! as any).source && (router.params! as any).source == 'time_of_day') {
            if ((router.params! as any).chooseLocation) {
                (router.params! as any).chooseLocation(location, 'PICK')
            }
            navigation.goBack()
            return;
        }
        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 (location.lng < -180) {
            location.lng += 360
        }
        if (location.lng > 180) {
            location.lng -= 360
        }
        if (location.lat > 90) {
            location.lat -= 90
        }

        if (location.lat < -90) {
            location.lat += 90
        }
        systemLocation({
            lat: (location as any).lat,
            lng: (location as any).lng,
            date_start: strYesterday,
            date_end: strTomorrow,
            coordinate_system_standard: process.env.TARO_ENV == 'weapp' ? 'GCJ-02' : 'WGS-84'
        }).then(data => {
            global.locationDetail = data
            Taro.setStorage({
                key: 'gps',
                data: JSON.stringify(data as any)
            })

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

            navigation.goBack()
        })
    }

    function getCurrent() {
        if (kIsIOS) {
            requestLocation()
            return;
        }
        var Jto = require('react-native').NativeModules.NativeBridge;
        Jto.checkSystemLocationService().then(res => {
            if (res) {
                requestLocation()
            }
            else {
                showAlert({
                    title: t('feature.auth_sys.location_title'),
                    content: t('feature.auth_sys.device_location_desc'),
                    showCancel: true,
                    cancelText: t('feature.auth_sys.location_cancel'),
                    confirmText: t('feature.auth_sys.device_confirm'),
                    confirm: () => {
                        Jto.openSystemLocationSettings()
                    }
                })
            }
        })

    }

    function requestLocation() {
        setIsLoading(true)
        Taro.getLocation({
            success(res) {
                // showAlert({
                //     title: 'location',
                //     content: JSON.stringify(res)
                // })
                setShow(true)
                setCurrent(res)
                setCenterLocation(res)
                location = {
                    lat: (res as any).latitude, lng: (res as any).longitude
                }
                setIsLoading(false)
            },
            fail(res) {
                console.log('location update failed reason', res)
                if (res.errMsg == 'Permissions denied!') {
                    setIsLoading(false)
                    showAlert({
                        title: t('feature.auth_sys.location_title'),
                        content: kIsIOS ? t('feature.auth_sys.location_desc') : t('feature.auth_sys.location_android_service_desc'),
                        showCancel: true,
                        cancelText: t('feature.auth_sys.location_cancel'),
                        confirmText: kIsIOS ? t('feature.auth_sys.location_confirm') : t('feature.auth_sys.service_confirm'),
                        confirm: () => {
                            if (kIsIOS) {
                                Linking.openURL('app-settings:')
                            }
                            else {
                                Linking.openSettings()
                                // var Jto = require('react-native').NativeModules.NativeBridge;
                                // Jto.openNotificationSettings()
                            }

                        }
                    })
                }
                else {
                    if (kIsAndroid) {

                        var Jto = require('react-native').NativeModules.NativeBridge;
                        Jto.getLocation().then(result => {
                            var res = JSON.parse(result)
                            setCurrent(res)
                            setCenterLocation(res)
                            location = {
                                lat: (res as any).latitude, lng: (res as any).longitude
                            }
                            setIsLoading(false)
                            // showAlert({
                            //     title: 'location2',
                            //     content: JSON.stringify(res)
                            // })
                        }).catch(e => {
                            setIsLoading(false)

                            // showAlert({
                            //     title: 'location failed',
                            //     content: JSON.stringify(e)
                            // })
                        })
                    }
                    else {
                        setIsLoading(false)
                    }
                }
            }
        })
    }


    function showCurrent() {
        getCurrent()
    }

    function centerPosition() {
        if (centerLocation) {
            return { lat: centerLocation.latitude, lng: centerLocation.longitude }
        }
        return null
    }

    function mapMarkers() {
        const icon = '<?xml version="1.0" standalone="no"?><!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"><svg t="1721280834380" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="8231" xmlns:xlink="http://www.w3.org/1999/xlink" width="200" height="200"><path d="M511.999097 511.999097m-486.524133 0a486.524133 486.524133 0 1 0 973.048266 0 486.524133 486.524133 0 1 0-973.048266 0Z" fill="#286FB7" opacity=".2" p-id="8232"></path><path d="M511.999097 511.999097m-307.200542 0a307.200542 307.200542 0 1 0 614.401084 0 307.200542 307.200542 0 1 0-614.401084 0Z" fill="#FFFFFF" p-id="8233"></path><path d="M511.999097 511.999097m-257.688367 0a257.688367 257.688367 0 1 0 515.376734 0 257.688367 257.688367 0 1 0-515.376734 0Z" fill="#4575F6" p-id="8234"></path></svg>'
        if (current) {
            return [{
                id: 9527,
                position: {
                    lat: current.latitude,
                    lng: current.longitude
                },
                icon: `<div style="width: 24px; height: 24px; background-color: #286FB752; border-radius: 50%;display:flex;align-items:center;justify-content:center;">
                    <div style="width: 16px; height: 16px; background-color: #fff;; border-radius: 50%;display:flex;align-items:center;justify-content:center">
                    <div style="width: 12px; height: 12px; background-color: #4575F6; border-radius: 50%;display:flex;align-items:center;justify-content:center">
                    </div>
                    </div>
                </div>`,
                // icon:
                //     require('@/assets/images/current_location.png'),
                // icon: this.state.user_last_car,
                size: [32, 32],
            }]
        }
        return []
    }

    return <View style={{ flex: 1 }}>
        <LeafletView
            style={{ flex: 1 }}
            zoom={zoom}
            mapCenterPosition={centerPosition()}
            mapMarkers={mapMarkers()}
            onMessageReceived={e => {
                if (e.event == 'onZoomEnd' && e.payload && e.payload.zoom) {
                    Taro.setStorage({ key: 'zoom', data: (e as any).payload.zoom })
                }

                if (e.payload && e.payload.mapCenterPosition)
                    location = e.payload.mapCenterPosition
                // if (e.event && e.event == 'onMoveEnd') {
                //     if (e.payload && e.payload.mapCenterPosition)
                //         setLocation(e.payload.mapCenterPosition)
                // }
                // setTimeout(() => {
                //     if (e.payload && e.payload.mapCenterPosition)
                //         setLocation(e.payload.mapCenterPosition)
                // }, 500)
                // if (e.payload && e.payload.mapCenterPosition)
                //     setLocation(e.payload.mapCenterPosition)
            }}
        />
        <View style={styles.overlayView}
            pointerEvents="none"
        >
            <Image src={require('@/assets/images/center.png')} style={styles.center} />
        </View>
        <View style={styles.location_btn}>
            {
                isLoading ? <View style={{ width: 20, height: 20, overflow: 'hidden' }}>
                    <AtActivityIndicator size={20} color="#000" content="" />
                </View> :
                    <Image src={require('@/assets/images/current_location.png')} onClick={showCurrent} style={styles.location_icon} />
            }

        </View>

        {/* <View style={styles.footer}>
            {
                location && <Text style={{ fontSize: 14, color: '#000' }}>Center位置:lat {(location as any).lat.toFixed(4)} lng {(location as any).lng.toFixed(4)}</Text>
            }
        </View> */}
    </View>
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
    },
    scrollContent: {
        // 您的滚动内容样式
    },
    overlayView: {
        // 覆盖视图样式
        position: 'absolute',
        top: 0,
        left: 0,
        right: 0,
        bottom: 0,
        alignItems: 'center',
        justifyContent: 'center'
    },
    center: {
        width: 35,
        height: 35,
        marginBottom: 21
    },
    location_btn: {
        position: 'absolute',
        left: 40,
        bottom: 80,
        width: 50,
        height: 50,
        alignItems: 'center',
        justifyContent: 'center',
        backgroundColor: '#fff',
        borderRadius: 5
    },
    location_icon: {
        width: 30,
        height: 30
    },
    footer: {
        position: 'absolute',
        left: 50,
        right: 50,
        bottom: 30,
        backgroundColor: '#fff',
        alignItems: 'center',
        justifyContent: 'center',
        height: 30
    }

});