<template>
    <div>
        <div style="text-align: center;">
            <a style="font-size: 24px;font-weight:bolder;">{{ state.title }}</a>
        </div>
    </div>
    <div style="width: 100%;text-align: right;line-height: 80px;">
        <a-button @click="initDataSource" type="primary">
            重置表格
        </a-button>
        </div>
    <div style="display:flex">
        <div id="barChartId" style="flex:1;width:600px;height:900px;border: 1px solid #333;">
            <div style="width: 100%;font-weight: 600;text-align: center;">{{ state.clickCity }}</div>
            <div  id="barChartId" style="width:600px;height:600px;margin: 0 auto;">

            </div>
        </div>
        <div style="width: 700px;height:900px;border: 1px solid #333;">
            <a-table :scroll="{ x: 600, y: 750 }" :columns="state.columns" :data-source="state.dataSource"
                :loading="state.loading" :pagination="state.pagination" bordered style="border-bottom:1px solid #f0f0f0;">
                <template #bodyCell="{ column, record }">
                    <template v-if="column.key === 'url'">
                        <a :href="record.url" target="_blank">
                            {{ record.url }}
                        </a>
                    </template>
                    <template v-else-if="column.key === 'score'">
                        <span>
                            <a-tag :color="record.score < 60 ? 'volcano' : record.score > 80 ? 'geekblue' : 'green'">
                                {{ record.score }}
                            </a-tag>
                        </span>
                    </template>
                    <template v-else-if="column.key === 'option'">
                        <a-tooltip placement="topLeft" :title="record.editUrl">
                            <a :href="record.editUrl" target="_blank">
                                编辑文章
                            </a>
                        </a-tooltip>
                    </template>
                </template>
            </a-table>
        </div>

    </div>
</template>
<script setup>
import chinaJson from './chinaGeo.js';
import gameJson from './gameJson.js';
import { tableGameColumns } from './const.js'
import * as echarts from 'echarts';
import { defineProps, reactive, watch, nextTick, onUnmounted, onMounted } from 'vue';
const props = defineProps({
    tableData: []
})

const state = reactive({
    title: 'python 爬虫赛道 参赛选手所在城市',
    clickCity:'全国',
    linesCoord: [],
    focusCity: '广东省',
    locationGis: [],
    centerLoction: [],
    aimPointData: [],
    airData: [],
    exportLoading: false,
    columns: tableGameColumns,
    dataSource: [],
    echartInstance: undefined,
    pagination: {
        total: 0,
        current: 1,
        pageSize: 50,
        pageSizeOptions: ['50', '100', '200'],
        showTotal: (total, range) => {
            return range[0] + '-' + range[1] + ' 共' + total + '个选手';
        },
        onShowSizeChange: changePageSize, // 改变每页数量时更新显示
        onChange: changePage,//点击页码事件
    }
})
function initDataSource() {
    state.clickCity='全国'
    state.dataSource = []
    state.total = 0
    Object.keys(gameJson).forEach(uid => {
        state.dataSource.push({
            uid: gameJson[uid].uid,
            name: gameJson[uid].name,
            ip: gameJson[uid].ip.split('：')[1]
        })
        state.total += 1
    })
    state.pagination.current=1
}

function filterName(name) {
    state.clickCity=name
    state.dataSource = []
    state.total = 0
    Object.keys(gameJson).forEach(uid => {
        const locName=gameJson[uid].ip.split('：')[1]
        if(name.includes(locName)){
            
            state.dataSource.push({
            uid: gameJson[uid].uid,
            name: gameJson[uid].name,
            ip: locName
        })
        state.total += 1
        }
    })
    state.pagination.current=1
}


function initMap() {
    echarts.registerMap('chinaJson', chinaJson)
    let itemData = chinaJson.features
    let length = itemData.length
    state.aimPointData = []
    state.linesCoord= []
    for (let loc = 0; loc < length; ++loc) {
        let name = itemData[loc].properties.name
        state.aimPointData.push({
            value: name
        })
        let center = itemData[loc].properties.center
        // 中心位置
        if (name.includes(state.focusCity)) {
            state.centerLoction = center
        }
    }
    for (let loc = 0; loc < length; ++loc) {
        let name = itemData[loc].properties.name
        let number = 0
        let center = itemData[loc].properties.center
        Object.keys(gameJson).forEach(uid => {
            const locName=gameJson[uid].ip.split('：')[1]
            if (name.includes(locName)||locName.includes(name)) {
                number += 1
            }
        })
        state.locationGis.push({
            value: center
        })
        // eslint-disable-next-line eqeqeq
        if (!name.includes(state.focusCity)) {
            if(center&&state.centerLoction){
                state.linesCoord.push([center, state.centerLoction])
            }
            
        }
        // eslint-disable-next-line eqeqeq
        if (name && name !== state.focusCity) {
            let temp = {
                name: `${name}`,
                value: Number(number)
            }
            state.airData.push(temp)
        }
        continue
    }

    setTimeout(()=>{
        renderEchartBar()
    },500)
}

// storage
function changePage(page, pageSize) {
    state.pagination.current = page
    state.pagination.pageSize = pageSize
}
function changePageSize(current, pageSize) {
    state.pagination.current = current
    state.pagination.pageSize = pageSize
}
// watch(() => props.tableData,
//     (val) => {
//         state.dataSource = val
//         nextTick(() => {
//             renderEchartBar()
//         })
//     }, {
//     deep: true,
//     immediate: true
// })
function renderEchartBar() {
    // 基于准备好的dom，初始化echarts实例
    const domInstance = document.getElementById('barChartId')
    if (domInstance) {
        domInstance.removeAttribute('_echarts_instance_')
    }
    else {
        return
    }
    const myChart = echarts.init(domInstance);
    const option = {
        title: {
            text: '中国地图',
            subtext: 'chinaJson'
        },
        geo: {
            // 经纬度中心
            // center: state.centerLoction,
            type: 'map',
            map: 'chinaJson', // 这里的值要和上面registerMap的第一个参数一致
            roam: false, // 拖拽
            nameProperty: 'name',
            // 悬浮标签
            label: {
                type: 'map',
                map: 'chinaJson', // 这里的值要和上面registerMap的第一个参数一致
                // roam: false, // 拖拽
                // nameProperty: 'name',
                show: true,
                color: '#333',
                formatter:function(params){
                    return params.name
                },
                // backgroundColor: '#546de5',
                align: 'center',
                fontSize: 10,
                width: (function () {
                    // let n = parseInt(Math.random() * 10)
                    return 110
                })(),
                height: 50,
                shadowColor: 'rgba(0,0,0,.7)',
                borderRadius: 10
            },
            zoom: 1.2
        },
        series: [
            // 坐标点的热力数据
            {
                data: state.airData,
                geoIndex: 0, // 将热力的数据和第0个geo配置关联在一起
                type: 'map'
            },
            {
                type: 'effectScatter',
                // 渲染显示
                zlevel: 3,
                showEffectOn: 'render',
                data: state.locationGis, // 配置散点的坐标数据
                coordinateSystem: 'geo', // 指明散点使用的坐标系统
                rippleEffect: {
                    // 缩放
                    scale: 4,
                    // 涟漪的颜色
                    color: '#cf6a87',
                    // 波纹数量
                    number: 2,
                    // 扩散方式 stroke(线条) fill（区域覆盖）
                    brushType: 'fill'
                },
                // 形状
                symbol: 'circle'
            },
            // 飞线层
            {
                // name: '贵阳市飞线',
                type: 'lines',
                coordinateSystem: 'geo',
                polyline: true,
                zlevel: 3,
                effect: {
                    show: true,
                    period: 5,
                    trailLength: 0, // 拖尾
                    symbol: 'arrow', // 箭头
                    color: 'red', // 样式颜色
                    symbolSize: 5
                },
                lineStyle: {
                    color: '#000',
                    width: 2,
                    type: 'solid',
                    dashOffset: 1
                },
                // 飞线层数据
                data: state.linesCoord
            }
        ],
        visualMap: {
            min: 0,
            max: 100,
            inRange: {
                color: ['white', '#0984e3'] // 控制颜色渐变的范围
            },
            calculable: false // 出现滑块
        }
    }
    // 使用刚指定的配置项和数据显示图表。
    myChart.setOption(option, true);
    // 监听
    state.echartInstance = myChart;
    myChart.on('click', function (params) {
        console.log('params',params)
        filterName(params.name)
    });
    window.onresize = myChart.resize;
}

onUnmounted(() => {
    window.onresize = null
})
onMounted(() => {
    initDataSource()
    initMap()
})
</script>