import {createMVTWithStyle} from './mvt'

import {
    drawRectangle
} from './rectangle.js'

var defined = Cesium.defined
var formatError = Cesium.formatError
var queryToObject = Cesium.queryToObject
var TileMapServiceImageryProvider = Cesium.TileMapServiceImageryProvider
var Viewer = Cesium.Viewer
var UrlTemplateImageryProvider = Cesium.UrlTemplateImageryProvider


var fixGltf = function (gltf) {
    if (!gltf.extensionsUsed) {
        return;
    }

    var v = gltf.extensionsUsed.indexOf('KHR_technique_webgl');
    var t = gltf.extensionsRequired.indexOf('KHR_technique_webgl');
    // 中招了。。
    if (v !== -1) {
        gltf.extensionsRequired.splice(t, 1, 'KHR_techniques_webgl');
        gltf.extensionsUsed.splice(v, 1, 'KHR_techniques_webgl');
        gltf.extensions = gltf.extensions || {};
        gltf.extensions['KHR_techniques_webgl'] = {};
        gltf.extensions['KHR_techniques_webgl'].programs = gltf.programs;
        gltf.extensions['KHR_techniques_webgl'].shaders = gltf.shaders;
        gltf.extensions['KHR_techniques_webgl'].techniques = gltf.techniques;
        var techniques = gltf.extensions['KHR_techniques_webgl'].techniques;

        gltf.materials.forEach(function (mat, index) {
            gltf.materials[index].extensions['KHR_technique_webgl'].values = gltf.materials[index].values;
            gltf.materials[index].extensions['KHR_techniques_webgl'] = gltf.materials[index].extensions['KHR_technique_webgl'];

            var vtxfMaterialExtension = gltf.materials[index].extensions['KHR_techniques_webgl'];

            for (var value in vtxfMaterialExtension.values) {
                var us = techniques[vtxfMaterialExtension.technique].uniforms;
                for (var key in us) {
                    if (us[key] === value) {
                        vtxfMaterialExtension.values[key] = vtxfMaterialExtension.values[value];
                        delete vtxfMaterialExtension.values[value];
                        break;
                    }
                }
            };
        });

        techniques.forEach(function (t) {
            for (var attribute in t.attributes) {
                var name = t.attributes[attribute];
                t.attributes[attribute] = t.parameters[name];
            };

            for (var uniform in t.uniforms) {
                var name = t.uniforms[uniform];
                t.uniforms[uniform] = t.parameters[name];
            };
        });
    }
}

Object.defineProperties(Cesium.Model.prototype, {
    _cachedGltf: {
        set: function (value) {
            this._vtxf_cachedGltf = value;
            if (this._vtxf_cachedGltf && this._vtxf_cachedGltf._gltf) {
                fixGltf(this._vtxf_cachedGltf._gltf);
            }
        },
        get: function () {
            return this._vtxf_cachedGltf;
        }
    }
});

// 创建热力图
function createHeatMap(max, data) {
    // 创建元素
    var heatDoc = document.createElement("div");
    heatDoc.setAttribute("style", "width:1000px;height:1000px;margin: 0px;display: none;");
    document.body.appendChild(heatDoc);
    // 创建热力图对象
    var heatmap = h337.create({
        container: heatDoc,
        radius: 20,
        maxOpacity: .5,
        minOpacity: 0,
        blur: .75,
        gradient: {
            '0.9': 'red',
            '0.8': 'orange',
            '0.7': 'yellow',
            '0.5': 'blue',
            '0.3': 'green',
        },
    });
    // 添加数据
    heatmap.setData({
        max: max,
        data: data
    });
    return heatmap;
}

// 创建正方形 绑定热力图 
function createRectangle(viewer, coordinate, heatMap) {
    viewer.entities.add({
        name: 'Rotating rectangle with rotating texture coordinate',
        show: true,
        rectangle: {
            coordinates: new Cesium.Rectangle(coordinate[0], coordinate[1], coordinate[2], coordinate[3]), //Cesium.Rectangle.fromDegrees(coordinate[0], coordinate[1], coordinate[2], coordinate[3]),
            material: heatMap._renderer.canvas // 核心语句，填充热力图
        }
    });
}


// 生成len个随机数据
function getData(len) {
    //构建一些随机数据点
    var points = [];
    var max = 0;
    var width = 1000;
    var height = 1000;
    while (len--) {
        var val = Math.floor(Math.random() * 500);
        max = Math.max(max, val);
        var point = {
            x: Math.floor(Math.random() * width),
            y: Math.floor(Math.random() * height),
            value: val
        };
        points.push(point);
    }
    return {
        max: max,
        data: points
    }
}

function main() {
    /*
     Options parsed from query string:
       source=url          The URL of a CZML/GeoJSON/KML data source to load at startup.
                           Automatic data type detection uses file extension.
       sourceType=czml/geojson/kml
                           Override data type detection for source.
       flyTo=false         Don't automatically fly to the loaded source.
       tmsImageryUrl=url   Automatically use a TMS imagery provider.
       lookAt=id           The ID of the entity to track at startup.
       stats=true          Enable the FPS performance display.
       inspector=true      Enable the inspector widget.
       debug=true          Full WebGL error reporting at substantial performance cost.
       theme=lighter       Use the dark-text-on-light-background theme.
       scene3DOnly=true    Enable 3D only mode.
       view=longitude,latitude,[height,heading,pitch,roll]
                           Automatically set a camera view. Values in degrees and meters.
                           [height,heading,pitch,roll] default is looking straight down, [300,0,-90,0]
       saveCamera=false    Don't automatically update the camera view in the URL when it changes.
     */
    var $loadingIndicator = document.getElementById('loadingIndicator')
    var endUserOptions = queryToObject(window.location.search.substring(1));

    var imageryProvider;
    if (defined(endUserOptions.tmsImageryUrl)) {
        imageryProvider = new TileMapServiceImageryProvider({
            url: endUserOptions.tmsImageryUrl
        });
    }

    var viewer;
    try {
        // var hasBaseLayerPicker = !defined(imageryProvider);
        // viewer = new Viewer('cesiumContainer', {
        //     imageryProvider : imageryProvider,
        //     baseLayerPicker : hasBaseLayerPicker,
        //     scene3DOnly : endUserOptions.scene3DOnly,
        //     requestRenderMode : true
        // });

        // if (hasBaseLayerPicker) {
        //     var viewModel = viewer.baseLayerPicker.viewModel;
        //     viewModel.selectedTerrain = viewModel.terrainProviderViewModels[1];
        // } else {
        //     viewer.terrainProvider = createWorldTerrain({
        //         requestWaterMask: true,
        //         requestVertexNormals: true
        //     });
        // }

        var Google = new UrlTemplateImageryProvider({
            url: "http://mt3.google.cn/vt/lyrs=y@110&hl=zh-CN&gl=cn&src=app&x={x}&y={y}&z={z}&s=Ga",
        })

       //天地图影像服务
      var tdtImagerLayerProvider =new Cesium.WebMapTileServiceImageryProvider({
        url: "http://{s}.tianditu.gov.cn/img_c/wmts?tk=463a3e5ee4e35c17ae02564f18f95655&service=wmts&request=GetTile&version=1.0.0" +
        "&LAYER=img&tileMatrixSet=c&TileMatrix={TileMatrix}&TileRow={TileRow}&TileCol={TileCol}" +
        "&style=default&format=tiles",
        layer: "tdtImg_c",
        style: "default",
        format: "tiles",
        tileMatrixSetID: "c",
        subdomains:["t0","t1","t2","t3","t4","t5","t6","t7"],
        tilingScheme:new Cesium.GeographicTilingScheme(),
       tileMatrixLabels:["1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16","17","18","19"],
        maximumLevel:50,
        show: false
    })   


        var PBF = createMVTWithStyle(Cesium, ol, createMapboxStreetsV6Style, {
            url: 'pbf/{z}/{x}/{y}.pbf',
            key: "pk.eyJ1IjoibXV5YW8xOTg3IiwiYSI6ImNpcm9ueHd6cjAwNzZoa20xazY1aWlubjIifQ.5tLtC5j1rh8Eqjlyrq3OaA"
        });


        viewer = window.viewer = new Viewer('cesiumContainer', {
            resolutionScale: 1,
            terrainProviderViewModels: [],
            animation: false, //动画控制不显示     
            baseLayerPicker: false,
            fullscreenButton: false, //全屏按钮,默认显示true
            geocoder: false, //地名查找,默认true
            timeline: false, //时间线,默认true
            vrButton: false, //双屏模式,默认不显示false
            homeButton: true, //主页按钮，默认true 
            infoBox: false, //点击要素之后显示的信息,默认true
            selectionIndicator: false, //选中元素显示,默认true
            sceneModePicker: false, //是否显示投影方式控件
            navigationHelpButton: true, //是否显示帮助信息控件
            maximumRenderTimeChange: Infinity,
            requestRenderMode: true,
            imageryProvider: tdtImagerLayerProvider,
        });

        //viewer.scene.debugShowFramesPerSecond = true;
        //viewer.scene.screenSpaceCameraController.enableTranslate = false;
        //viewer.scene.screenSpaceCameraController.enableTilt = false;
        //viewer.scene.screenSpaceCameraController.enableLook = false;
        //viewer.scene.screenSpaceCameraController.enableCollisionDetection = false;

        var imageryLayers = viewer.imageryLayers;
        imageryLayers.addImageryProvider(PBF);


        viewer.camera.setView({
            destination: Cesium.Cartesian3.fromDegrees(113.07242100, 22.58652789, 1000.0),
            orientation: {
                heading: 5.205384767667713,
                pitch: -1.0220630084744524,
                roll: 6.27919703978724
            }
        })

        // 第一个热力图
        // var coordinate1 = [1.9733857532084744,  0.39425835263667813,  1.9733970408057608,  0.39426568435545245];
        // var heatMap1 = createHeatMap(getData(1000).max, getData(1000).data);
        // createRectangle(viewer, coordinate1, heatMap1);

        // 第二个热力图
        // var coordinate2 = [-109.0, 30.0, -80.0, 41.0];
        // var heatMap2 = createHeatMap(getData(3000).max, getData(3000).data);
        // createRectangle(viewer, coordinate2, heatMap2);

        // // 第三个热力图
        // var coordinate3 = [-109.0, 41.0, -80.0, 50.0];
        // var heatMap3 = createHeatMap(getData(5000).max, getData(5000).data);
        // createRectangle(viewer, coordinate3, heatMap3);


        var handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);

        drawRectangle(Cesium, viewer, handler, function (coords) {
            console.log(coords)
            var heatMap1 = createHeatMap(getData(1000).max, getData(1000).data);
            createRectangle(viewer, [coords.west, coords.south, coords.east, coords.north], heatMap1);
        });

        var tileset = viewer.scene.primitives.add(new Cesium.Cesium3DTileset({
            url: "/static/tiles/temp/tileset.json", //Cesium.IonResource.fromAssetId(item) //'static/tiles/tileset.json'
            //maximumMemoryUsage:200
            maximumScreenSpaceError: 25,
            maximumNumberOfLoadedTiles: 1000
        }));

        tileset.readyPromise.then(function (tileset) {
            //viewer.entities.values.forEach(item=>item.show = true)
            //viewer.zoomTo(tileset);
            viewer.homeButton.viewModel.command.beforeExecute.addEventListener(function (e) {
                e.cancel = true;
                //viewer.zoomTo(tileset,new Cesium.HeadingPitchRoll(5.208372654027434, -0.22688012666187052, 6.281056493524698));
                //viewer.zoomTo(tileset,new Cesium.HeadingPitchRange(5.208372654027434, -0.22688012666187052, tileset.boundingSphere.radius * 2.0));
                viewer.zoomTo(tileset);
            });
        }).otherwise(function (error) {
            console.log(error);
        });

        viewer.camera.changed.addEventListener(
            function () {
                if (viewer.camera._suspendTerrainAdjustment && viewer.scene.mode === Cesium.SceneMode.SCENE3D) {
                    viewer.camera._suspendTerrainAdjustment = false;
                    viewer.camera._adjustHeightForTerrain();
                }
            }
        );


    } catch (exception) {
        $loadingIndicator.style.display = 'none';
        var message = formatError(exception);
        console.error(message);
        if (!document.querySelector('.cesium-widget-errorPanel')) {
            window.alert(message); //eslint-disable-line no-alert
        }
        return;
    }

    $loadingIndicator.style.display = 'none';
}

export function start(){
    main()
}