<template>
    <!--热力图-->
    <div style="width: 100%; height: 100%;">
        <div :id="chartId" class="main"></div>
    </div>
</template>

<script>
export default {
    name: "hotMap_chart"
}
</script>

<script setup>
import * as echarts from 'echarts';
import { computed, nextTick, onMounted, onUnmounted, ref, watch } from 'vue';
import worldJson from '@/assets/json/world.json';
import chineseWorldName from '@/assets/json/chineseWorldName.json';
import useAppStore from '@/store/module/app'

const appStore = useAppStore && useAppStore()
const maxValue = ref(0)
let myChart = null;
const props = defineProps({
    title: {
        type: String,
        default: '默认未知'
    },
    data: {
        type: Array,
        default: () => []
    },
    mapCenter: {
        type: Array,
        default: () => []
    },
    yName: {//y轴名称
        type: Array,
        default: () => []
    }
})

watch(() => props.data, (newVal) => {
    // // updateChart();
    setTimeout(() => {
        initChart();
    }, 0)

}, { deep: true, immediate: true })

const obj = {
    '中国': [104, 35],
    '巴西': [-51.9253, -14.2350],
    '马来西亚': [109.5, 3.5]
}

watch(() => appStore.currentHotMapCountry, (newVal, oldVal) => {
    initChart()
})

watch(() => maxValue.value, (newVal) => {
    if (myChart && newVal > 0) {
        myChart.setOption({
            visualMap: {
                text: [newVal, 0],
                range: [0, newVal],
                min: 0,
                max: newVal,
            }
        }, { notMerge: false, lazyUpdate: false })
    }
})

const data = computed(() => {
    let result = []
    // console.log('y--props.data', props.data)
    props.data.forEach(el => {
        let y = el.y
        if (Object.prototype.toString.call(y) == '[object Object]' && y.hasOwnProperty('dropRate')) {
            y = y.dropRate
        }
        // console.log('y', y)
        y.forEach(y => {
            const { value, GridCode } = y
            result.push({
                code: GridCode,
                count: value,
            })
            // console.log('item', item)
        })
    })
    result = result.sort((pre, next) => pre.count - next.count)//排列顺序
    maxValue.value = result[result.length - 1]?.count || 0//获取最大值
    result = mergeData(result, appStore.gridInfoList)
    return result

})

const mergeData = (data, baseData = []) => {
    if (!baseData) return []
    // if(data)
    let _baseData = baseData?.map(item => ({
        name: item.gridName,
        code: item.gridCode,
        value: [
            item.vertex1Lon,
            item.vertex1Lat,
            item.vertex2Lon,
            item.vertex2Lat,
            item.vertex3Lon,
            item.vertex3Lat,
            item.vertex4Lon,
            item.vertex4Lat,
            item.vertex5Lon,
            item.vertex5Lat,
            item.vertex6Lon,
            item.vertex6Lat,
            null
        ],
    }))

    _baseData.forEach(item => {
        data.forEach(el => {
            if (item.code == el.code) {
                item.value[item.value.length - 1] = el.count
            }

        })
    })
    return _baseData
}

// 生成唯一的图表ID
const chartId = ref('hexagonHeatMap_' + Math.random().toString(36).substr(2, 9));


// 初始化图表
function initChart() {
    const chartDom = document.getElementById(chartId.value);
    chartDom.style.width = '100%';
    chartDom.style.height = '100%';

    echarts.registerMap("world", worldJson);
    if (!myChart) {
        myChart = echarts.init(chartDom);
    };
    const option = {
        backgroundColor: '#000',

        // legend: {
        //     show: true,
        //     data: ['默认'],
        //     textStyle: {
        //         color: '#fff',
        //         fontSize: 12
        //     },
        //     top: 0,
        //     left: '-5px',
        //     backgroundColor: 'transparent',
        //     borderColor: 'transparent',
        //     padding: [5, 10],
        //     // 添加图标样式控制
        //     icon: 'rect',  // 使用矩形图标
        //     itemWidth: 15, // 图例宽度
        //     itemHeight: 5, // 图例高度，设为较小值形成线条效果

        // },
        tooltip: {
            trigger: 'item',
            formatter: function (params) {
                const val = params.value
                const color = params.color
                // console.log('tooltip', val)
                if (val[12] == null) {
                    return `<span style="display:inline-block;margin-right:4px;border-radius:10px;width:10px;height:10px;background-color:${color};"></span> ${params.name}`
                } else {
                    return `<span style="display:inline-block;margin-right:4px;border-radius:10px;width:10px;height:10px;background-color:${color};"></span> ${params.name}  ${val[12]}`
                }
            }
        },

        title: {
            text: props.title,
            // left: 'center',
            // top: 10,
            left: 6,
            textStyle: {
                color: '#fff',
                fontSize: 12,
                fontWeight: 'bold'
            }
        },
        geo: {
            map: "world",
            roam: true,
            center: obj[appStore.currentHotMapCountry] || [104, 35], // 中国中心
            // center: [-51.9253, -14.2350], // 巴西
            zoom: 10, // 放大倍数
            // aspectScale: Math.cos((chRoughLatitude * Math.PI) / 180),
            // nameProperty: 'name_en', // If using en name.
            label: {
                show: true,
                textBorderColor: "#f7f7f7",//国家名称文字显示
                textBorderWidth: 1,
            },
            itemStyle: {
                areaColor: "#282a31", // 地图底色
                borderColor: "#575a61", // 国界线
                borderWidth: 1,
            },
            emphasis: {
                itemStyle: {
                    borderColor: '#0d99ff',//鼠标hover时边框颜色
                    areaColor: "#282a31", // 鼠标hover地图颜色
                    borderWidth: 2
                },
            },
            nameMap: chineseWorldName
        },
        visualMap: {
            text: (() => {
                // console.log('maxValue', maxValue.value)
                return [maxValue.value, 0]
            })(),
            textStyle: {
                color: "#fff"
            },
            // dimension: 12,
            // itemWidth: 12,
            // itemHeight: 68,
            left: "center", // 水平居中
            bottom: 1, // 距离底部 20px
            range: [0, maxValue.value],
            min: 0,
            max: maxValue.value,
            orient: "horizontal",
            inRange: {
                color: [
                    "#6ffcba",
                    "#409eff",
                    "#2e7dff",
                    "#97D5E4",

                    // "#f46d43",
                    // "#BF1C05",
                ],
            },
            // type: 'piecewise',
            // calculable: true
        },

        series: [
            {
                type: "custom",
                // name:'moren',
                coordinateSystem: "geo",
                emphasis: {
                    focus: "self",
                },
                renderItem(params, api) {
                    // console.log(api.visual("color"), '对比', api.value(0), 'ii');

                    // debugger
                    if (api.value(0) == null) {
                        return null
                    }
                    const point1 = api.coord([api.value(0), api.value(1)]);
                    const point2 = api.coord([api.value(2), api.value(3)]);
                    const point3 = api.coord([api.value(4), api.value(5)]);
                    const point4 = api.coord([api.value(6), api.value(7)]);
                    const point5 = api.coord([api.value(8), api.value(9)]);
                    const point6 = api.coord([api.value(10), api.value(11)]);

                    const hex = [point1, point2, point3, point4, point5, point6];

                    const val = api.value(12)
                    // console.log('val', val)

                    if (val == null || isNaN(val)) {
                        return {
                            type: "polygon",
                            shape: {
                                points: hex,
                            },
                            style: {
                                fill: '#282a31',   // 👈 不填充
                                stroke: 'rgba(255,255,255,0.6)',// 👈 描边颜色
                                lineWidth: 1           // 👈 描边宽度

                            },
                        }
                    } else {
                        // console.log('val', val)
                    }

                    return {
                        type: "polygon",
                        shape: {
                            points: hex,
                        },
                        style: {
                            fill: api.visual("color"),
                        },
                    };
                },
                data: data.value,
            }
        ]
    }

    myChart.setOption(option);
    resizeChart();
}


function updateChart() {
    if (!myChart) return;

    myChart.setOption({
        series: [
            {
                type: 'custom',
                data: data.value
            }
        ]
    });
}



// 响应式调整图表大小
function resizeChart() {
    if (myChart) {
        myChart.resize();
    }
}

onMounted(async () => {

    // 确保DOM渲染完成后初始化图表
    // nextTick(() => {
    //     initChart();
    //     window.addEventListener('resize', resizeChart);
    // });
});

onUnmounted(() => {
    if (myChart) {
        window.removeEventListener('resize', resizeChart);
        myChart.dispose();
        myChart = null;
    }
});
</script>

<style scoped>
.main {
    width: 100%;
    height: 100%;
    /* min-height: 400px; */
    /* overflow: hidden; */
}
</style>