import { View, StyleSheet, Linking } from "react-native";
import { 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 } 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";

// 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 { t } = useTranslation()
    const [show, setShow] = useState(false)
    const [count, setCount] = useState(0)

    useEffect(() => {
        navigation.setOptions({
            headerTitle: 'Choose Location',
            headerRight: () => {
                return <View>
                    <Text onClick={confirmChoose} style={{ color: '#fff', marginRight: 15 }}>Done</Text>
                </View>
            }
        });
        getCurrent()
    }, [])

    function confirmChoose() {
        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())}`

        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() {
        Taro.getLocation({
            success(res) {
                // showAlert({
                //     title: 'location',
                //     content: JSON.stringify(res)
                // })
                setShow(true)
                setCurrent(res)
                location = {
                    lat: (res as any).latitude, lng: (res as any).longitude
                }
            },
            fail(res) {
                console.log('location update failed reason', res)
                if (res.errMsg == 'Permissions denied!') {
                    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)
                            location = {
                                lat: (res as any).latitude, lng: (res as any).longitude
                            }
                        })
                    }
                }
            }
        })
    }


    function showCurrent() {
        getCurrent()
    }

    function centerPosition() {
        if (current) {
            return { lat: current.latitude, lng: current.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={10}
            mapCenterPosition={centerPosition()}
            mapMarkers={mapMarkers()}
            onMessageReceived={e => {
                if (e.payload && e.payload.mapCenterPosition)
                    console.log((e as any).payload.mapCenterPosition)
                // console.log(e)
                // setCount(count => count + 1)
                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>
        <Image src={require('@/assets/images/current_location.png')} onClick={showCurrent} style={styles.location_btn} />
        {/* <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: 40,
        height: 40,
        marginBottom: 25
    },
    location_btn: {
        position: 'absolute',
        left: 40,
        bottom: 80,
        width: 40,
        height: 40
    },
    footer: {
        position: 'absolute',
        left: 50,
        right: 50,
        bottom: 30,
        backgroundColor: '#fff',
        alignItems: 'center',
        justifyContent: 'center',
        height: 30
    }

});