import { Ref, ref, watch } from 'vue';
import * as am4core from "@amcharts/amcharts4/core";
import * as am4maps from "@amcharts/amcharts4/maps";
import am4themes_animated from "@amcharts/amcharts4/themes/animated";
import am4geodata_worldHigh from "@amcharts/amcharts4-geodata/worldUltra";
import { useFontStore, useMapStore } from '@/store/index'
import { storeToRefs } from 'pinia';
import am4geodata_data_countries from "@amcharts/amcharts4-geodata/data/countries";

import am5geodata_lang_cn_ZH from "@amcharts/amcharts4-geodata/lang/cn_ZH";
import AliyunUpload from '@/utils/upload/aliyun';
import { MapTheme } from '@/types/mapTheme';


export default (MapDOM: Ref<HTMLElement | undefined>, loadingStatus: Ref<boolean>) => {
    const mapStore = useMapStore()
    const { operaIndex, fillColor, fillType, canOpera, newLine, lineSeries, removeMark, labelSeries, execut,splineSeries,currentTheme } = storeToRefs(mapStore)
    mapStore.setAllCountries(am5geodata_lang_cn_ZH)
    const eventName = ref<string>('')

    let map: am4maps.MapChart
    let worldSeries: am4maps.MapPolygonSeries
    let countrySeries: am4maps.MapPolygonSeries
    let countryPolygon: am4maps.MapPolygon
    let back: am4core.ZoomOutButton
    let addButton: am4core.Button
    const CountriesKeys = ref<string[]>([])



    const initMap = () => {
        loadingStatus.value = true
        am4core.useTheme(am4themes_animated);
        map = am4core.create(MapDOM.value, am4maps.MapChart)
        map.geodata = am4geodata_worldHigh
        map.geodataNames = am5geodata_lang_cn_ZH
        map.projection = new am4maps.projections.Mercator();
        map.events.on('hit', () => {
            if (!eventName.value || eventName.value == '') mapStore.setCurrent(null)
            eventName.value = ''
        })
        map.zoomControl = new am4maps.ZoomControl();
        map.zoomControl.slider.height = 100;
        map.maxZoomLevel = 64

        worldSeries = map.series.push(new am4maps.MapPolygonSeries());
        worldSeries.exclude = ["AQ"];
        if (CountriesKeys.value && CountriesKeys.value.length > 0) {
            worldSeries.include = CountriesKeys.value
        }
        worldSeries.useGeodata = true;
        worldSeries.clickable = true

        let polygonTemplate = worldSeries.mapPolygons.template;
        polygonTemplate.tooltipText = "{name}";
        polygonTemplate.tooltipColorSource
        polygonTemplate.fill = am4core.color(`#818181`);
        polygonTemplate.stroke = am4core.color(`#ffffff`);
        polygonTemplate.strokeWidth = 0.1
        polygonTemplate.events.on("hit", (e) => {
            createCountry(e)
        })

        worldSeries.events.on('ready', (e) => {
            loadingStatus.value = false
        })

        initCountry()
        createBackButton()
        createAddButton()
        initLineSeries()
        initLabelSeries()
        initSplineSeries()
    }



    const initCountry = () => {
        countrySeries = map.series.push(new am4maps.MapPolygonSeries());
        countrySeries.useGeodata = true;
        countrySeries.hide();
        countrySeries.geodataSource.events.on("done", () => {
            worldSeries.hide();
            countrySeries.show();
        });

        countryPolygon = countrySeries.mapPolygons.template;
        countryPolygon.tooltipText = "{name}";
        countryPolygon.nonScalingStroke = true;
        countryPolygon.fill = am4core.color(`#818181`);
        countryPolygon.stroke = am4core.color(`#ffffff`);
        countryPolygon.strokeWidth = 0.1
        countryPolygon.strokeDasharray = '20,20'

        countryPolygon.events.on("hit", (e) => {

            if (operaIndex.value == 1) fillColorHandler(e)
            else if (operaIndex.value == 5) createMarkImageHandler(e)
            else if (operaIndex.value == 3) createLabel(e)
            else {
                eventName.value = 'MapPolygon'
                mapStore.setCurrent(e.target)
            }
        })
    }

    const disposeAll = () => {
        map.disposeChildren()
        map.dispose()
    }

    const exportPng = (showBackground:boolean): Promise<string> => {
        if(!showBackground) map.background.fillOpacity = 0
        const tt = map.config
        countrySeries.exporting.getJSON("json").then(async r=>{
            
            r = decodeURIComponent(r.replace('data:application/json;charset=utf-8,',''))
            const blob = new Blob([r],{ type: 'application/json;charset=utf-8' });
            await AliyunUpload.UploadAsync(blob,"tripfmap/1/temp.json")
        })
        loadingStatus.value = true
        let tempBack = back.isShowing
        let tempAdd = addButton.isShowing
        back.hide()
        addButton.hide()
        map.zoomControl.hide()
        map.exporting.backgroundColor = am4core.color(`#00000000`)

        return new Promise((resolve) => {
            setTimeout(() => {
                map.exporting.getImage("png").then(r => {
                    map.zoomControl.show()
                    if (tempBack) back.show()
                    if (tempAdd) addButton.show()
                    loadingStatus.value = false
                    resolve(r)
                }).catch((e) => {
                    map.zoomControl.show()
                    if (tempBack) back.show()
                    if (tempAdd) addButton.show()
                    loadingStatus.value = false
                    resolve('')
                })
            }, 1000)
        })
    }

    const isHaveBackground = () => {
        return map.background.fillOpacity>0
    }

    const createMarkImageHandler = (e: any) => {
        let markerPath = mapStore.getMarker
        let imageSeries = map.series.push(new am4maps.MapImageSeries())

        if (markerPath == 'circle') {
            let circle = imageSeries.mapImages.template.createChild(am4core.Circle);
            circle.radius = 10;
            circle.fill = am4core.color(fillColor.value.realColor.substring(0, 7));
            circle.fillOpacity = fillColor.value.opacity
            circle.stroke = am4core.color("#FFFFFF");
            circle.strokeWidth = 2;
            circle.scale = 1;
        } else {
            var marker1 = imageSeries.mapImages.template.createChild(am4core.Circle);
            marker1.path = markerPath
            marker1.fill = am4core.color(fillColor.value.realColor.substring(0, 7));
            marker1.fillOpacity = fillColor.value.opacity
            marker1.stroke = am4core.color("#FFFFFF");
            marker1.strokeWidth = 0;
            marker1.scale = 0.8;
            marker1.horizontalCenter = "middle";
            marker1.verticalCenter = "middle";
        }
        imageSeries.mapImages.template.nonScaling = true;
        imageSeries.mapImages.template.propertyFields.latitude = "latitude";
        imageSeries.mapImages.template.propertyFields.longitude = "longitude";
        imageSeries.data = [
            map.svgPointToGeo({ x: e.svgPoint.x, y: e.svgPoint.y })
        ]
        imageSeries.events.on("dragstart", () => {
            map.panBehavior = 'none'
        })
        imageSeries.events.on("dragstop", () => {
            map.panBehavior = "move"
        })
        imageSeries.events.on("hit", (e) => {
            eventName.value = 'MapImageSeries'
            mapStore.setCurrent(e.target)

        })
        eventName.value = 'MapImageSeries'

        mapStore.setCurrent(imageSeries)
    }

    const setMarks = (marks: { lat: number, lng: number, name: string }[]) => {
        for (let i = 0; i < marks.length; i++) {
            const x = marks[i];
            let imageSeries = map.series.push(new am4maps.MapImageSeries())
            let circle = imageSeries.mapImages.template.createChild(am4core.Circle);
            circle.radius = 10;
            circle.fill = am4core.color(fillColor.value.realColor.substring(0, 7));
            circle.fillOpacity = fillColor.value.opacity
            circle.stroke = am4core.color("#FFFFFF");
            circle.strokeWidth = 2;
            circle.scale = 0.6;

            imageSeries.mapImages.template.nonScaling = true;

            imageSeries.mapImages.template.propertyFields.latitude = "latitude";
            imageSeries.mapImages.template.propertyFields.longitude = "longitude";
            imageSeries.data = [{ latitude: x.lat, longitude: x.lng }]
            imageSeries.events.on("dragstart", () => {
                map.panBehavior = 'none'
            })
            imageSeries.events.on("dragstop", () => {
                map.panBehavior = "move"
            })
            imageSeries.events.on("hit", (e) => {
                eventName.value = 'MapImageSeries'
                mapStore.setCurrent(e.target)
            })

            setTimeout(() => {
                let labelChildren = imageSeries.mapImages.create();
                labelChildren.latitude = x.lat;
                labelChildren.longitude = x.lng;

                let label = labelChildren.createChild(am4core.Label)
                label.horizontalCenter = "middle";
                label.fontSize = 13;
                label.fontFamily = 'pingfangr'
                label.fill = am4core.color(fillColor.value.realColor)
                label.currentText = x.name
                label.text = x.name
                console.log(x.name)
                // labelChildren.children.getIndex(0).hide()
                // label.marginBotton=0
                label.y = 6
                label.paddingLeft = 6
                label.x = -2.5

                setTimeout(() => {
                    try {
                        // @ts-ignore
                        labelChildren!.children!.getIndex(0).hide()
                    } catch (error) { }
                }, 1000);
            }, 1000);
        }
    }

    const setLines = (vals: { latitude: number, longitude: number }[][]) => {
        for (let i = 0; i < vals.length; i++) {
            const item = vals[i];
            let points: am4core.IGeoPoint[] = item
            createLine(points)
        }
    }

    const fillColorHandler = (e: any) => {
        if (operaIndex.value != 1) return;
        if (fillType.value == 2) {
            countryPolygon.polygon.fill = am4core.color(`#${fillColor.value.color.toString(16).padStart(6, '0')}`)
            countryPolygon.polygon.fillOpacity = fillColor.value.opacity
        } else {
            var dataItem = e.target.dataItem as any;
            dataItem.dataContext.colorWasSet = false
            e.target.polygon.fill = am4core.color(`#${fillColor.value.color.toString(16).padStart(6, '0')}`)
            e.target.polygon.fillOpacity = fillColor.value.opacity
        }
    }

    const createCountry = (ev: any) => {
        mapStore.clearCheckedCountries()
        ev.target.series.chart.zoomToMapObject(ev.target);

        var chiMap = ev.target.dataItem.dataContext.id;
        if (chiMap) {
            let geoUrl = am4geodata_data_countries[chiMap].find(x => x.indexOf("High") != -1)
            ev.target.isHover = false;
            // @ts-ignore
            countrySeries.geodata = null
            // @ts-ignore
            countrySeries.include = null
            countrySeries.invalidateData()
            countrySeries.geodataSource.url = "https://cdn.amcharts.com/lib/4/geodata/json/" + geoUrl + ".json";
            countrySeries.geodataSource.load();
            mapStore.setCheckedCountries({
                id: chiMap,
                name: ev.target.dataItem.dataContext.name,
                url: countrySeries.geodataSource.url
            })
            back.show();
            addButton.show()
            canOpera.value = true
        }
    }

    const setCountry = (names: string[]) => {
        mapStore.clearCheckedCountries()
        let allCountries = mapStore.getAllCountries
        let countriesData: any[] = []
        Object.keys(allCountries!).forEach((key: string) => {
            if (names.includes(allCountries![key])) {
                countriesData.push({
                    id: key,
                    name: allCountries![key]
                });
            }else if(names.includes(key)){
                countriesData.push({
                    id: key,
                    name: allCountries![key]
                });
            }
        })
        if (countriesData && countriesData.length > 0) {

            if (countriesData.length == 1) {
                let first = countriesData[0]
                let geoUrl = am4geodata_data_countries[first.id].find(x => x.indexOf("High") != -1)
                // @ts-ignore
                countrySeries.geodata = null
                // @ts-ignore
                countrySeries.include = null
                countrySeries.invalidateData()
                setTimeout(() => {
                    try {
                        map.zoomToMapObject(worldSeries.getPolygonById(first.id))
                    } catch (error) { }
                }, 500);
                countrySeries.geodataSource.url = "https://cdn.amcharts.com/lib/4/geodata/json/" + geoUrl + ".json";
                countrySeries.geodataSource.load();
                mapStore.setCheckedCountries({
                    id: first.id,
                    name: first.name,
                    url: countrySeries.geodataSource.url
                })
            } else if (countriesData.length > 1) {
                worldSeries.hide()
                countrySeries.show()
                let idArray: any[] = []
                for (let i = 0; i < countriesData.length; i++) {
                    const item = countriesData[i];
                    let geoUrl = am4geodata_data_countries[item.id].find(x => x.indexOf("High") != -1)
                    geoUrl = "https://cdn.amcharts.com/lib/4/geodata/json/" + geoUrl + ".json";
                    mapStore.setCheckedCountries({
                        id: item.id,
                        name: item.name,
                        url: geoUrl
                    })
                    idArray.push(item.id)
                }
                countrySeries.geodata = am4geodata_worldHigh
                countrySeries.include = idArray
                countrySeries.invalidateData()
                setTimeout(() => {
                    try {
                        map.zoomToMapObject(countrySeries.getPolygonById(idArray![0]))
                    } catch (error) {

                    }
                }, 500);
            }
            back.show();
            addButton.show()
            canOpera.value = true
        }

    }

    const setMulitpCountries = (payload: any, execut: number) => {

        let tempChecked = mapStore.getCheckedCountries
        let id = payload.id
        let idArray = tempChecked.map(x => x.id)
        if (execut == 1) {
            let geoUrl = am4geodata_data_countries[id].find(x => x.indexOf("High") != -1)
            geoUrl = "https://cdn.amcharts.com/lib/4/geodata/json/" + geoUrl + ".json";
            mapStore.setCheckedCountries({
                id: id,
                name: payload.name,
                url: geoUrl
            })
            idArray.push(id)
        } else {
            let ri = idArray.indexOf(id)
            if (ri != -1) {
                idArray.splice(ri, 1)
                tempChecked.splice(ri, 1)
            }
        }

        if (idArray.length > 1) {
            countrySeries.geodata = am4geodata_worldHigh
            countrySeries.include = idArray
            countrySeries.invalidateData()
            setTimeout(() => {
                map.zoomToMapObject(countrySeries.getPolygonById(id))
            }, 500);
        } else if (idArray.length == 1) {
            // @ts-ignore
            countrySeries.geodata = null
            // @ts-ignore
            countrySeries.include = null
            countrySeries.invalidateData()
            countrySeries.geodataSource.url = tempChecked[0].url
            countrySeries.geodataSource.load();
        } else {
            worldSeries.show();
            map.goHome();
            countrySeries.hide();
            back.hide();
            addButton.hide()
            canOpera.value = false
            operaIndex.value = 0
            mapStore.clearCheckedCountries()
            mapStore.setCurrent(null)
        }

    }

    const createBackButton = () => {
        back = map.createChild(am4core.ZoomOutButton);
        back.align = "right";
        back.positionInvalid
        back.margin(20, 20, 20, 0)
        back.icon = new am4core.Sprite()
        back.icon.fill = am4core.color(`#ffffff`)
        back.icon.path = "M16,8 L14,8 L14,16 L10,16 L10,10 L6,10 L6,16 L2,16 L2,8 L0,8 L8,0 L16,8 Z M16,8"
        back.readerTitle = '返回'
        back.hide();
        back.events.on("hit", function () {
            worldSeries.show();
            map.goHome();
            countrySeries.hide();
            back.hide();
            addButton.hide()
            canOpera.value = false
            operaIndex.value = 0
            mapStore.clearCheckedCountries()
            mapStore.setCurrent(null)
        });
    }

    const createAddButton = () => {
        addButton = map.createChild(am4core.ZoomOutButton)
        addButton.positionInvalid
        addButton.margin(0, 20, 0, 0)
        addButton.align = "right"
        addButton.y = 40
        addButton.icon = new am4core.Sprite()
        addButton.icon.fill = am4core.color(`#ffffff`)
        addButton.icon.scale = 0.018
        addButton.icon.path = "M678.272 98.176C656 96 629.12 96 596.224 96H427.776c-32.896 0-59.84 0-82.048 2.176-23.232 2.304-43.712 7.168-63.104 18.304-19.392 11.136-33.92 26.432-47.488 45.376-13.056 18.048-26.56 41.344-43.008 69.76L108.48 375.808c-16.512 28.48-30.08 51.84-39.36 72.192-9.728 21.312-15.808 41.6-15.808 64s6.08 42.688 15.808 64c9.216 20.352 22.848 43.712 39.36 72.192l83.648 144.192c16.448 28.416 29.952 51.712 43.008 69.76 13.632 18.944 28.096 34.24 47.488 45.44 19.392 11.136 39.872 16 63.104 18.24 22.208 2.176 49.152 2.176 82.048 2.176h168.448c32.896 0 59.84 0 82.048-2.176 23.232-2.304 43.712-7.104 63.104-18.304 19.392-11.136 33.92-26.432 47.488-45.376 13.056-18.048 26.56-41.344 43.008-69.76l83.648-144.192c16.512-28.48 30.08-51.84 39.36-72.192 9.728-21.312 15.808-41.6 15.808-64s-6.08-42.688-15.808-64c-9.28-20.352-22.848-43.712-39.36-72.192l-83.648-144.192c-16.448-28.416-29.952-51.712-43.008-69.76-13.632-18.944-28.096-34.24-47.488-45.44-19.392-11.072-39.872-16-63.104-18.24zM512 661.376a149.312 149.312 0 1 1 0-298.688 149.312 149.312 0 0 1 0 298.624z"
        addButton.readerTitle = '设置国家图层'
        addButton.cursorOverStyle = am4core.MouseCursorStyle.pointer
        addButton.hide();

        addButton.events.on("hit", function () {
            eventName.value = 'Country'
            mapStore.setCurrent('Country')
        });
    }

    const initLabelSeries = () => {
        labelSeries.value = map.series.push(new am4maps.MapImageSeries())
    }

    const createLabel = (e: any) => {
        let point = map.svgPointToGeo({ x: e.svgPoint.x, y: e.svgPoint.y })
        let labelChildren = labelSeries.value!.mapImages.create();
        labelChildren.latitude = point.latitude;
        labelChildren.longitude = point.longitude;

        let label = labelChildren.createChild(am4core.Label)
        label.horizontalCenter = "middle";
        label.verticalCenter = "middle";
        label.fontSize = 15;
        label.fontFamily = 'pingfangr'
        label.nonScaling = true;
        label.interactionsEnabled = false;
        label.fill = am4core.color(fillColor.value.realColor)
        label.text = '文字...'
        label.cursorOverStyle = am4core.MouseCursorStyle.pointer
        label.draggable = true
        label.interactionsEnabled = true

        label.events.on("dragstart", () => {
            map.panBehavior = 'none'
        })
        label.events.on("dragstop", () => {
            map.panBehavior = "move"
        })
        label.events.on("hit", (e) => {
            eventName.value = 'Label'
            mapStore.setCurrent(e.target)

        })
        eventName.value = 'Label'
        mapStore.setCurrent(label)
        //label.children.getIndex(0)!.text = state;
    }

    const initLineSeries = () => {
        lineSeries.value = map.series.push(new am4maps.MapArcSeries());
        lineSeries.value!.mapLines.template.strokeWidth = 2;
        lineSeries.value!.mapLines.template.stroke = am4core.color(`#${fillColor.value.color.toString(16).padStart(6, '0')}`);
        lineSeries.value!.mapLines.template.strokeOpacity = fillColor.value.opacity
        lineSeries.value!.mapLines.template.nonScalingStroke = true;
        lineSeries.value!.mapLines.template.line.controlPointDistance = 0;
        lineSeries.value!.mapLines.template.line.controlPointPosition = 0.5;
        lineSeries.value!.mapLines.template.line.resizable = true
        lineSeries.value!.mapLines.template.line.cursorOverStyle = am4core.MouseCursorStyle.pointer
        lineSeries.value!.mapLines.template.strokeLinecap = 'round'
    }

    const initSplineSeries = () => {
        splineSeries.value = map.series.push(new am4maps.MapSplineSeries());
        if(splineSeries.value){
            splineSeries.value.mapLines.template.line.tensionX = 0.6;
            splineSeries.value.mapLines.template.line.tensionY = 2;
            splineSeries.value.mapLines.template.strokeWidth = 2;
            splineSeries.value.mapLines.template.stroke = am4core.color(`#${fillColor.value.color.toString(16).padStart(6, '0')}`);
            splineSeries.value.mapLines.template.strokeOpacity = fillColor.value.opacity
            splineSeries.value.mapLines.template.nonScalingStroke = true
            splineSeries.value.mapLines.template.line.cursorOverStyle = am4core.MouseCursorStyle.pointer
            splineSeries.value.mapLines.template.strokeLinecap = 'round'

            // let pointers =[
            //         { "latitude": 48.856614, "longitude": 2.352222 },
            //         { "latitude": 40.712775, "longitude": -74.005973 }
            //     ]

            // createSpLine(pointers)
        }
        
    }

    const createSpLine = (points: am4core.IGeoPoint[]) => {
        if(splineSeries.value){
            let line = splineSeries.value.mapLines.create();
            line.multiGeoLine = [points];
            line.draggable = true
            line.strokeDasharray = '0,0'
            //@ts-ignore
            line.children.getIndex(0).tensionY = 2
            line.events.on("hit", (e) => {
                eventName.value = 'lineEvent'
                mapStore.setCurrent(e.target)
            })
            line.events.on("dragstart", () => {
                map.panBehavior = 'none'
            })
            line.events.on("dragstop", () => {
                map.panBehavior = "move"
            })
            mapStore.setCurrent(line)
        }
    }

    const lineTransformSpline = (line:am4maps.MapLine)=>{
        let spline = splineSeries.value!.mapLines.create()
        spline.multiGeoLine = line.multiGeoLine
        spline.stroke = line.stroke
        spline.strokeLinecap = line.strokeLinecap
        spline.strokeWidth = line.strokeWidth
        spline.strokeOpacity = line.strokeOpacity
        spline.strokeDasharray = line.strokeDasharray
        spline.draggable = true
        //@ts-ignore
        spline.children.getIndex(0).tensionY = 2
        spline.events.on("hit", (e) => {
            eventName.value = 'lineEvent'
            mapStore.setCurrent(e.target)
        })
        spline.events.on("dragstart", () => {
            map.panBehavior = 'none'
        })
        spline.events.on("dragstop", () => {
            map.panBehavior = "move"
        })
        //mapStore.setCurrent(line)
    }

    const splineTransformLine = (spline:am4maps.MapSpline)=>{
        let line = lineSeries.value!.mapLines.create()
        line.multiGeoLine = spline.multiGeoLine
        line.stroke = spline.stroke
        line.strokeLinecap = spline.strokeLinecap
        line.strokeWidth = spline.strokeWidth
        line.strokeOpacity = spline.strokeOpacity
        line.strokeDasharray = spline.strokeDasharray
        line.draggable = true
       
        line.events.on("hit", (e) => {
            eventName.value = 'lineEvent'
            mapStore.setCurrent(e.target)
        })
        line.events.on("dragstart", () => {
            map.panBehavior = 'none'
        })
        line.events.on("dragstop", () => {
            map.panBehavior = "move"
        })
        //mapStore.setCurrent(line)
    }

    const createLine = (points: am4core.IGeoPoint[]) => {

        let line = lineSeries.value!.mapLines.create();
        line.multiGeoLine = [points];
        line.draggable = true
        line.events.on("hit", (e) => {
            eventName.value = 'lineEvent'
            mapStore.setCurrent(e.target)
        })
        line.events.on("dragstart", () => {
            map.panBehavior = 'none'
        })
        line.events.on("dragstop", () => {
            map.panBehavior = "move"
        })
        //var tria = bullet.createChild();

        mapStore.setCurrent(line)
    }

    const changeMarkStyleToCurrent = ()=>{
        let current = mapStore.getCurrent
        if(current){
            let cc = current.mapImages.getIndex(0).children.getIndex(0)
            let ct = current.mapImages.template.children.getIndex(0)
            let cl:any = undefined
            if(current.mapImages.length>1 && current.mapImages.getIndex(1).children.length>1){
                cl = current.mapImages.getIndex(1).children.getIndex(1)
            }
            for (let i = 0; i < map.series.length; i++) {
                const element = map.series.getIndex(i);
                if(element && element.className=='MapImageSeries' && element.uid!=current.uid && element.data && element.data.length>0){
                    let mark = element as am4maps.MapImageSeries
                    if(mark && mark.mapImages.length>0 && mark.mapImages.getIndex(0)!.children!.length>0){
                        let chi =  mark.mapImages!.getIndex(0)!.children.getIndex(0)
                        let tempChi = mark.mapImages.template.children.getIndex(0)
                        if(chi){
                            chi.strokeWidth= cc.strokeWidth
                            chi.strokeOpacity = cc.strokeOpacity
                            chi.stroke = cc.stroke
                            chi.scale = cc.scale
                            chi.fillOpacity = cc.fillOpacity
                            chi.fill = cc.fill
                        }
                        if(tempChi){
                            tempChi.strokeWidth= ct.strokeWidth
                            tempChi.strokeOpacity = ct.strokeOpacity
                            tempChi.stroke = ct.stroke
                            tempChi.scale = ct.scale
                            tempChi.fillOpacity = ct.fillOpacity
                            tempChi.fill = ct.fill
                        }
                        if(cl){
                            let lab:any = undefined
                            if(mark.mapImages.length>1 && mark.mapImages!.getIndex(1)!.children.length>1){
                                lab = mark.mapImages!.getIndex(1)!.children.getIndex(1)
                            }
                            if(!lab){
                                let labelChildren = mark.mapImages.create();
                                labelChildren.latitude = mark.data[0].latitude;
                                labelChildren.longitude = mark.data[0].longitude;

                                let label = labelChildren.createChild(am4core.Label)
                                label.horizontalCenter = "middle";
                                label.fontSize = 13;
                                label.fontFamily = 'pingfangr'
                                label.fill = am4core.color(fillColor.value.realColor)
                                label.text= '文字内容'
                                labelChildren.children.getIndex(0)!.hide()

                                lab = label
                            }

                            //lab.text = cl.text
                            lab.fontSize = cl.fontSize??15
                            lab.marginBottom = cl.marginBottom
                            lab.fill = cl.fill
                            calcLabelLocal(lab,mark)
                        } else {
                            if(mark.mapImages.length>1 && mark.mapImages!.getIndex(1)!.children.length>1){
                                mark.mapImages.removeIndex(1)
                            }
                        }
                    }
                }
            }
        }
    }

    const calcLabelLocal = (label:am4core.Label,parent:am4maps.MapImageSeries) =>{
        if(label){
            let scale = parent.mapImages.template.children.getIndex(0)!.scale
            //@ts-ignore
            let radius = parent.mapImages.template.children.getIndex(0)!.radius
            let align = label.marginBottom
            radius = radius==10?10:35
            let temp = radius*scale
            let increment = radius==10?10:0
            if(align==0){
                label.y = temp
                label.paddingLeft = temp
                label.x = 0 - (increment*.5)
            } else if(align==1){
                label.y = -(label.fontSize*1.33) - increment
                label.paddingLeft = temp
                label.x = 0 - (increment*.5)
            } else if(align==2){
                label.y = ((temp-label.fontSize - increment)/2)-(label.fontSize*0.2)
                label.x = ((label.fontSize*label.text.length)/2)+temp+(increment*.5)
                label.paddingLeft = 0
            } else if(align==3){
                label.y = ((temp-label.fontSize - increment)/2)-(label.fontSize*0.2)
                label.x = (-label.fontSize*label.text.length)/2 - (increment*1.5)
                label.paddingLeft = 0
            }
            //label.marginBottom=align
        }
        
    }

    const setLineTheme = ()=>{
        map.series.values.forEach(x=>{
            if(x.className=='MapSplineSeries'){
                let t = x as am4maps.MapSplineSeries
                t.mapLines.values.forEach(y=>{
                    y.stroke = am4core.color(currentTheme.value!.line.color)
                    y.strokeWidth = currentTheme.value!.line.width
                })
            } else if(x.className=='MapArcSeries'){
                let t = x as am4maps.MapArcSeries
                t.mapLines.values.forEach(y=>{
                    y.stroke = am4core.color(currentTheme.value!.line.color)
                    y.strokeWidth = currentTheme.value!.line.width
                })
            }
        })
    }

    const setImageTheme = ()=>{
        map.series.values.forEach(x=>{
            if(x.className=='MapImageSeries'){
                let t = x as am4maps.MapImageSeries
                if(t.mapImages && t.mapImages.values.length>0 && t.mapImages!.getIndex(0)!.children.getIndex(0)?.className!="Label"){
                    let temp = t.mapImages!.getIndex(0)!.children.getIndex(0)!
                    temp.fill =  am4core.color(currentTheme.value!.tag.color)
                    temp.scale =currentTheme.value!.tag.size
                    if(!temp.path) {
                        temp.strokeWidth = currentTheme.value!.tag.border
                        temp.stroke = am4core.color(currentTheme.value!.tag.borderColor)
                    }
                }

                let cl:am4core.Sprite|undefined = undefined
                if(t.mapImages.length>1 && t.mapImages!.getIndex(1)!.children.length>1){
                    let lab:any = undefined
                    lab = t.mapImages!.getIndex(1)!.children.getIndex(1)
                    if(lab){
                        useFontStore().loadFontToDocument([currentTheme.value!.text.fontFamily??""])
                        lab.fontSize = currentTheme.value!.text.size
                        lab.fill = am4core.color(currentTheme.value!.text.color)
                        lab.fontFamily = currentTheme.value!.text.fontFamily
                    }
                }

                
                
            }
        })
    }

    const setLableTheme = () => {
        map.series.values.forEach(x=>{
            if(x.className=='MapImageSeries' && x.children.length>0){
                let t = x as am4maps.MapImageSeries
                if(t.mapImages &&t.mapImages.values.length>0 && t.mapImages!.getIndex(0)!.children.getIndex(0)!.className=="Label"){
                    let lab = t.mapImages!.getIndex(0)!.children.getIndex(0)! as am4core.Label
                    lab.fontSize = currentTheme.value!.text.size
                    lab.fill =  am4core.color(currentTheme.value!.text.color)
                    lab.fontFamily = currentTheme.value!.text.fontFamily??""
                    useFontStore().loadFontToDocument([currentTheme.value!.text.fontFamily??""])
                }
                
            }
        })
    }

    const setTheme = (n: MapTheme|null)=>{
        
        if(n){
            map.background.fill = am4core.color(n.mapBackground);
            map.background.fillOpacity = 1;
            if(!countrySeries.include) countryPolygon.polygon.fill = am4core.color(n.fillColor[0])
            else{
                countrySeries.mapPolygons.values.forEach((x,i) => {
                    let color = i<n.fillColor.length?n.fillColor[i]:n.fillColor[n.fillColor.length-1]
                    x.fill = am4core.color(color);
                })
            }
            console.log(countrySeries.mapPolygons)
            countrySeries.mapPolygons.template.stroke = am4core.color(n.borderColor);
            countrySeries.mapPolygons.template.strokeWidth = n.border
            if(!countrySeries.include) countrySeries.geodataSource.load();
            setLineTheme()
            setImageTheme()
            setLableTheme()
            //console.log(map.series)
        }
    }

    watch(() => newLine.value, (newVal: number[]) => {
        let points: am4core.IGeoPoint[] = []
        points.push(map.svgPointToGeo({ x: newVal[0], y: newVal[1] }))
        points.push(map.svgPointToGeo({ x: newVal[2], y: newVal[3] }))
        createLine(points)
    })

    watch(() => execut.value, (newVal) => {
        if (newVal) {
            setMulitpCountries(newVal.payload, newVal.exec)
        }
    })

    watch(() => removeMark.value, (newVal: any) => {
        if (newVal) {
            let i = -1
            for (let j = 0; j < map.series.length; j++) {
                const element = map.series.getIndex(j);
                if (element?.uid == newVal.uid) {
                    i = j
                    break
                }
            }
            if (i != -1) {
                map.series.removeIndex(i)
                mapStore.setCurrent(null)
                removeMark.value = null
            }
        }
    })

    // watch(()=> currentTheme.value,(n: MapTheme|null)=>{
    //     setTheme(n)
    // })

    return {
        initMap,
        setCountry,
        setMarks,
        setLines,
        disposeAll,
        exportPng,
        isHaveBackground,
        lineTransformSpline,
        splineTransformLine,
        changeMarkStyleToCurrent,
        setTheme
    }
}