var MeasureTools = (function() {
    'use strict';
    
    var measureActive = false;
    var measureDraw = null;
    var measureSource = null;
    var measureLayer = null;
    var measureTooltips = [];
    var measureFeatures = [];
    var currentMeasureTooltips = [];
    var currentSketch = null;
    var currentListener = null;
    var segmentTooltips = [];
    var map = null;
    
    function init(mapInstance) {
        map = mapInstance;
        
        // 测距专用图层
        measureSource = new ol.source.Vector();
        measureLayer = new ol.layer.Vector({
            source: measureSource,
            style: new ol.style.Style({
                fill: new ol.style.Fill({ color: 'rgba(255,255,255,0.2)' }),
                stroke: new ol.style.Stroke({ color: '#ffcc33', width: 2 }),
                image: new ol.style.RegularShape({
                    points: 4,
                    radius: 8,
                    radius2: 0,
                    angle: Math.PI / 4,
                    stroke: new ol.style.Stroke({ color: '#ed8936', width: 2 })
                })
            })
        });
        
        if (map) {
            map.addLayer(measureLayer);
        }
    }
    
    function toggleMeasureDistance() {
        if (measureActive) {
            deactivateMeasure();
            if (window.layer && typeof window.layer.msg === 'function') {
                window.layer.msg('测距功能已关闭');
            }
        } else {
            activateMeasure();
            if (window.layer && typeof window.layer.msg === 'function') {
                window.layer.msg('点击左键添加距离节点，点击右键结束测量 :)');
            }
        }
        
        var menu = document.getElementById('mapFunctionsMenu');
        if (menu) {
            menu.classList.remove('show');
        }
    }
    
    function finishMeasuring() {
        if (measureActive && currentSketch && measureDraw) {
            measureDraw.finishDrawing();
        }
    }
    
    function activateMeasure() {
        if (!map || !measureSource) return;
        
        measureActive = true;
        
        // 显示测量状态指示器
        var measureStatus = document.getElementById('measureStatus');
        if (measureStatus) {
            measureStatus.style.display = 'flex';
        }
        
        measureDraw = new ol.interaction.Draw({
            source: measureSource,
            type: 'LineString',
            style: new ol.style.Style({
                fill: new ol.style.Fill({ color: 'rgba(255,255,255,0.2)' }),
                stroke: new ol.style.Stroke({ color: '#ffcc33', width: 2 }),
                image: new ol.style.RegularShape({
                    points: 4,
                    radius: 8,
                    radius2: 0,
                    angle: Math.PI / 4,
                    stroke: new ol.style.Stroke({ color: '#ed8936', width: 2 })
                })
            })
        });
        
        map.addInteraction(measureDraw);

        map.getViewport().addEventListener('contextmenu', function(e) {
            if (measureActive && currentSketch) {
                e.preventDefault();
                measureDraw.finishDrawing();
            }
        });
        
        measureDraw.on('drawstart', function(evt) {
            currentSketch = evt.feature;
            currentMeasureTooltips = [];
            segmentTooltips = [];
            
            currentListener = currentSketch.getGeometry().on('change', function(e) {
                var geom = e.target;
                var coords = geom.getCoordinates();
                
                clearTemporaryTooltips();
                clearSegmentTooltips();
                
                // 计算并显示每个节点的距离
                var total = 0;
                for (var i = 0; i < coords.length; i++) {
                    if (i === 0) {
                        // 起点
                        var startTooltip = createMeasureTooltip(coords[0], '起点');
                        currentMeasureTooltips.push(startTooltip);
                    } else {
                        // 计算段距离
                        var seg = new ol.geom.LineString([coords[i-1], coords[i]]);
                        var segmentLength = ol.sphere.getLength(seg);
                        total += segmentLength;
                        
                        // 显示每个节点的累计距离
                        var output = formatLength(total);
                        var tooltip = createMeasureTooltip(coords[i], output);
                        segmentTooltips.push(tooltip);
                        
                        if (i === coords.length - 1) {
                            currentMeasureTooltips.push(tooltip);
                        }
                    }
                }
            });
        });
        
        // 绘制结束
        measureDraw.on('drawend', function(evt) {
            var coords = evt.feature.getGeometry().getCoordinates();
        
            clearTemporaryTooltips();
            clearSegmentTooltips();
            
            var total = 0;
            for (var i = 0; i < coords.length; i++) {
                if (i === 0) {
                    var startTooltip = createMeasureTooltip(coords[0], '起点', true);
                    measureTooltips.push(startTooltip);
                } else {
                    var seg = new ol.geom.LineString([coords[i-1], coords[i]]);
                    total += ol.sphere.getLength(seg);
                    
                    var output = formatLength(total);
                    var tooltip = createMeasureTooltip(coords[i], output, true);
                    measureTooltips.push(tooltip);
                }
            }
            
            measureFeatures.push(evt.feature);
            
            if (currentListener) {
                ol.Observable.unByKey(currentListener);
            }
            currentSketch = null;
            currentListener = null;
            
            var measureStatus = document.getElementById('measureStatus');
            if (measureStatus) {
                measureStatus.style.display = 'none';
            }
            
            map.removeInteraction(measureDraw);
            measureActive = false;
            
            if (window.layer && typeof window.layer.msg === 'function') {
                window.layer.msg('测量完成');
            }
        });
    }
    
    function deactivateMeasure() {
        measureActive = false;
        
        var measureStatus = document.getElementById('measureStatus');
        if (measureStatus) {
            measureStatus.style.display = 'none';
        }
        
        if (measureDraw && map) {
            map.removeInteraction(measureDraw);
            measureDraw = null;
        }
        
        if (currentListener) {
            ol.Observable.unByKey(currentListener);
            currentListener = null;
        }
        
        currentSketch = null;
        clearTemporaryTooltips();
        clearSegmentTooltips();
    }
    
    function createMeasureTooltip(coord, text, isStatic) {
        var elem = document.createElement('div');
        elem.className = isStatic ? 'ol-tooltip ol-tooltip-static' : 'ol-tooltip ol-tooltip-measure';
        elem.innerHTML = text;
        
        var overlay = new ol.Overlay({
            element: elem,
            offset: [0, -15],
            positioning: 'bottom-center'
        });
        
        overlay.setPosition(coord);
        
        if (map) {
            map.addOverlay(overlay);
        }
        
        return overlay;
    }
    
    function formatLength(length) {
        if (length > 1000) {
            return (Math.round(length / 100) / 10) + ' km';
        } else {
            return (Math.round(length * 10) / 10) + ' m';
        }
    }
    
    function clearAllMeasureTooltips() {
        if (!map) return;
        
        for (var i = 0; i < measureTooltips.length; i++) {
            map.removeOverlay(measureTooltips[i]);
        }
        measureTooltips = [];
        
        clearTemporaryTooltips();
    }
    
    function clearTemporaryTooltips() {
        if (!map) return;
        
        for (var i = 0; i < currentMeasureTooltips.length; i++) {
            map.removeOverlay(currentMeasureTooltips[i]);
        }
        currentMeasureTooltips = [];
    }
    
    function clearSegmentTooltips() {
        if (!map) return;
        
        for (var i = 0; i < segmentTooltips.length; i++) {
            map.removeOverlay(segmentTooltips[i]);
        }
        segmentTooltips = [];
    }
    
    function clearMeasure() {
        if (measureSource) {
            measureSource.clear();
        }
        
        clearAllMeasureTooltips();
        measureFeatures = [];
        
        if (window.layer && typeof window.layer.msg === 'function') {
            window.layer.msg('测距标记已清除');
        }
        
        // 关闭地图功能菜单
        var menu = document.getElementById('mapFunctionsMenu');
        if (menu) {
            menu.classList.remove('show');
        }
    }
    
    function isActive() {
        return measureActive;
    }
    
    function getMeasureCount() {
        return measureFeatures.length;
    }
    
    return {
        init: init,
        toggleMeasureDistance: toggleMeasureDistance,
        finishMeasuring: finishMeasuring,
        clearMeasure: clearMeasure,
        isActive: isActive,
        getMeasureCount: getMeasureCount
    };
})(); 