import { onMount } from "solid-js";
import { Scene, PointLayer, PolygonLayer, LineLayer, Marker } from '@antv/l7';
import { Mapbox } from '@antv/l7-maps';
// import { GaodeMap } from '@antv/l7-maps';
// import DataSet from '@antv/data-set';

// import json from "../../../assets/file/100000_full.json"

import utils from "../../../utils/index"
import config from "../../../base/config"

import { getGeography, getMapfull } from "../../../api/bigScreen"

import "../../../assets/style/BigScreenHome.css"


function Map(prop) {
    let anchorLayer = undefined,
        textLayer = undefined,
        timeHome = undefined,
        $canvas = undefined,
        scene = undefined,
        source = [],
        index = 0,
        li = [],
        cli = [
            '#87CEFA',
            '#00BFFF',
            '#7FFFAA',
            '#00FF7F',
            '#32CD32',
            '#F0E68C',
            '#FFD700',
            '#FF7F50',
            '#FF6347',
            '#FF0000'
        ];

    // TODO: 高德地图
    /***
     * 高德天气，暂时不用只能在https下可以
     */
    function getWatcher(local) {
        getGeography({
            radius: 1,
            key: config.webToke,
            location: [local.lng, local.lat].join()
        }).then(res => {
            let adcode = res.regeocode.addressComponent.adcode.split("");
            getWeather({
                key: config.webToke,
                // city: adcode[0] + adcode[1] + adcode[2] + adcode[3] + "00"
                city: 610100
            }).then(r => prop.setfun(r))
        })
    }
    function TrendChart() {
        scene = new Scene({
            id: $canvas,
            logoVisible: false,
            // map: new GaodeMap({
            //     style: 'blank',
            //     pitch: 50,
            //     zoom: 3,
            //     maxZoom: 7,
            //     minZoom: 7,
            //     token: config.gaodeToken
            // })
            map: new Mapbox({
                pitch: 40,
                style: 'blank',
                zoom: 5.6,
                rotateEnable: true,

            })
        });


        scene.on('loaded', () => {
            scene.setCenter([108.2, 35])
            // 获取地理/天气信息
            // AMap.convertFrom([prop.Geography.longitude, prop.Geography.latitude], 'gps', function (status, result) {
            //     if (result.info !== 'ok') return
            //     console.log(result)
            //     const local = result.locations[0] || { Q: -190, R: -190, lat: -190, lng: -1906 }
            //     scene.setCenter([local.lng, local.lat])
            //     getWatcher(local)
            // });
            getMapfull().then(data => {
                li = data && data.features && data.features.length ? data.features : [];
                console.log(prop.li)
                for (let i = 0; i < li.length; i++) {
                    const v = li[i].properties || { center: [] };
                    const Data = {
                        name: v.name,
                        lng: v.center[0],
                        lat: v.center[1],
                        size: prop.li.find(item => item.area === v.name).usrcount, // 自定义数据
                    };
                    source.push(Data);
                }
                const layer = new PointLayer()
                    .source(source, {
                        parser: {
                            type: 'json',
                            x: 'lng',
                            y: 'lat'
                        }
                    })
                    .shape('circle')
                    .color('backgoundColor')
                    .size(42);
                // 上层线条
                const lineUp = new LineLayer({ zIndex: 3, blend: "normal" })
                    .source(data)
                    .shape('line')
                    .color('rgb(0,255,255)')
                    .size(0.5)
                    .style({
                        raisingHeight: 150000
                    })
                    .animate({
                        interval: 1, // 间隔
                        duration: 1, // 持续时间，延时
                        trailLength: 3 // 流线长度
                    });
                //  围栏
                const bottomLayer = new LineLayer({ zIndex: 0, blend: "normal" })
                    .source(data)
                    .shape('wall')
                    .color('rgb(0,255,255)')
                    .size(10)
                    .style({
                        raisingHeight: 0,
                        heightfixed: true,
                        opacity: 1,
                        sourceColor: '#0DCCFF',
                    });
                // 高度
                const gd = new PolygonLayer({ zIndex: 1, blend: "normal" })
                    .source(data)
                    .size(150000)
                    .shape('extrude')
                    .color("name", cli)
                    .style({
                        heightfixed: true,
                        pickLight: true,
                        raisingHeight: 10000,
                        opacity: 0.8
                    });

                // 水波
                const waveLayer = new PointLayer({ zIndex: 3, blend: 'normal' })
                    .source(source,
                        {
                            parser: {
                                type: 'json',
                                x: 'lng',
                                y: 'lat'
                            }
                        }
                    )
                    .shape('circle')
                    .color("name", cli)
                    .size('size', v => {
                        let p = v / source[0].size;
                        // p < 0.4 ? p = (p + 0.2).toFixed(2) - 0 : '';
                        return p * 100
                    })
                    .animate(true)
                    .style({});

                // 柱子
                const barLayer = new PointLayer({ zIndex: 2, depth: false })
                    .source(
                        source,
                        {
                            parser: {
                                type: 'json',
                                x: 'lng',
                                y: 'lat'
                            }
                        }
                    )
                    .shape('cylinder')
                    .color("name", cli)
                    .size('size', v => {
                        let p = v / source[0].size;
                        // p < 0.4 ? p = (p + 0.2).toFixed(2) - 0 : '';
                        return [5, 5, p * 300]
                    })
                    .animate(true)
                    .style({
                        raisingHeight: 200000,
                        opacityLinear: {
                            enable: true, // true - false
                            dir: 'up' // up - down
                        },
                        lightEnable: false
                    });
                scene.addLayer(gd);
                scene.addLayer(bottomLayer);
                scene.addLayer(layer);
                scene.addLayer(lineUp);
                scene.addLayer(waveLayer);
                scene.addLayer(barLayer);

                timeout()
                mapFun();
            })
        });
    }

    function mapFun() {
        if (timeHome) clearTimeout(timeHome);
        timeHome = setTimeout(() => {
            timeout(scene)
        }, 3000);
    }

    function timeout() {
        // scene.setCenter([source[index].lng, source[index].lat])
        mapFun(scene);
        anchorLayer && scene.removeAllMakers();
        textLayer && scene.removeLayer(textLayer);
        var el = document.createElement('div'), son = document.createElement('div');
        el.className = 'tooltip';
        son.className = "tooltipSon";
        son.innerHTML = `<div>${source[index].name}</div>${utils.formatNumber(source[index].size, 2)}`;
        el.appendChild(son);
        // toolpit
        anchorLayer = new Marker({
            element: el
        }).setLnglat([source[index].lng, source[index].lat]);

        const text = [], province = [];
        for (let i = 0; i < source.length; i++) {
            if (index === i) {
                li[i].value = 10000 * Math.random();
                li[i] && province.push(li[i]);
                continue
            }
            const v = source[i];
            text.push(v);
        }
        // 文字
        textLayer = new PointLayer({ zIndex: 1, blend: "normal" })
            .source(text, {
                parser: {
                    type: 'json',
                    x: 'lng',
                    y: 'lat'
                }
            })
            .shape('name', 'text')
            .size(14)
            .style({
                textAnchor: 'center', // 文本相对锚点的位置 center|left|right|top|bottom|top-left
                spacing: 2, // 字符间距
                padding: [1, 1], // 文本包围盒 padding [水平，垂直]，影响碰撞检测结果，避免相邻文本靠的太近
                stroke: '#FFFFFF', // 描边颜色
                strokeWidth: 0.2, // 描边宽度
                raisingHeight: 90000,
                textAllowOverlap: true
            });
        scene.addLayer(textLayer);
        scene.addMarker(anchorLayer);

        if (source[index + 1]) index++
        else index = 0;
    }
    onMount(() => {
        TrendChart()
    })
    return (
        <div className="livRang map" style={`width:${prop.width}px;`}>
            <div className="head">{prop.title}</div>
            <div ref={$canvas} style={`width:${prop.width}px;height:${prop.height}px;position: relative;`}></div>
        </div>
    );
}

export default Map;
