<template>
    <div class="map">
        <div id="baiduMap" v-if="chooseMenu === 0"></div>
        <div ref="chart" id="map-chart" v-else></div>

        <div class="box" v-if="showBox">
            <div class="title">
                <img :src="chooseInfo.logo" alt="" />
                <span> {{ chooseInfo.orgName }}</span>
            </div>
            <div class="text">{{ chooseInfo.parentOrg }} {{ chooseInfo.orgType }}</div>
            <div class="text">企业介绍:{{ chooseInfo.intro }}</div>
            <div class="text">地 址:{{ chooseInfo.addressDetail }}</div>
        </div>
    </div>
</template>

<script>
import * as echarts from 'echarts';
import JiangXi from '../JiangXi.json';
import 'echarts-gl';
import menuOptions from '../mixins/menuOptions';
import { initMap, purpleStyle } from '../plugins/common';
// eslint-disable-next-line no-redeclare
/* global BMapGL */

/* global mapv */

/* global mapvgl */

/* global initMap */

/* global whiteStyle */
export default {
    name: 'MapChart',
    mixins: [menuOptions],
    props: {
        valueInfo: {
            type: [Object, Array],
            default: () => {
                return {};
            },
        },
    },
    data() {
        return {
            myChart: null,
            active: '南昌市',
            preActive: '南昌市',
            flag: true,
            isOn: false,
            timeData: null,
            desc: 1000,
            sndStat: {},
            showLables: [],
            map: null,
            chooseInfo: {
                address: '江西上饶',
                addressDetail: '江西省上饶市信州区茶圣东路文创中心2号楼3楼',
                contactName: '林必利 ',
                id: 11836,
                intro:
                    '上饶市饶东现代产业发展有限公司成立于2017-02-21，法定代表人为林必利，注册资本为100000万元人民币，统一社会信用代码为91361100MA35Q7G85K，企业地址位于江西省上饶市信州区茶圣东路文创中心2号楼3楼，所属行业为商务服务业，经营范围包含：现代农业服务；节能环保产业服务；信息技术产业服务；智慧城市开发建设和运营管理。',
                location: '116.309983,39.983965\r',
                logo: 'https://image.qcc.com/auto/1658389f6237d1dc73c3281f589d0753.jpg',
                orgName: '上饶市饶东现代产业发展有限公司',
                orgType: '小微企业',
                parentOrg: '商务服务业',
                publicCompany: false,
                status: 'PASS',
                userId: 11835,
            },
            showBox: false,
        };
    },
    computed: {
        labels() {
            return this.valueInfo.labels || [];
        },
        datas() {
            return this.valueInfo.data || [];
        },
    },
    watch: {
        active() {
            this.changeChoose();
        },
    },
    mounted() {
        window.addEventListener('resize', this.resize);
    },
    beforeUpdate() {
        if (this.timeData) {
            clearTimeout(this.timeData);
        }
    },
    beforeDestroy() {
        if (this.timeData) {
            clearTimeout(this.timeData);
        }
    },
    methods: {
        resize() {
            this.myChart.resize();
        },
        clearDom() {
            if (this.timeData) {
                clearTimeout(this.timeData);
            }
            this.showBox = false;

            if (this.chooseMenu == 0) {
                if (this.map) {
                    this.map.destroy();
                    this.map = null;
                }
            } else {
                if (!this.myChart) {
                    let chartDom = document.getElementById('map-chart');
                    if (chartDom.style) {
                        chartDom.style.backgroundImage = '';
                    }
                    this.myChart = echarts.init(chartDom);
                } else if (this.myChart) {
                    let chartDom = document.getElementById('map-chart');
                    if (chartDom.style) {
                        chartDom.style.backgroundImage = '';
                    }

                    this.myChart.dispose();
                }
            }
        },
        init() {
            this.clearDom();
            this.$nextTick(() => {
                console.log(this.chooseMenu);
                if (this.chooseMenu === 0) {
                    this.initBaidu();
                } else if (this.chooseMenu === 2 || this.chooseMenu === 4 || this.chooseMenu === 3) {
                    this.initScatter();
                } else if (this.chooseMenu === 5 || this.chooseMenu === 6) {
                    this.showLables =
                        this.chooseMenu === 6
                            ? ['初级示范区', '高级示范区', '重点示范区']
                            : ['高新基地', '高级高新基地', '重点高新基地'];
                    this.initScatter('more');
                } else if (this.chooseMenu === 1) {
                    this.initScatter();
                }
            });
        },
        initBaidu() {
            var map = initMap(
                {
                    tilt: 50,
                    heading: 0,
                    center: [115.853087, 28.689709],
                    zoom: 9,
                    style: purpleStyle,
                    skyColors: [
                        // 地面颜色
                        'rgba(226, 237, 248, 0)',
                        // 天空颜色
                        'rgba(186, 211, 252, 1)',
                    ],
                },
                'baiduMap'
            );

            map.setMinZoom(8);
            map.setMaxZoom(20);

            map.enableScrollWheelZoom();
            var bd = new BMapGL.Boundary();
            bd.get('江西省', function (rs) {
                var count = rs.boundaries.length; //行政区域的点有多少个
                var pointArray = [];
                for (let i = 0; i < count; i++) {
                    let path = [];
                    let str = rs.boundaries[i].replace(' ', '');
                    let points = str.split(';');
                    for (let j = 0; j < points.length; j++) {
                        let lng = points[j].split(',')[0];
                        let lat = points[j].split(',')[1];
                        path.push(new BMapGL.Point(lng, lat));
                    }
                    let prism = new BMapGL.Prism(path, 5000, {
                        topFillColor: '#5679ea',
                        topFillOpacity: 0.2,
                        sideFillColor: '#5679ea',
                        sideFillOpacity: 0.5,
                    });
                    map.addOverlay(prism);
                }
            });

            this.map = map;
            this.initCity();
        },
        initCity() {
            var data = [];
            var data2 = [];

            var citys = ['南昌', '景德镇', '萍乡', '九江', '新余', '鹰潭', '赣州', '吉安', '宜春', '抚州', '上饶'];
            var randomCount = citys.length;
            var values = [...this.valueInfo].filter((item) => {
                let pos = item.location.split(',');
                return pos.length == 2;
            });
            let nums = {};
            values.forEach((item) => {
                console.log(item);
                let address = item.address.replace(/江西/, '');
                if (citys.includes(address)) {
                    let _num = nums[address] || 0;
                    _num++;
                    nums[address] = _num;
                }
            });

            console.log(nums);

            // 构造数据
            while (randomCount--) {
                var cityName = citys[randomCount];
                var cityCenter = mapv.utilCityCenter.getCenterByCityName(cityName);
                data.push({
                    geometry: {
                        type: 'Point',
                        coordinates: [cityCenter.lng, cityCenter.lat],
                    },
                    properties: {
                        text: cityName + '\n' + (nums[cityName] || 0),
                        // textColor: '#fff',
                        // borderColor: ['#0f0', '#f00', '#00f'][randomCount % 3],
                        // backgroundColor: ['#0f0', '#f00', '#00f'][randomCount % 3],
                    },
                });
            }

            data2 = values.map((item) => {
                let pos = item.location.split(',');
                return {
                    geometry: {
                        type: 'Point',
                        coordinates: [pos[0], pos[1]],
                    },
                    properties: {
                        text: item.orgName,
                        // textColor: '#fff',
                        // borderColor: ['#0f0', '#f00', '#00f'][randomCount % 3],
                        // backgroundColor: ['#0f0', '#f00', '#00f'][randomCount % 3],
                    },
                };
            });

            var view = new mapvgl.View({
                map: this.map,
            });

            let _this = this;

            var layer = new mapvgl.LabelLayer({
                textAlign: 'center',
                textColor: '#fc0',
                borderColor: '#666',
                backgroundColor: '#666',
                padding: [2, 5],
                borderRadius: 5,
                fontSize: 12,
                lineHeight: 16,
                collides: true, // 是否开启碰撞检测, 数量较多时建议打开
                enablePicked: true,
                onClick: (e) => {
                    // 点击事件
                    let _zoom = 11;
                    let zoom = this.map.getZoom();
                    console.log(this.map.getZoom());
                    if (zoom > 10) {
                        console.log(values[e.dataIndex]);
                        _this.chooseInfo = values[e.dataIndex];
                        _zoom = 18;
                        setTimeout(() => {
                            _this.showBox = true;
                        }, 500);
                    }
                    if (e.dataItem) {
                        let location = e.dataItem.geometry.coordinates;
                        this.map.centerAndZoom(new BMapGL.Point(location[0], location[1]), _zoom);
                    }
                },
            });
            view.addLayer(layer);
            layer.setData(data);
            this.map.addEventListener('zoomstart', (e) => {
                this.showBox = false;
            });
            this.map.addEventListener('zoomend', (e) => {
                if (e.currentTarget.zoomLevel > 9) {
                    layer.setData(data2);
                } else {
                    layer.setData(data);
                }
            });
        },
        init3D() {
            var chartDom = document.getElementById('map-chart');
            this.myChart = echarts.init(chartDom);
            this.myChart.setOption({
                color: '#0A2B6A',
                geo3D: {
                    map: 'JangXi',
                    shading: 'lambert',
                    instancing: true,
                    label: {
                        show: false,
                        formatter: (params) => {
                            this.active = params.name;
                            return '';
                        },
                    },
                    light: {
                        main: {
                            intensity: 1,
                        },
                        ambient: {
                            intensity: 0.5,
                        },
                    },
                    regionHeight: 5,
                    boxHeight: 40,
                    viewControl: {
                        distance: 200,
                        minDistance: 150,
                        alpha: 40,
                        beta: 30,
                        rotateSensitivity: [1, 0],
                    },
                },
                zAxis3D: {
                    type: 'value',
                    min: 0,
                    max: 9000000,
                },
                series: [
                    {
                        id: 'value',
                        type: 'bar3D',
                        name: '江西省数据',
                        coordinateSystem: 'geo3D',
                        shading: 'lambert',
                        data: [],
                        bevelSize: 0.3,
                        barSize: 5,
                        minHeight: 0,
                        bevelSmoothness: 2,
                        zlevel: 1,
                        silent: true,
                        light: {
                            main: {
                                intensity: 1.2,
                            },
                        },
                    },
                    {
                        id: 'name',
                        type: 'bar3D',
                        name: '江西省名称',
                        coordinateSystem: 'geo3D',
                        shading: 'lambert',
                        data: JiangXi.features.map((item) => {
                            let value = this.getCenter(item, true);

                            if (this.active === item) {
                                value.push(15);
                            } else {
                                value.push(0);
                            }
                            return {
                                name: item,
                                value: value,
                                itemStyle: {
                                    color: this.active === item ? '#FA8816' : '#0A2B6A',
                                },
                            };
                        }),
                        barSize: 1,
                        minHeight: 0,
                        bevelSmoothness: 0,
                        label: {
                            show: true,
                            formatter: (params) => {
                                return params.name;
                            },
                            distance: 0,
                            textStyle: {
                                color: '#fff',
                            },
                        },
                        silent: true,
                        zlevel: 2,
                    },
                ],
            });
            this.myChart.getZr().on('mouseout', () => {
                this.isOn = true;
            });
            this.myChart.getZr().on('globalout', () => {
                this.isOn = false;
                this.animationMove();
            });
            this.changeChoose();
            this.animationMove();
        },
        initScatter(type = 'one') {
            var chartDom = document.getElementById('map-chart');
            this.myChart = echarts.init(chartDom, 'jmrh');
            this.myChart.setOption({
                geo: {
                    map: 'JangXi',
                    label: {
                        show: true,
                        color: '#fff',
                    },
                    itemStyle: {
                        color: '#0C4189',
                        borderColor: '#8CD9FD',
                    },
                    silent: true,
                },
                tooltip: {
                    trigger: 'item',
                },
                visualMap: {
                    show: true,
                    bottom: 30,
                    left: 'center',
                    orient: 'horizontal',
                    min: 0,
                    max: type === 'one' ? this.maxList([...this.datas]) : 3,
                    seriesIndex: 0,
                    calculable: true,
                    inRange: {
                        color: ['#FDA033', '#FD6C33', '#FD4C33'],
                    },
                },
            });

            if (type == 'one') {
                this.myChart.setOption({
                    series: [
                        {
                            type: 'effectScatter',
                            coordinateSystem: 'geo',
                            data: [...this.labels].map((item, index) => {
                                let list = [this.getCenter(item), [...this.datas][index]];
                                return {
                                    name: item,
                                    value: list.flat(),
                                };
                            }),
                            symbolSize: function (val) {
                                let size = val[2];
                                if (size > 1000000) {
                                    size = Math.floor(size / 100000);
                                }
                                if (size > 100000) {
                                    size = Math.floor(size / 10000);
                                }
                                if (size > 10000) {
                                    size = Math.floor(size / 1000);
                                }
                                if (size > 1000) {
                                    size = Math.floor(size / 100);
                                }
                                if (size > 100) {
                                    size = Math.floor(size / 10);
                                }
                                return size;
                            },
                            encode: {
                                value: 2,
                            },
                            showEffectOn: 'render',
                            rippleEffect: {
                                brushType: 'stroke',
                            },
                            hoverAnimation: true,
                            label: {
                                formatter: (params) => {
                                    return params.name + '\r\n' + params.value[2] + '万元';
                                },
                                show: true,
                                color: '#fff',
                                fontWeight: 'bold',
                            },
                            itemStyle: {
                                shadowBlur: 10,
                                shadowColor: '#333',
                            },
                            zlevel: 1,
                        },
                    ],
                });
            } else {
                let points = [...this.labels]
                    .map((item, index) => {
                        return this.getRadomlngLat(item, 3, ([...this.datas][index] % 3) + 1);
                    })
                    .flat();

                this.myChart.setOption({
                    visualMap: {
                        show: false,
                    },
                    series: [
                        {
                            type: 'effectScatter',
                            coordinateSystem: 'geo',
                            data: points,
                            symbolSize: function (val) {
                                return 20;
                            },
                            showEffectOn: 'render',
                            rippleEffect: {
                                brushType: 'stroke',
                            },
                            hoverAnimation: true,
                            label: {
                                formatter: (params) => {
                                    return [...this.showLables][params.value[2] - 1];
                                },
                                show: false,
                                color: '#fff',
                                fontWeight: 'bold',
                                position: 'right',
                            },
                            emphasis: {
                                label: {
                                    show: true,
                                },
                            },
                            itemStyle: {
                                shadowBlur: 10,
                                shadowColor: '#333',
                            },
                            zlevel: 1,
                        },
                    ],
                });
            }
        },
        initHeatmap() {
            var chartDom = document.getElementById('map-chart');
            this.myChart = echarts.init(chartDom, 'jmrh');
            this.myChart.setOption({
                geo: {
                    map: 'JangXi',
                    label: {
                        show: true,
                        color: '#fff',
                    },
                    itemStyle: {
                        color: '#0C4189',
                        borderColor: '#8CD9FD',
                    },
                    silent: true,
                },
                visualMap: {
                    show: true,
                    bottom: 30,
                    left: 'center',
                    orient: 'horizontal',
                    min: 0,
                    max: 5,
                    seriesIndex: 0,
                    calculable: true,
                    inRange: {
                        color: ['blue', 'blue', 'green', 'yellow', 'red'],
                    },
                },
            });

            this.$nextTick(() => {
                let points = [...this.labels]
                    .map((item) => {
                        return this.getRadomlngLat(item);
                    })
                    .flat();
                this.myChart.setOption({
                    series: [
                        {
                            type: 'heatmap',
                            coordinateSystem: 'geo',
                            geoIndexnumber: 0,
                            data: points,
                        },
                    ],
                });
            });
        },
        maxList(list, type = 'max') {
            list = list.sort((a, b) => {
                return b - a;
            });

            return type === 'max' ? list[0] : list[list.length] - 1;
        },
        changeChoose() {
            const res = { ...this.valueInfo };
            this.myChart.setOption({
                geo3D: {
                    regions: res.labels.map((item) => {
                        return {
                            name: item,
                            height: this.active === item ? 15 : 5,
                            itemStyle:
                                this.active === item
                                    ? {
                                          color: '#FA8816',
                                          borderWidth: 1,
                                          borderColor: '#FA8816',
                                      }
                                    : {
                                          color: '#0A2B6A',
                                          borderWidth: 1,
                                          borderColor: '#8CD9FD',
                                      },
                            emphasis: {
                                itemStyle:
                                    this.active === item
                                        ? {
                                              color: '#FA8816',
                                          }
                                        : {
                                              color: '#0A2B6A',
                                          },
                            },
                        };
                    }),
                },
                series: [
                    {
                        id: 'value',
                        name: '江西省数据',
                        data: res.labels.map((item, index) => {
                            let value = 0;
                            if (this.active === item) {
                                value = res.data[index] + this.desc;
                            } else {
                                value = res.data[index];
                            }

                            return {
                                name: item,
                                value: [...this.getCenter(item), value],
                                itemStyle: {
                                    color: this.active === item ? '#ffc38c' : '#5AC1FF',
                                    opacity: 0.8,
                                },
                                label: {
                                    show: true,
                                    formatter: (params) => {
                                        if (params.name === this.active) {
                                            return params.value[2] - this.desc;
                                        } else {
                                            return params.value[2];
                                        }
                                    },
                                    distance: 2,
                                    textStyle: {
                                        color: this.active === item ? '#FA8816' : '#fff',
                                        fontSize: this.active === item ? 18 : 12,
                                        opacity: 1,
                                        fontWeight: 'bold',
                                    },
                                },
                            };
                        }),
                    },
                    {
                        id: 'name',
                        name: '江西省名称',
                        data: res.labels.map((item) => {
                            let value = this.getCenter(item, true);
                            value.push(0);
                            return {
                                name: item,
                                value: value,
                                itemStyle: {
                                    color: this.active === item ? '#FA8816' : '#0A2B6A',
                                },
                                label: {
                                    distance: this.active === item ? 10 : 2,
                                    textStyle: {
                                        fontSize: this.active === item ? 18 : 12,
                                    },
                                },
                            };
                        }),
                    },
                ],
            });
        },
        getRadomlngLat(name = '南昌市', val = 1, randomCount) {
            if (!randomCount) {
                let index = [...this.labels].findIndex((item) => {
                    return item === name;
                });

                if (index || index === 0) {
                    randomCount = this.datas[index];
                }
            }

            if (val !== 1) {
                val = (Math.floor(Math.random() * 10) % val) + 1;
            }

            var data = [];

            var geo = this.myChart.getModel().getComponent('geo').coordinateSystem;
            var region = geo.getRegion(name);
            var rect = region.getBoundingRect();
            for (var i = 0; i < randomCount; i++) {
                var coord = [Infinity, Infinity, val];
                while (!region.contain(coord)) {
                    coord[0] = rect.x + Math.random() * rect.width;
                    coord[1] = rect.y + Math.random() * rect.height;
                }
                // const itemName = 's' + i;
                // geoCoordMap[itemName] = coord;

                data.push(coord);
            }
            return data;
        },
        getCenter(name, isLable = false) {
            let info = JiangXi.features.find((item) => {
                return name === item.properties.name;
            });
            let center = info ? info.properties.centroid : [0, 0];
            if (isLable) {
                center = [center[0] + 0.200151, center[1] - 0.276493];
            }
            return center;
        },
        animationMove() {
            if (this.timeData) {
                clearTimeout(this.timeData);
            }

            this.timeData = setTimeout(() => {
                if (!this.flag || this.isOn) {
                    return;
                } else {
                    const citys = JiangXi.features;
                    let index =
                        citys.findIndex((item) => {
                            return this.active === item.properties.name;
                        }) || 0;
                    this.active = citys[(index + 1) % citys.length].properties.name;
                    this.animationMove();
                }
            }, 3000);
        },
    },
};
</script>

<style lang="less" scoped>
#map-chart,
#baiduMap {
    width: 100%;
    height: 100%;
}
.map {
    width: 100%;
    height: 100%;
}
@prim: #3cbef2;
.box {
    padding: 15px;
    width: 500px;
    box-sizing: border-box;
    position: fixed;
    top: 200px;
    z-index: 999;
    background-color: rgba(0, 0, 0, 0.5);
    left: 50%;
    transform: translateX(-50%);
    color: @prim;
    border-radius: 8px;
    .title {
        .flex();
        img {
            width: 40px;
            height: 40px;
            border-radius: 100px;
        }
        span {
            font-size: 16px;
            font-weight: bold;
            margin-left: 6px;
        }
    }

    .text {
        font-size: 14px;
        margin-top: 12px;
    }
}
</style>
