<?php
/**
 * Black Maps Block Template
 * WordPress标准地图区块模板
 */

// 防止直接访问
if (!defined('ABSPATH')) {
    exit;
}

// 获取简码参数或使用默认值
global $black_maps_shortcode_atts;
$atts = isset($black_maps_shortcode_atts) ? $black_maps_shortcode_atts : array();

// 设置默认参数
$map_id = !empty($atts['id']) ? esc_attr($atts['id']) : 'black-maps-' . uniqid();
$map_class = !empty($atts['class']) ? esc_attr($atts['class']) : '';
$map_height = !empty($atts['height']) ? esc_attr($atts['height']) : get_theme_mod('black_maps_height', '100vh');
$background_color = get_theme_mod('black_maps_bg_color', '#f8f9fa');
$title = get_theme_mod('black_maps_title', 'Global Layout');
$subtitle = get_theme_mod('black_maps_subtitle', 'Global Service Operations: Remote diagnostics with 2-hour onsite response in key markets');
?>

<div class="black-maps-wrapper <?php echo $map_class; ?>" id="<?php echo esc_attr($map_id); ?>-wrapper" style="background-color: <?php echo esc_attr($background_color); ?>; height: <?php echo esc_attr($map_height); ?>;">
    <div id="<?php echo esc_attr($map_id); ?>" class="black-maps-container">
        <div class="black-maps-loading"><?php _e('Loading map...', 'nenghui-energy-theme'); ?></div>
    </div>
</div>

<script type="text/javascript">
// 等待所有资源加载完成
(function() {
    function initMapWhenReady() {
        // 检查jQuery和ECharts是否都已加载
        if (typeof jQuery === 'undefined') {
            setTimeout(initMapWhenReady, 100);
            return;
        }
        
        if (typeof echarts === 'undefined') {
            setTimeout(initMapWhenReady, 100);
            return;
        }
        
        // 使用jQuery执行初始化
        jQuery(document).ready(function($) {
            'use strict';
    
    // 初始化地图函数
    function initBlackMap() {
        var mapContainer = document.getElementById('<?php echo esc_js($map_id); ?>');
        if (!mapContainer) {
            console.error('Map container not found');
            return;
        }
        
        // 清除加载提示
        $(mapContainer).find('.black-maps-loading').remove();
        
        var chart = echarts.init(mapContainer);
        
        // 从自定义器获取配置
        var mapConfig = {
            title: '<?php echo esc_js($title); ?>',
            subtitle: '<?php echo esc_js($subtitle); ?>',
            backgroundColor: '<?php echo esc_js(get_theme_mod("black_maps_chart_bg", "transparent")); ?>',
            titleColor: '<?php echo esc_js(get_theme_mod("black_maps_title_color", "#333")); ?>',
            titleSize: <?php echo intval(get_theme_mod('black_maps_title_size', 20)); ?>,
            chinaColor: '<?php echo esc_js(get_theme_mod("black_maps_china_color", "#e74c3c")); ?>',
            targetColor: '<?php echo esc_js(get_theme_mod("black_maps_target_color", "#2eb6aa")); ?>',
            lineColor: '<?php echo esc_js(get_theme_mod("black_maps_line_color", "#FFFFFF")); ?>',
            effectColor: '<?php echo esc_js(get_theme_mod("black_maps_effect_color", "#0080ff")); ?>'
        };
        
        // 获取自定义国家数据
        var customCountries = <?php echo json_encode(get_theme_mod('black_maps_countries', array())); ?>;
        
        // 国家代码到全称的映射表
        var countryNames = {
            'Shanghai': 'Shanghai',
            'NL': 'Netherlands',
            'BE': 'Belgium', 
            'CZ': 'Czech Republic',
            'IQ': 'Iraq',
            'ES': 'Spain',
            'PL': 'Poland',
            'FR': 'France',
            'RO': 'Romania',
            'IN': 'India',
            'VN': 'Vietnam',
            'ID': 'Indonesia',
            'TH': 'Thailand',
            'DE': 'Germany',
            'IT': 'Italy',
            'AE': 'United Arab Emirates'
        };
        
        /*
            图中相关城市经纬度,根据你的需求添加数据
            关于国家的经纬度，可以用首都的经纬度或者其他城市的经纬度
        */
        var geoCoordMap = {
            // 起点城市
            'Shanghai': [121.4737, 31.2304],
            // 目标国家坐标 (使用国家英文简写作为键)
            'NL': [5.291265999999999, 52.132633],
            'BE': [4.469936, 50.503887],
            'CZ': [15.472962, 49.81749199999999],
            'IQ': [43.679291, 33.223191],
            'ES': [-3.74922, 40.46366700000001],
            'PL': [19.145136, 51.919438],
            'FR': [2.213749, 46.227638],
            'RO': [24.96676, 45.943161],
            'IN': [78.96288, 20.593684],
            'VN': [108.277199, 14.058324],
            'ID': [113.921327, -0.789275],
            'TH': [100.992541, 15.870032],
            'DE': [10.451526, 51.165691],
            'IT': [12.56738, 41.87194],
            'AE': [55.296249, 25.276987]
        };

        // 上海到全球15个国家的贸易路线数据 (保持与geoCoordMap中的键一致)
        var globalTradeData = [
            [{ name: 'Shanghai' }, { name: "NL", value: 30 }],
            [{ name: 'Shanghai' }, { name: "BE", value: 30 }],
            [{ name: 'Shanghai' }, { name: "CZ", value: 30 }],
            [{ name: 'Shanghai' }, { name: "IQ", value: 30 }],
            [{ name: 'Shanghai' }, { name: "ES", value: 30 }],
            [{ name: 'Shanghai' }, { name: "PL", value: 30 }],
            [{ name: 'Shanghai' }, { name: "FR", value: 30 }],
            [{ name: 'Shanghai' }, { name: "RO", value: 30 }],
            [{ name: 'Shanghai' }, { name: "IN", value: 30 }],
            [{ name: 'Shanghai' }, { name: "VN", value: 30 }],
            [{ name: 'Shanghai' }, { name: "ID", value: 30 }],
            [{ name: 'Shanghai' }, { name: "TH", value: 30 }],
            [{ name: 'Shanghai' }, { name: "DE", value: 30 }],
            [{ name: 'Shanghai' }, { name: "IT", value: 30 }],
            [{ name: 'Shanghai' }, { name: "AE", value: 30 }]
        ];

        // 小飞机的图标，可以用其他图形替换
        var planePath =
            'path://M720.384 237.824H307.6608c-38.7072 0-70.0928 31.3856-70.0928 70.0928v403.712c0 22.9376 11.0592 43.2128 28.0576 56.0128 22.1184 3.328 44.6976 5.0688 67.7376 5.0688 101.4784 0 195.1232-33.536 270.4896-90.1632l-75.9296-128.5632-56.1664 51.7632-12.6464 86.0672c-1.0752 7.3728-10.8032 9.2672-14.592 2.816l-42.8544-73.216-75.6224-45.056c-6.4-3.7888-4.4032-13.5168 2.9184-14.5408l87.6544-12.2368 52.2752-54.6304-138.2912-79.872a8.3968 8.3968 0 0 1-1.8944-13.056l18.944-20.0704c1.8944-1.9968 4.7104-2.9696 7.424-2.5088l194.6112 31.1296 72.3456-75.6224c19.2-20.0192 51.2-20.0192 70.3488 0.0512 18.7904 19.712 17.8176 50.944-2.2016 69.4272l-72.6528 66.9696 25.7024 177.92c86.784-82.176 140.9024-198.4512 140.9024-327.3728 0-16.2304-0.8704-32.3072-2.56-48.0768-11.9296-21.504-34.8672-36.0448-61.184-36.0448z';
        // 获取地图中起点和终点的坐标，以数组形式保存下来
        var convertData = function(data) {
            var res = [];
            for (var i = 0; i < data.length; i++) {
                var dataItem = data[i];
                var fromCoord = geoCoordMap[dataItem[0].name];
                var toCoord = geoCoordMap[dataItem[1].name];
                if (fromCoord && toCoord) {
                    res.push([{
                        coord: fromCoord // 起点坐标
                    }, {
                        coord: toCoord // 终点坐标
                    }])
                }
            }
            return res;
        }

        var color = [mapConfig.effectColor, mapConfig.effectColor, mapConfig.lineColor]; // 自定义图中要用到的颜色
        var series = []; // 用来存储地图数据

        [
            ['Shanghai', globalTradeData]
        ].forEach(function(item, i) {
            series.push({
                // 白色航线特效图
                type: 'lines',
                zlevel: 1, // 用于分层，z-index的效果
                effect: {
                    show: true, // 动效是否显示
                    period: 6, // 特效动画时间
                    trailLength: 0.7, // 特效尾迹的长度
                    color: '#fff', // 特效颜色
                    symbolSize: 3 // 特效大小
                },
                lineStyle: {
                    normal: { // 正常情况下的线条样式
                        color: color[2],
                        width: 0, // 因为是叠加效果，要是有宽度，线条会变粗，白色航线特效不明显
                        curveness: -0.2 // 线条曲度
                    }
                },
                data: convertData(item[1]) // 特效的起始、终点位置
            }, { // 小飞机航线效果
                type: 'lines',
                zlevel: 2,
                //symbol: ['none', 'arrow'],   // 用于设置箭头
                symbolSize: 10,
                effect: {
                    show: true,
                    period: 6,
                    trailLength: 0,
                    // symbol: planePath, // 特效形状，可以用其他svg pathdata路径代替
                    symbolSize: 5
                },
                lineStyle: {
                    normal: {
                        color: color[2],
                        width: 1,
                        opacity: 0.6,
                        curveness: -0.2
                    }
                },
                data: convertData(item[1]) // 特效的起始、终点位置，一个二维数组，相当于coords: convertData(item[1])
            }, { // 散点效果
                type: 'effectScatter',
                coordinateSystem: 'geo', // 表示使用的坐标系为地理坐标系
                zlevel: 3,
                rippleEffect: {
                    brushType: 'stroke', // 波纹绘制效果
                    period: 4,
                    scale: 2.5
                },
                // 添加鼠标交互动画
                animationDelay: function (idx) {
                    return idx * 100;
                },
                label: {
                    normal: { // 默认隐藏文本标签
                        show: false
                    },
                    emphasis: { // 鼠标悬停时显示标签
                        show: true,
                        position: 'top',
                        formatter: '{b}',
                        textStyle: {
                            color: '#333',
                            fontSize: 12,
                            fontWeight: 'bold',
                            textShadowColor: '#fff',
                            textShadowBlur: 2
                        }
                    }
                },
                itemStyle: {
                    normal: {
                        color: color[0],
                        shadowBlur: 10,
                        shadowColor: 'rgba(0, 0, 0, 0.3)'
                    },
                    emphasis: {
                        color: color[0],
                        shadowBlur: 20,
                        shadowColor: 'rgba(0, 0, 0, 0.5)',
                        scale: 1.2
                    }
                },
                data: item[1].map(function(dataItem) {
                    return {
                        name: dataItem[1].name,
                        value: geoCoordMap[dataItem[1].name], // 目标国家的位置
                        symbolSize: dataItem[1].value / 6, // 增大散点大小，更突出显示目标国家
                    };
                })
            });
        });

        // 显示终点位置,类似于上面最后一个效果，放在外面写，是为了防止被循环执行多次
        series.push({
            type: 'effectScatter',
            coordinateSystem: 'geo',
            zlevel: 3,
            rippleEffect: {
                brushType: 'stroke',
                period: 4,
                scale: 2.5
            },
            // 添加鼠标交互动画
            animationDelay: function (idx) {
                return idx * 50;
            },
            label: {
                normal: {
                    show: false // 默认隐藏标签
                },
                emphasis: { // 鼠标悬停时显示标签
                    show: true,
                    position: 'left',
                    formatter: '{b}',
                    textStyle: {
                        color: '#333',
                        fontSize: 20,
                        fontWeight: 'bold',
                        textShadowColor: '#fff',
                        textShadowBlur: 3
                    }
                }
            },
            symbolSize: function(val) {
                return val[2] / 6; // 增大上海起点的散点大小
            },
            itemStyle: {
                normal: {
                    color: color[1],
                    shadowBlur: 15,
                    shadowColor: 'rgba(0, 0, 0, 0.4)'
                },
                emphasis: {
                    color: color[1],
                    shadowBlur: 25,
                    shadowColor: 'rgba(0, 0, 0, 0.6)',
                    scale: 1.3
                }
            },
            data: [{
                name: 'Shanghai',
                value: [121.4737, 31.2304, 30],
                itemStyle: {
                    normal: {
                        shadowBlur: 15,
                        shadowColor: 'rgba(0, 0, 0, 0.4)'
                    },
                    emphasis: {
                        shadowBlur: 25,
                        shadowColor: 'rgba(0, 0, 0, 0.6)',
                        scale: 1.3
                    }
                },
                label: {
                    normal: {
                        show: false // 默认隐藏上海标签
                    },
                    emphasis: { // 鼠标悬停时显示标签
                        show: true,
                        position: 'right',
                        textStyle: {
                            color: '#333',
                            fontSize: 12,
                            fontWeight: 'bold',
                            textShadowColor: '#fff',
                            textShadowBlur: 3
                        }
                    }
                }
            }]
        });

        // 如果有自定义国家数据，合并到默认数据中
        if (customCountries && customCountries.length > 0) {
            customCountries.forEach(function(country) {
                if (country.code && country.lat && country.lng) {
                    geoCoordMap[country.code] = [parseFloat(country.lng), parseFloat(country.lat)];
                    globalTradeData.push([{ name: 'Shanghai' }, { name: country.code, value: parseInt(country.value) || 30 }]);
                }
            });
        }
        
        // 配置地图选项
        var mapOption = {
            backgroundColor: mapConfig.backgroundColor,
            title: {
                text: mapConfig.title,
                subtext: mapConfig.subtitle,
                textStyle: {
                    color: mapConfig.titleColor,
                    fontSize: mapConfig.titleSize
                },
                top: '10px',
                left: 'center',
            },
            // 添加tooltip配置，实现鼠标悬停提示
            tooltip: {
                trigger: 'item',
                backgroundColor: '#ffffff',
                borderColor: '#e0e0e0',
                borderWidth: 1,
                borderRadius: 8,
                padding: [8, 12],
                boxShadow: '0 4px 12px rgba(0, 0, 0, 0.15)',
                textStyle: {
                    color: '#333333',
                    fontSize: 12,
                    fontWeight: 'normal'
                },
                formatter: function(params) {
                    if (params.seriesType === 'effectScatter') {
                        return countryNames[params.name] || params.name;
                    }
                    return countryNames[params.name] || params.name;
                },
                // 添加动画效果
                animation: true,
                animationDuration: 300,
                animationEasing: 'cubicOut'
            },
            // 添加全局动画配置
            animation: true,
            animationDuration: 1000,
            animationEasing: 'cubicOut',
            geo: {
                map: 'world', // 与引用进来的地图js名字一致
                roam: false, // 禁止缩放平移
                itemStyle: { // 每个区域的样式
                    normal: {
                        areaColor: '#e8e8e8', // 将非目标区域调暗
                        borderColor: '#d0d0d0',
                        borderWidth: 1
                    },
                    emphasis: {
                        areaColor: '#c8c8c8', // 鼠标悬停时的颜色
                        borderColor: '#a0a0a0',
                        borderWidth: 2
                    }
                },
                regions: [
                    { // 中国区域
                        name: 'China',
                        selected: false,
                        itemStyle: {
                            normal: {
                                areaColor: mapConfig.chinaColor // 中国颜色
                            },
                            emphasis: {
                                areaColor: mapConfig.chinaColor
                            }
                        }
                    },
                    // 目标国家区域高亮显示
                    { name: 'Netherlands', itemStyle: { normal: { areaColor: mapConfig.targetColor }, emphasis: { areaColor: mapConfig.targetColor } } },
                    { name: 'Belgium', itemStyle: { normal: { areaColor: mapConfig.targetColor }, emphasis: { areaColor: mapConfig.targetColor } } },
                    { name: 'Czech Republic', itemStyle: { normal: { areaColor: mapConfig.targetColor }, emphasis: { areaColor: mapConfig.targetColor } } },
                    { name: 'Iraq', itemStyle: { normal: { areaColor: mapConfig.targetColor }, emphasis: { areaColor: mapConfig.targetColor } } },
                    { name: 'Spain', itemStyle: { normal: { areaColor: mapConfig.targetColor }, emphasis: { areaColor: mapConfig.targetColor } } },
                    { name: 'Poland', itemStyle: { normal: { areaColor: mapConfig.targetColor }, emphasis: { areaColor: mapConfig.targetColor } } },
                    { name: 'France', itemStyle: { normal: { areaColor: mapConfig.targetColor }, emphasis: { areaColor: mapConfig.targetColor } } },
                    { name: 'Romania', itemStyle: { normal: { areaColor: mapConfig.targetColor }, emphasis: { areaColor: mapConfig.targetColor } } },
                    { name: 'India', itemStyle: { normal: { areaColor: mapConfig.targetColor }, emphasis: { areaColor: mapConfig.targetColor } } },
                    { name: 'Vietnam', itemStyle: { normal: { areaColor: mapConfig.targetColor }, emphasis: { areaColor: mapConfig.targetColor } } },
                    { name: 'Indonesia', itemStyle: { normal: { areaColor: mapConfig.targetColor }, emphasis: { areaColor: mapConfig.targetColor } } },
                    { name: 'Thailand', itemStyle: { normal: { areaColor: mapConfig.targetColor }, emphasis: { areaColor: mapConfig.targetColor } } },
                    { name: 'Germany', itemStyle: { normal: { areaColor: mapConfig.targetColor }, emphasis: { areaColor: mapConfig.targetColor } } },
                    { name: 'Italy', itemStyle: { normal: { areaColor: mapConfig.targetColor }, emphasis: { areaColor: mapConfig.targetColor } } },
                    { name: 'United Arab Emirates', itemStyle: { normal: { areaColor: mapConfig.targetColor }, emphasis: { areaColor: mapConfig.targetColor } } }
                ]
            },
            series: series,
            textStyle: {
                fontSize: 12
            }
        };
        
        // 设置地图配置
        chart.setOption(mapOption);
        
        // 响应式处理
        window.addEventListener('resize', function() {
            chart.resize();
        });
    }
    
    // 初始化地图
    initBlackMap();
    
        });
    }
    
    // 开始检查和初始化
    initMapWhenReady();
})();
</script>