<template>
	<div id="container"></div> 
</template>

<script>
    import Vue from 'vue';

	export default {
		data() {
			return {
				
			}
		},
		methods: {
            getMap() {
                var _this = this
                this.http.post( this.port.map.mapList, {},
                res => {
                    if (res.code == "ok") {
                        var list = res.data;

                        if(list != null && list.length > 0){
                            var map = new AMap.Map('container', {
                                resizeEnable: true,   
                                zoom: 5
                            });
                            map.clearMap();  
                            var markers = [] , 
                                infoWindow , 
                                data = list;

                            var marker;
                            for(var i in data){
                                var jfong=[ data[i].ylng , data[i].xlat];
                                marker = new AMap.Marker({
                                    position: jfong,
                                    zIndex: 101,
                                    map:map
                                });	
                                marker.setMap(map);	
                                marker.msg = data[i];
                                marker.on('click', function(data){
                                    var str = "<div class='window'>" +
                                        "<div class='info-top'><div>"+ data.target.msg.companyName +"</div><i class='el-icon-close' @click='closeInfoWindow()'></i></div>" +
                                        "<div class='info-middle'>";
                                        for(var i in data.target.msg.list){
                                            str += "<div class='info-item'><a @click='jumpToMold("+ data.target.msg.list[i].id +")'>" + data.target.msg.list[i].modelName + "（" + data.target.msg.list[i].modelNo + "）</a>"
                                                if(data.target.msg.list[i].state=='0'){
                                                    str += "<span class='info-state'><span class='info-ball' style='background:#999999;'></span>静止</span>"
                                                } else {
                                                    str += "<span class='info-state'><span class='info-ball' style='background:#00CD66;'></span>运行</span>"
                                                }
                                            str += "</div>"
                                        }
                                        str += "</div>" +
                                    "</div>"

                                    var MyComponent = Vue.extend({
                                        template: str ,
                                        methods:{
                                            closeInfoWindow:function() {
                                                map.clearInfoWindow();
                                            },
                                            jumpToMold:function(id) {
                                                _this.$router.push("/moldList/" + id + "/0");
                                            }
                                        }
                                    });
                                    var component= new MyComponent().$mount();
                                    infoWindow.setContent(component.$el);
                                    infoWindow.open(map, data.lnglat);
                                });
                            }

                            infoWindow = new AMap.InfoWindow({
                                isCustom:	true,
                                draggable: true,  //是否可拖动
                                showShadow: true,
                                autoMove: true,
                                offset: new AMap.Pixel(0, -31),
                                content:""
                            });

                            marker.setMap(map);
                        }
                    } else {
                        this.$message({
                            message: res.msg,
                            type: "error"
                        });
                    }
                },
                error => {
                    this.$message({
                        message: error,
                        type: "error"
                    });
                });
            },
        },
        mounted() {
            //this.getMap();

            this.$el.style.height = (window.innerHeight - 100) + "px";
            const that = this;
            window.onresize = function temp() {
                that.$el.style.height = (window.innerHeight - 100) + "px";
            };

            //新地图
            var map = new AMap.Map('container', {
                zoom: 4,
                //mapStyle: "amap://styles/grey",
                mapStyle: "amap://styles/8016abec658e1132508723183f848f14",
                features: ['bg']
            });

            var _this = this;
            //加载相关组件
            AMapUI.load(['ui/geo/DistrictCluster', 'ui/misc/PointSimplifier', 'lib/$' ,  'lib/utils'], function(DistrictCluster, PointSimplifier , $ , utils) {

                window.DistrictCluster = DistrictCluster;

                //启动页面
                var pointSimplifierIns = new PointSimplifier({
                    map: map, //所属的地图实例
                    autoSetFitView: false, //禁止自动更新地图视野
                    zIndex: 110,
                    getPosition: function(item) {
                        if (!item) {
                            return null;
                        }
                        //var parts = item.split(',');
                        //返回经纬度
                        //return [parseFloat(parts[0]), parseFloat(parts[1])];
                        return [parseFloat(item.lng), parseFloat(item.lat)];
                    },
                    getHoverTitle: function(dataItem, idx) {
                        var state = "";
                        if(dataItem.state == '0'){
                            state = "静止"
                        } else if(dataItem.state == '1'){
                            state = "运动"
                        } else if(dataItem.state == '2'){
                            state = "告警"
                        } else if(dataItem.state == '3'){
                            state = "报废"
                        }
                        return dataItem.modelName + '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;' + state;
                    },
                    renderOptions: {
                        //点的样式
                        pointStyle: {
                            width: 6,
                            height: 6,
                            fillStyle:'rgba(0, 236, 252, 0.9)'
                        },
                        //鼠标hover时的title信息
                        hoverTitleStyle: {
                            position: 'top'
                        }
                    }
                });

                function MyRender(distClusterIns, opts) {
                    //直接调用父类的构造函数
                    MyRender.__super__.constructor.apply(this, arguments);
                }

                //继承默认引擎
                utils.inherit(MyRender, DistrictCluster.Render.Default);

                utils.extend(MyRender.prototype, {
                    drawFeaturePolygons: function(ctx, polygons, styleOptions, feature, dataItems) {
                        //调用父类方法
                        MyRender.__super__.drawFeaturePolygons.apply(this, arguments);

                        //直接绘制聚合信息
                        this.drawMyLabel(feature, dataItems);
                    },
                    _initContainter: function() {
                        //调用父类方法
                        MyRender.__super__._initContainter.apply(this, arguments);

                        //创建一个新的canvas
                        this._createCanvas('mylabel', this._container);
                    },
                    /**
                     * 绘制一个蓝底白字的label替代聚合标注
                     */
                    drawMyLabel: function(feature, dataItems) {
                        //if(dataItems.length != 0){
                            var pixelRatio = this.getPixelRatio(); //高清下存在比例放大

                            var containerPos = map.lngLatToContainer(feature.properties.centroid || feature.properties.center);

                            var labelCtx = this._getCanvasCxt('mylabel');

                            //文字的中心点
                            var centerX = containerPos.getX() * pixelRatio,
                                centerY = containerPos.getY() * pixelRatio;

                            labelCtx.save();

                            labelCtx.font = 12 * pixelRatio + 'px 微软雅黑';
                            
                            var name = feature.properties.name;
                            if(feature.properties.level == "province") {
                                if(name == "黑龙江省" || name == "内蒙古自治区"){
                                    name = name.substring(0,3)
                                } else {
                                    name = name.substring(0,2)
                                }
                            }
                            var text = name;//feature.properties.name ;//+ '\n' + dataItems.length;
                            var textMetrics = labelCtx.measureText(text);
                            var halfTxtWidth = textMetrics.width / 2;

                            var num = dataItems.length;
                            var numMetrics = labelCtx.measureText(num);
                            var halfNumWidth = numMetrics.width / 2;

                            // labelCtx.fillStyle = 'rgba(3 , 94 , 255 , 0.5)';//'#3366cc';
                            
                            labelCtx.beginPath();
                            labelCtx.fillStyle = 'rgba(12 , 239 , 231 , 0.8)';//'#3366cc';

                            //绘制一个蓝色背景
                            labelCtx.strokeStyle= "rgba(12 , 239 , 231 , 0.65)"
                            labelCtx.fillStyle = 'rgba(12 , 239 , 231 , 0.65)';
                            
                            var radius = 0;
                            if(textMetrics.width > numMetrics.width) {
                                radius = (textMetrics.width + 6 * pixelRatio) / 2;
                            } else {
                                radius = (numMetrics.width + 6 * pixelRatio) / 2;
                            }

                            labelCtx.arc(centerX , centerY, radius + 6,
                                0*Math.PI, 2*Math.PI, false);

                            labelCtx.closePath();
                            labelCtx.fill();
                            // labelCtx.fillRect(centerX - halfTxtWidth - 3 * pixelRatio,
                            //     centerY - 11 * pixelRatio,
                            //     textMetrics.width + 6 * pixelRatio,
                            //     22 * pixelRatio);

                            labelCtx.fillStyle = '#ffffff';
                            labelCtx.textBaseline = 'middle';
                            //labelCtx.stroke();

                            labelCtx.fillText(text, centerX - halfTxtWidth, centerY - 5);
                            labelCtx.fillText(num , centerX - halfNumWidth, centerY + 12);

                            labelCtx.stroke();
                            labelCtx.restore();
                        //}
                    }
                });

                var distCluster = new DistrictCluster({
                    zIndex: 100,
                    map: map, //所属的地图实例
                    getPosition: function(item) {
                        if (!item) {
                            return null;
                        }
                        // var parts = item.split(',');
                        //返回经纬度
                        //return [parseFloat(parts[0]), parseFloat(parts[1])];
                        return [parseFloat(item.lng), parseFloat(item.lat)];
                    },
                    renderConstructor: MyRender,
                    //特定区划级别的默认样式
                    renderOptions: {
                        getClusterMarker: null,
                        featureClickToShowSub: true,
                        featureStyle: {
                            lineWidth: 2, //描边线宽
                            // strokeStyle: 'rgba(0, 119, 180, 0.5)', //描边色
                            strokeStyle: 'rgba(75, 143, 239, 0.5)', //描边色
                            //鼠标Hover后的样式
                            hoverOptions: {
                                fillStyle: 'rgba(255,255,255,0.2)'
                            }
                        },
                        getFeatureStyle: function(feature, dataItems) {
                            return {
                                fillStyle: ''
                            };
                        }
                    },
                });

                window.distCluster = distCluster;

                map.on('zoomend', function() {
                    var zoom = map.getZoom();
                    //获取 pointStyle
                    var pointStyle = pointSimplifierIns.getRenderOptions().pointStyle;
                    //根据当前zoom调整点的尺寸
                    pointStyle.width = pointStyle.height = 2 * Math.pow(1.2, map.getZoom() - 3);
                });

                var zoom = map.getZoom();
                //获取 pointStyle
                var pointStyle = pointSimplifierIns.getRenderOptions().pointStyle;
                //根据当前zoom调整点的尺寸
                pointStyle.width = pointStyle.height = 2 * Math.pow(1.2, map.getZoom() - 3);

                $('<div id="loadingTip">加载数据，请稍候...</div>').appendTo(document.body);
                // $.get('https://a.amap.com/amap-ui/static/data/10w.txt', function(csv) {
                
                //     $('#loadingTip').remove();
                //     var data = csv.split('\n');
                //     distCluster.setData(data);
                //     pointSimplifierIns.setData(data);
                // });
                _this.http.post( _this.port.map.newMap, {},
                res => {
                    $('#loadingTip').remove();
                    var data = res.data;
                    distCluster.setData(data);
                    pointSimplifierIns.setData(data);
                },
                error => {
                    _this.$message({
                        message: error,
                        type: "error"
                    });
                })
            });
        }
	}

</script>

<style scoped lang="scss">
    #container {
        width: 100%; 
        margin-top: 10px;
    }  
</style>
