var qqMapObj = {
    map: null,
    lastZoom: 4,
    geoAlready: false,
    markers: null,
    idle: false,
    infoWindows: [],
    initMap: function() {
        this.map = new qq.maps.Map(document.getElementById("allmap"), {
            center: new qq.maps.LatLng(34.916527, 108.397128),
            zoom: this.lastZoom,
            mapStyleId: 'style1'
        });
        $(".zoom-control").hide();
        this.initEvent();
    },
    initEvent: function() {
        qq.maps.event.addListener(this.map, "zoom_changed", (event => {
            var zoom = event.target.zoom;
            if (zoom < 6 && qqMapObj.lastZoom >= 6) {
                controller.mapZoom(0)
            } else if (zoom >= 6 && zoom < 9 && (qqMapObj.lastZoom >= 9 || qqMapObj.lastZoom < 6)) { //市级展开
                controller.mapZoom(1)
            } else if (zoom >= 9 && zoom < 12 && (qqMapObj.lastZoom < 9 || qqMapObj.lastZoom >= 12)) { //区级展开
                controller.mapZoom(2)
            } else if (zoom >= 12 && qqMapObj.lastZoom < 12) { //以详细地址展开
                controller.mapZoom(3)
            }
            qqMapObj.lastZoom = zoom;
        }))
        qq.maps.event.addListener(this.map, "mousemove", function(event) {
            qqMapObj.mousePoint = event.latLng;
        })
        qq.maps.event.addListener(this.map, "tilesloaded", function(event) {
            if (qqMapObj.idle) { //地图已经加载完毕
                return;
            }
            qqMapObj.idle = true;
            controller.initTip();
        })


    },
    drawMaker: function(data, key) {

        if (qqMapObj.markers && qqMapObj.markers.length > 0) {
            qqMapObj.markers.forEach(item => {
                item.setMap(null);
            })
        }
        qqMapObj.markers = [];
        qqMapObj.infoWindows.forEach(item => {
            item.setMap(null)
        });
        if (!(data && data.length)) {
            console.log("木有数据了")
            return;
        }
        this.getItemLocation(data, key);
        var timerGeo = setInterval(function() {
            if (qqMapObj.geoAlready) { //地址解析完毕
                clearInterval(timerGeo);
                var zoom = qqMapObj.lastZoom;
                var center = qqMapObj.map.getCenter();
                data.forEach((item, index) => {
                    if (!item.location) {
                        return;
                    }
                    zoom = ZOOM_LEVEL[item.level - 1];
                    center = item.location
                    var total = item.total;

                    let radius = 1;
                    if (total > 20) {
                        radius = 4
                    } else if (total > 10) {
                        radius = 3
                    } else if (total > 5) {
                        radius = 2
                    }
                    var marker = new qq.maps.Marker({
                        //设置Marker的位置坐标
                        position: item.location,
                        //设置显示Marker的地图
                        map: qqMapObj.map,

                    });
                    item.total && (marker.setTitle(item.name + ":" + item.total))
                    qq.maps.event.addListener(marker, 'click', function(event) {
                        controller.makerClick(item);
                        console.log(event)
                        event.event.stopPropagation();
                    });
                    marker.setIcon(new qq.maps.MarkerImage(
                        "marker" + radius + ".png"
                    ));
                    qqMapObj.markers.push(marker);
                })


                /* qqMapObj.markers.on("click", function(e) {

                     controller.makerClick(e.geometry.properties)
                 });*/
                console.log("markers", zoom)
                qqMapObj.zoomMap(zoom, center)
            }
        }, 100); //

    },
    zoomMap: function(zoom, point) {
        if (zoom <= 5) {
            point = new qq.maps.LatLng(34.916527, 108.397128)
        }

        this.map.setCenter(point);
        var curZoom = parseInt(this.map.getZoom());
        if (zoom != curZoom) {
            this.map.setZoom(zoom);
            this.lastZoom = zoom;
        }

    },

    getItemLocation: function(data, key) {

        if (!data) {

            return;
        }
        this.geoAlready = false;
        var dataRow = data.length;
        data.forEach((item, index) => {
            if (item.location) {
                if (dataRow == index + 1) {
                    qqMapObj.geoAlready = true;
                }
                return;
            }
            if (item.level == 1) { //省级
                item.location = this.getProvinceCenterPoint(item.name);
                if (dataRow == index + 1) {
                    qqMapObj.geoAlready = true;
                }
                return;
            } else {
                var callbacks = {

                    complete: function(result) {
                        console.log("解析地址:" + item[key], result.detail)
                        var detail = result.detail;
                        if (detail) { //解析成功
                            item.location = new qq.maps.LatLng(detail.location.lat, detail.location.lng);
                        }
                        if (dataRow == index + 1) {
                            qqMapObj.geoAlready = true;
                        }
                    },
                    error: function(result) {

                        console.log("解析地址失败," + item[key] + ",item:", item)
                        if (dataRow == index + 1) {
                            qqMapObj.geoAlready = true;
                        }
                    }

                }
                var addr = item[key]
                var geocoder = new qq.maps.Geocoder(callbacks); // 地址解析器
                geocoder.getLocation(addr);

            }
        })



    },
    getProvinceCenterPoint: function(province) {
        if (!province) {
            return;
        }
        var provinceCenterData = {
            '山东': [117.000923, 36.675807],
            '河北': [115.48333, 38.03333],
            '吉林': [125.35000, 43.88333],
            '黑龙江': [127.63333, 47.75000],
            '辽宁': [123.38333, 41.80000],
            '内蒙古': [111.670801, 41.818311],
            '新疆': [87.68333, 43.76667],
            '甘肃': [103.73333, 36.03333],
            '宁夏': [106.26667, 37.46667],
            '山西': [112.53333, 37.86667],
            '陕西': [108.95000, 34.26667],
            '河南': [113.65000, 34.76667],
            '安徽': [117.283042, 31.86119],
            '江苏': [119.78333, 32.05000],
            '浙江': [120.20000, 30.26667],
            '福建': [118.30000, 26.08333],
            '广东': [113.23333, 23.16667],
            '江西': [115.90000, 28.68333],
            '海南': [110.35000, 20.01667],
            '广西': [108.320004, 22.82402],
            '贵州': [106.71667, 26.56667],
            '湖南': [113.00000, 28.21667],
            '湖北': [114.298572, 30.584355],
            '四川': [104.06667, 30.66667],
            '云南': [102.73333, 25.05000],
            '西藏': [91.00000, 30.60000],
            '青海': [96.75000, 36.56667],
            '天津': [117.20000, 39.13333],
            '上海': [121.55333, 31.20000],
            '重庆': [106.45000, 29.56667],
            '北京': [116.41667, 39.91667],
            '台湾': [121.30, 25.03],
            '香港': [114.10000, 22.20000],
            '澳门': [113.50000, 22.20000],
        }

        for (var item in provinceCenterData) {
            if (province.substr(0, item.length) == item) {
                return new qq.maps.LatLng(provinceCenterData[item][1], provinceCenterData[item][0]);
            }
        }
        console.error(province + "：获取省中心位置失败")
        return null;

    }
}

var controller = { //数据桥梁控制
    initTip: function() {
        update(1)
        setTimeout(function() {

        }, 2000)

    },
    makerClick: function(item) {
        console.log(item)
        if (item.level == 4) {
            tipObj.setDeviceDetail(item.id)
        } else {
            /* var infoWindow = new TMap.InfoWindow({
                 map: TMapObj.map,
                 position: item.location, //设置信息框位置
                 content: item.name + ":" + item.total //设置信息框内容
             });*/
            //TMapObj.infoWindows.push(infoWindow)
        }

    },

    setFloatTipLocation: function(point) {
        var t = { x: 300, y: 500 }
        var x = t.x;
        var y = t.y;
        var win_x = document.body.clientWidth;
        var win_y = document.body.clientHeight;

        if (x + 240 > win_x) {
            x = x - 240;
        }
        if (y + 200 > win_y) {
            y = y - 200
        }
        console.log("提示框位置:", t.x, t.y, x, y)
        tipObj.setFloatTipPosition(x, y)
    },
    mapZoom: function(level) {

        var point = qqMapObj.mousePoint
        if (!point) {
            return
        }
        var lastLevel = tipObj.level;

        if (level == lastLevel) {
            return;
        }
        console.log(level, lastLevel)
        var callback = {
            complete: function(result) {
                if (lastLevel > level) {
                    tipObj.back();
                } else if (lastLevel < level) {
                    var name = null;
                    if (level == 1) {
                        name = result.detail.addressComponents.province
                    } else if (level == 2) {
                        name = result.detail.addressComponents.city
                    } else if (level == 3) {
                        name = result.detail.addressComponents.district
                    } else if (level > 3) {
                        tipObj.setDeviceList();
                    }
                    if (name) {
                        tipObj.triggerSelectChange(name)
                    }
                }
            },
            error: function() {
                console.log("解析坐标失败");
            }
        }
        var geocoder = new qq.maps.Geocoder(callback);

        var qqmapPoint = new qq.maps.LatLng(point.lat, point.lng)
        geocoder.getAddress(qqmapPoint);

    },
    initMap: function() {
        qqMapObj.initMap();

    },
    setTipData: function(data) {
        tipObj.setData(data)
    },
    drawMaker: function(data, key) {
        key = key || "addr"
        qqMapObj.drawMaker(data, key);
    },
}