(function(KDApi, $) {
    const TYPE_DEVICELIST = "device_list";
    const TYPE_INIT = "device_init";
    const TYPE_DEVICEDETAIL = "device_detail";
    const ZOOM_LEVEL = [4, 6, 9, 12];
    const statusMap = {
        0 : {
            name: "离线",
            color: '#666666',
        },
        1 : {
            name: "运行",
            color: '#40C01E',
        },
        2 : {
            name: "空闲",
            color: '#FFAC2D',
        },

        3 : {
            name: "停机",
            color: '#F15243',
        }
    }

    function MyComopnent(model) {
        this._setModel(model);
    }
    MyComopnent.prototype = {
        _setModel: function(model) {
            this.model = model;
            controller.setModel(model)
        },
        init: function() {
            initHtml(this.model);
            controller.initMap();
        },
        update: function(result) {
            var data = result.data;
            var model = this.model;
            if (!data) {
                return;
            }
            controller.setTipData(data);
        },
        destoryed: function() {
         
        },

    };
    KDApi.register("srvpmc_devicemap", MyComopnent);
    function loadScript() {
        return;
        $.getScript("http://map.qq.com/api/gljs?v=1.exp&key=27VBZ-5ZYKW-AZTRS-O234W-SU342-HRFR5",function(result){
            console.log(result)
        })
       /* $.getScript("http://map.qq.com/api/js?v=2.exp&key=27VBZ-5ZYKW-AZTRS-O234W-SU342-HRFR5",function(result){
            console.log(result)
        })*/
            //
        //创建script标签，并设置src属性添加到body中
       /* $("[src^='https://map.qq.com/api']").remove();
        var javaApi = document.createElement("script");
        javaApi.type = "text/javascript";
        javaApi.src = "https://map.qq.com/api/gljs?v=1.exp&key=27VBZ-5ZYKW-AZTRS-O234W-SU342-HRFR5";
        var javaGL = document.createElement("script");
        javaGL.type = "text/javascript";
        javaGL.src = "https://map.qq.com/api/js?v=2.exp&key=27VBZ-5ZYKW-AZTRS-O234W-SU342-HRFR5";
        document.body.appendChild(javaApi);
        document.body.appendChild(javaGL);*/
    }
    function initHtml(model) {
        loadScript();
        KDApi.loadFile(['./css/deviceMap.css'], model.schemaId,function() {
            KDApi.loadFile(['./lib/map.qq.com.js'], model.schemaId,function() {
                KDApi.templateFilePath('./html/deviceMap.html', model.schemaId, {}).then(function(result) {
                model.dom.innerHTML = result;
            })
          
            })
        })
    }
    
var controller = { //数据桥梁控制
    setModel: function(model) {
            this.model = model;
        },
        getDeviceList:function(param){
            this.model.invoke(TYPE_DEVICELIST, param);
        },
        initTip: function() {
            this.model.invoke(TYPE_INIT, null);
        },
        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 lat = point.getLat();
        var lng = point.getLng();
        var x = 300;
        var y = 400;
        var getBoundsTimer = setInterval(() => {
            var boundary = qqMapObj.map.getBounds();
            if (boundary) {
                clearInterval(getBoundsTimer);
                var ne = boundary.getNorthEast();

                var sw = boundary.getSouthWest();
                var w = $("#allmap").width();
                var h = $("#allmap").height();
                var lng_diff = ne.getLng() - sw.getLng();
                var lat_diff = ne.getLat() - sw.getLat();

                x = w * (lng - sw.getLng()) / lng_diff;
                y = h * (ne.getLat() - lat) / lat_diff;
                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
                }

                tipObj.setFloatTipPosition(x, y)
            }
        }, 100)




    },
    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);
    },
}
    var controller1 = { //数据桥梁控制
        setModel: function(model) {
            this.model = model;
        },
        getDeviceList:function(param){
            this.model.invoke(TYPE_DEVICELIST, param);
        },
        initTip: function() {
            this.model.invoke(TYPE_INIT, null);
        },
        makerClick: function(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 = TMapObj.map.projectToContainer(point);
            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 = TMapObj.mousePoint
            if (!point) {
                return
            }
            var lastLevel = tipObj.level;

            if (level == lastLevel) {
                return;
            }

            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() {
            TMapObj.initMap();

        },
        setTipData: function(data) {
            tipObj.setData(data)
        },
        drawMaker: function(data, key) {
            key = key || "addr";
            TMapObj.drawMaker(data, key);
        },
    }
    var qqMapObj = {
    map: null,
    lastZoom: 4,
    geoAlready: false,
    markers: null,
    idle: false,
    infoWindows: [],
    initMap: function() {
        
        var timerInit = setInterval(function() {
            var elem = document.getElementById("allmap");
            if (elem) {
                clearInterval(timerInit)
                qqMapObj.map = new qq.maps.Map(elem, {
                    center: new qq.maps.LatLng(34.916527, 108.397128),
                    zoom: qqMapObj.lastZoom,
                    mapStyleId: 'style3',
                    zoomControl: false, //隐藏缩放控件
                    panControl: false, //隐藏平移控件
                    mapTypeControlOptions: { mapTypeIds: [], }, //隐藏卫星地图
                });

                qqMapObj.initEvent();
                controller.initTip();
            }

        }, 100)

    },
    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(
                        "isv/kingdee/srvpmc/srvpmc_devicemap/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 TMapObj = {
        map: null,
        lastZoom: 4,
        geoAlready: false,
        markers: null,
        idle: false,
        infoWindows: [],
        initMap: function() {
            var timer = setInterval(function() {
                if (typeof TMap != "undefined") {
                    clearInterval(timer);
                    TMapObj.map = new TMap.Map(document.getElementById("allmap"), {
                        center: new TMap.LatLng(34.916527, 108.397128),
                        zoom: TMapObj.lastZoom,
                        mapStyleId: 'style2'
                    });
                    $(".zoom-control").hide();
                    TMapObj.initEvent();
                }
            },
            100)

        },
        initEvent: function() {
            this.map.on("zoom_changed", (event =>{

                var zoom = event.zoom;
            if (zoom < 6 && this.lastZoom >= 6) {
                controller.mapZoom(0)
            } else if (zoom >= 6 && zoom <= 9 && (this.lastZoom > 9 || this.lastZoom < 6)) { //市级展开
                controller.mapZoom(1)
            } else if (zoom > 9 && zoom < 12 && (this.lastZoom <= 9 || this.lastZoom >= 12)) { //区级展开
                controller.mapZoom(2)
            } else if (zoom >= 12 && this.lastZoom < 12) { //以详细地址展开
                controller.mapZoom(3)
            }
            this.lastZoom = zoom;
        }));
    this.map.on("mousemove",
    function(event) {
        TMapObj.mousePoint = event.latLng;
    })
            
    this.map.on("tilesloaded",
    function(event) {
        if (TMapObj.idle) { //地图已经加载完毕
            return;
        }
        TMapObj.idle = true;
        controller.initTip();
    })

},
drawMaker: function(data, key) {

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

            var geometries = [];

            data.forEach((item, index) => {
                if (!item.location) {
                    return;
        }
        zoom = ZOOM_LEVEL[item.level - 1];
        center = item.location
        var total = item.total;

        let radius = 4;
        if (total > 20) {
            radius = 1
        } else if (total > 10) {
            radius = 2
        } else if (total > 5) {
            radius = 3
        }
        geometries.push({ // 批量点
            position: item.location,
            properties: item,
            styleId: 'marker' + radius
        })
    })

    TMapObj.markers = new TMap.MultiMarker({
        map: TMapObj.map,
        geometries: geometries,
        styles: { //点标注的相关样式
            "marker1": new TMap.MarkerStyle({
                width: 32,
                height: 32,
                src: 'markericon.png',
            }),
            "marker2": new TMap.MarkerStyle({
                width: 24,
                height: 24,
                src: 'markericon.png',
            }),
            "marker3": new TMap.MarkerStyle({
                width: 16,
                height: 16,
                src: 'markericon.png',
            }),
            "marker4": new TMap.MarkerStyle({
                width: 8,
                height: 8,
                src: 'markericon.png',
            })
        },
    });
    TMapObj.markers.on("click",
    function(e) {

        controller.makerClick(e.geometry.properties)
    });

    TMapObj.zoomMap(zoom, center)
}
},
100); //
},
zoomMap: function(zoom, point) {
    if (zoom <= 5) {
        point = new TMap.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) {
                TMapObj.geoAlready = true;
            }
    return;
}
if (item.level == 1) { //省级
    item.location = this.getProvinceCenterPoint(item.name);
    if (dataRow == index + 1) {
        TMapObj.geoAlready = true;
    }
    return;
} else {
    var callbacks = {

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

            console.log("解析地址失败," + item[key] + ",item:", item) ;
            if (dataRow == index + 1) {
                TMapObj.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 TMap.LatLng(provinceCenterData[item][1], provinceCenterData[item][0]);
        }
    }
    console.error(province + "：获取省中心位置失败");
    return null;

}
}

var tipObj = { //提示信息的属性以及对外暴露的接口
    init: function(pdata) {
        this.locations = pdata;
        this.level = 0;
        this.parentName = '中国';
        this.curSelect = '中国';
        this.curLocationData = pdata;
        this.pageIndex = 0;
        this.pageMaxRow = 10;
        this.deviceList = null;
        this.detailData = {};
        this.refresh();
        this.initEvents();
        this.model = null;
    },
    setModel: function(model) {
        this.model = model;
    },
    setFloatTipPosition(x, y) {

        $("#float-tip-container").css("left", x + "px");
$("#float-tip-container").css("top", y + "px")
},
setData: function(data) {
    if (data.type == TYPE_INIT) {
        this.init(data.data)
    }
    if (data.type == TYPE_DEVICELIST) {
        this.deviceList = data.data || [];
        this.setDeviceList();
    }

},

initEvents: function() {
    $("#device-list-container").on("click", ".device-container",
    function(event) {
        var deviceId = this.getAttribute("data-id");
        if (tipObj.level == 3) {

            tipObj.setDeviceDetail(deviceId) ;
            event.stopPropagation();
        } else {
            //var item = null;

            //for (var i = 0; i < tipObj.curLocationData.data.length; i++) {
            //if (tipObj.curLocationData.data[i].locationid == deviceId) {
            // controller.makerClick(tipObj.curLocationData.data[i]);
            //break;
            // }
            // }
            var name = $(this).find(".device-info").text();
            tipObj.triggerSelectChange(name)

        }

    })

    $("#locations").change(function() {
        tipObj.selectChanged();
    });
     $("#back-parent").click(function() {
        tipObj.back()
    });
     $("body").click(function() {
        $("#float-tip-container").hide();
    })
},
setDeviceDetail: function(deviceId) {
    var detailData = null;
    for (var i = 0; i < this.deviceList.length; i++) {
        if (deviceId == this.deviceList[i].id) {
            detailData = this.deviceList[i]
            break;
        }
    }
    if (detailData == null) {
        console.error("detailData is null");
        return;
    }
    $("#device-title-name").text(detailData.name);
    $("#customer-addr").text(detailData.addr);
    $("[data-form-id=device_map_new]").find("#customer-name").text(detailData.customer);
    $("[data-form-id=device_map_new]").find("#customer-contact").text(detailData.contact);
    $("[data-form-id=device_map_new]").find("#customer-phone").text(detailData.phone);
    var status = detailData.status;
    var colorDes = statusMap[status];
    $("[data-form-id=device_map_new]").find(".status-icon").css("background", colorDes.color);
    $("[data-form-id=device_map_new]").find(".status-name").text(colorDes.name);
    $("[data-form-id=device_map_new]").find(".status-name").css("color", colorDes.color);
    var device_tag_container = $("[data-form-id=device_map_new]").find("#device-tag-container");
    device_tag_container.empty;
    var tagData = detailData.tags;
    device_tag_container.empty();
    tagData.forEach(item =>{

        var value =  item.value;
        if(value==null){
            value="";
        }
        var html = "<div class='device-param-row'>" + "<div class='device-param-name'>" + item.name + "</div>" + "<div class='device-param-value'>" +value + "</div>" + "</div>";
    device_tag_container.append(html)
});
    controller.setFloatTipLocation(detailData.location);
    $("#float-tip-container").show();
},
triggerSelectChange: function(value) {

    if (!value) {
        return;
    }
    var elem = $("#locations");
    var options = elem.find("option");
    var option_len = options.length;
    if (option_len == 1) { //只有一个直接赋值
        let text = options[0].innerHTML;
        elem.val(text);
        this.selectChanged();
        return;
    }
    for (var i = 0; i < option_len; i++) {
        let item = options[i];
        let text = item.innerHTML;
        if (value.indexOf(text) >= 0 || text.indexOf(value) >= 0) {
            elem.val(text);
            this.selectChanged();
            break;
        }
    }

},
refresh: function() {
    $("#parentname").text(this.curSelect);
    this.setStatusData();
    this.setSelectData();
    this.level = this.curLocationData.level;
    if (this.level >= 3) {
       if (!this.deviceList) {
            this.getDeviceList();
            return;
        }
        this.setDeviceList();
    } else {
        this.deviceList = null;
        $("#device-list-container").empty();
        controller.drawMaker(this.curLocationData.data);
        this.setLocationInfo();
    }

},

getDeviceList: function() {
    var param = {
        location: this.curLocationData.locationId,
        level: this.curLocationData.level,
        ts:new Date().getTime(),
        //  start:this.pageIndex * this.pageMaxRow,
        //  end:(this.pageIndex+1) * this.pageMaxRow
    }
    controller.getDeviceList(param);
},
setDeviceList: function() {
    var deviceListContainer = $("#device-list-container");
    deviceListContainer.empty();
    var deviceList = this.deviceList;
    deviceList.forEach(item =>{
        var html = "<div class='device-container' data-id=" + item.id + ">" + "<span class='device-info'>" + item.deviceName + "</span>" + "<span class='device-info'>" + item.cusName + "</span>" + "</div>";
    deviceListContainer.append(html);
});
controller.drawMaker(deviceList)
},
setLocationInfo: function() {
    if (!this.curLocationData.data) {
        return;
    }
    var deviceListContainer = $("#device-list-container");
    deviceListContainer.empty();
    var deviceList = this.curLocationData.data;
    deviceList.forEach(item =>{
        var html = "<div class='device-container' data-id=" + item.id + ">" + "<span class='device-info'>" + item.name + "</span>" + "<span class='device-info'>" + item.total + "</span>" + "</div>";
    deviceListContainer.append(html);
})
},
selectChanged: function() {
    var elem = $("#locations");

    var name = elem.val();
    if (!name) {
        return;
    }

    this.parentName = this.curSelect;
    this.pageIndex = 0;
    this.curLocationData = this.getMapFromArray(name);
    this.curSelect = name,

    this.refresh();
},
setStatusData: function() {
    if (!this.curLocationData) {
        return;
    }
    var statusdata = [this.curLocationData.status0 || 0, this.curLocationData.status1 || 0, this.curLocationData.status2 || 0, this.curLocationData.status3 || 0]
    var totalDevice = statusdata.reduce((a, b) =>a + b) ;
    $("#total-device").text(totalDevice);
    $("#status-online").text(statusdata[1] + statusdata[2]);
    $("#status-offline").text(statusdata[0]);
    $("#status-down").text(statusdata[3]);
    var totalWidth = 160;

    var barList = $(".device-status-container-map");
    barList.each((index, item) =>{
        var num = parseInt($(item).find(".status-number").text());
    var barWidth = (totalDevice && totalWidth / totalDevice * num) || 0;
    $(item).find(".bar-has").css("width", barWidth + "px");
    $(item).find(".bar-has-not").css("width", totalWidth - barWidth + "px");
})
},
back: function() {
    var name = this.curSelect;
    if (name == "中国" || !(this.locations && this.locations.data)) {
        return;
    }

    var bFind = false;
    var pname = this.parentName;

    for (var i = 0; i < this.locations.data.length && !bFind; i++) {
        if (this.locations.data[i].name == name && pname == this.locations.name) {
            this.curLocationData = this.locations;
            this.curSelect = pname;
            this.parentName = this.curSelect;
            bFind = true;
            break;
        }
        var p = this.locations.data[i];
        if (! (p && p.data)) {
            continue;
        }

        for (var j = 0; j < p.data.length && !bFind; j++) {
            if (p.data[j].name == name && pname == p.name) {
                this.curLocationData = p;
                bFind = true;
                this.curSelect = pname;
                this.parentName = this.locations.name;
                break;
            }
            var c = p.data[j];
            if (! (c && c.data)) {
                continue;
            }
            for (var k = 0; k < c.data.length && !bFind; k++) {
                if (c.data[k].name == name && pname == c.name) {
                    this.curLocationData = c;
                    bFind = true;
                    this.curSelect = pname;
                    this.parentName = p.name;
                    break;
                }
                var d = c.data[k];
                if (! (d && d.data)) {
                    continue;
                }
                for (var x = 0; x < d.data.length && !bFind; x++) {
                    if (d.data[x].name == name && pname == d.name) {
                        this.curLocationData = d;
                        bFind = true;
                        this.curSelect = pname;
                        this.parentName = c.name;
                        break;
                    }

                }
            }
        }

    }

    if (bFind) {
        this.refresh();
    } else {
        console.error("没有找到父节点，算法错误")
    }
},
setSelectData: function() {

    if (! (this.curLocationData && this.curLocationData.data)) {
        var elem = $("#locations");
        elem.empty();
        elem[0].selectedIndex = -1;
        return;
    }
    var elem = $("#locations");
    elem.empty();

          
    this.curLocationData.data.forEach(item =>{
        var optionHtml = "<option data-id=" + item.id + ">" + item.name + "</option>";
        elem.append(optionHtml);
});
elem[0] &&( elem[0].selectedIndex = -1);
},
getMapFromArray: function(name) {
    if (name == "中国") {
        return this.locations;
    } else {
        if (this.curLocationData && this.curLocationData.data) {
            for (var i = 0; i < this.curLocationData.data.length; i++) {
                var item = this.curLocationData.data[i];
                if (item.name == name) {
                    return item;
                }
            }

        }
    }
}
}
})(KDApi, jQuery);