var map = null;
var layPoints = [];

function initMap(click) {
    // let key = '90bc158992feb8ccd0145e168cab1307';
    let init = function () {
        map = new AMap.Map("map", {
            viewMode: '2D', //默认使用 2D 模式
            zoom: 11, //地图级别
            center: [116.396477, 39.909278], //地图中心点
            mapStyle: "amap://styles/darkblue"
        });

        map.on('click', function (evt) {
            //    alert('您点击的位置:'+evt.lnglat.lng+' , '+ evt.lnglat.lat);
            if (click) {
                click(evt.lnglat);
            }
        });
    }
    return new Promise((resolve, reject) => {
        if (map) {
            resolve(200);
            return;
        }
        if (window.AMap) {
            init();
            resolve(200);
            return;
        }
        reject({ code: 500, msg: '高德地图未能初始化成功' });
    });

}

//添加一个点
function AddPoint(point, index, dragEnd, click, iconImg) {
  
    return new Promise((resolve, reject) => {
        try {
            if (!point) {
                reject("point不可用")
                return;
            }
            if (!point.longitude || !point.latitude) {
                reject("point的经纬度不可用")
                return;
            }
            layPoints.push({ lng: point.longitude, lat: point.latitude });

            let center = new AMap.LngLat(point.longitude, point.latitude);

            let icon = new AMap.Icon({
                size: new AMap.Size(45, 45), //图标尺寸
                image: iconImg, //Icon 的图像

                imageSize: new AMap.Size(45, 45), //根据所设置的大小拉伸或压缩图片
            });
            let marker = new AMap.Marker({
                icon: icon,
                position: center,
                offset: new AMap.Pixel(-15, -24),
                draggable: dragEnd ? true : false,
                cursor: 'point',
                title: point.isAlarming ? '正在报警:' + point.deviceName : point.deviceName,
                text: index,
                class: 'point',
                extData: point,
                anchor:'bottom-center'
            });
            marker.setMap(map);

            let lays = map.getAllOverlays('text');
            for (let i = 0; i < lays.length; i++) {
                const element = lays[i];
                let cls = element.getOptions();
                if (cls.class) {
                    element.dom.classList.add(cls.class);
                }
            }


            resolve(center);
        } catch (ex) {
            reject(ex)
        }

    });


}

function getCenter() {
    var center = map.getCenter().toJSON();
    return center;
}

function setCenter(lon, latitude) {
    var position = new AMap.LngLat(lon, latitude); //传入经纬度    
    map.setCenter(position); //简写 设置地图中心点

}

function calcCenter() {

    
}
//画多边形
function DrawPoy(points) {
    
    return new Promise((resolve, reject) => {
        if (!map) {
            reject("map未初始化");
            return;
        }
        if (!points) {
            reject("points未初始化");
            return;
        }
        if (!points.coordinates) {
            reject("coordinates未初始化");
            return;
        }

        if (!Array.isArray(points.coordinates)) {
            points.coordinates = JSON.parse(points.coordinates);
        }

        let path = [];


        setTimeout(() => {
            points.coordinates.filter(v => {
                if (v.lng && v.lat) {
                    path.push(new AMap.LngLat(v.lng, v.lat));
                    layPoints.push({ lng: v.lng, lat: v.lat });
                    return true;
                }
                return false;
            });
            if (!path.length) {
                reject("path为空");
            }
            let polygon = new AMap.Polygon({
                path: path,
                fillColor: '#F00C0C',
                fillOpacity: 0.03,
                strokeOpacity: 0.1,
                strokeColor: '#F00C0C',

                strokeWeight: 3,
                strokeStyle: 'dashed',
                // strokeDasharray: [50,50,50],
                extData: points
            });
            map.add(polygon);
            resolve("添加多边形成功");
        }, 0);
    });


}
//画圆形
function DrawCicle(points, raduis, dragEnd) {
    
    return new Promise((resolve, reject) => {
        if (!map) {
            reject("map未初始化");
            return;
        }
        if (!points) {
            reject("points未初始化");
            return;
        }
        if (!points.coordinates) {
            reject("coordinates未初始化");
            return;
        }

        if (!Array.isArray(points.coordinates)) {
            points.coordinates = JSON.parse(points.coordinates);
        }

        if (!(points.coordinates[0].lng && points.coordinates[0].lat)) {
            reject("圆的中心点不正确")
            return;
        }
        
        let circle = new AMap.Circle({
            center: [points.coordinates[0].lng, points.coordinates[0].lat],
            radius: raduis ? raduis : 1000, //半径
            borderWeight: 3,
            strokeColor: "#F00C0C",
            strokeWeight: 1,
            strokeOpacity: 0.2,
            fillOpacity: 0.4,
            strokeStyle: 'dashed',
            strokeDasharray: [10, 10],
            // 线样式还支持 'dashed'
            fillColor: '#1791fc',
            zIndex: 50,
        })
        map.add(circle);
        layPoints.push({ lng: points.coordinates[0].lng, lat: points.coordinates[0].lat });
        resolve("添加圆成功");
    });



}

//清除所有
function clearOverLays() {
    map && map.clearMap();
    layPoints = [];
}



function removeOverLay(lay) {
    map && map.remove(lay);
}



function setFitView() {
    if (map) { map.setFitView(); }
}
export default {
    gdMap: map,
    initMap: initMap,
    AddPoint: AddPoint,
    getCenter: getCenter,
    DrawPoy: DrawPoy,
    DrawCicle: DrawCicle,
    clearOverLays: clearOverLays,
    removeOverLay: removeOverLay,
    setCenter: setCenter,
    calcCenter: calcCenter,
    setFitView: setFitView
}