import { __awaiter, __generator } from "tslib";
import { TIMESPAN_INSTANT } from '../core/Constant';
import Instance from '../core/Instance';
import { Cesium3DTileset, Color, WebMercatorTilingScheme, UrlTemplateImageryProvider, CesiumTerrainProvider, EllipsoidTerrainProvider, Cesium3DTileStyle, ClassificationType, SingleTileImageryProvider, VerticalOrigin, LabelStyle, Cartesian2, Cartesian3 } from '@msign/angularis';
var tt = 'http://pvg5ixxws.bkt.clouddn.com/demo/dayanta/tt/tileset.json';
var tc = 'http://pvg5ixxws.bkt.clouddn.com/demo/dayanta/tv/tileset.json';
var img_sat_google_wgs84 = 'https://gis.7cdn.msign.net/maps/google_map_com/vt/lyrs=s@26803&x={x}&y={y}&z={z}';
var img_sat_google_gcj02 = 'https://gis.7cdn.msign.net/maps/google_map_com/vt/lyrs=s@26803&gl=CN&x={x}&y={y}&z={z}';
var trr_world = 'https://assets.agi.com/stk-terrain/v1/tilesets/PAMAP/tiles';
var trr_test = 'https://gis.7cdn.msign.net/terrains/terr_test/srtm_59_08-2';
var trr_china = 'https://gis.7cdn.msign.net/terrains/terr_china';
var trr_huizhou = 
// 'https://gis.7cdn.msign.net/zt/5um9/testdata/terrain/ASTGTM2_N23E114';
'https://gis.7cdn.msign.net/zt/5um9/testdata/terrain/CEHUI_HUIZHOU_LOCAL_FLOAT';
// const trr_test = 'http://k8s-01.zt.msign.net/data/terr_test/srtm_59_08-2';
var SceneControl = /** @class */ (function () {
    function SceneControl(viewer) {
        this._pCache = new Map();
        this._layerStyleConf = {
            highLightIds: [],
            hideIds: [],
            opacity: 1,
            opacityCover: false,
            colors: {}
        };
        // 载入数据栈
        this._layerStack = [];
        // 选择集
        this._selection = [];
        this._hoverOriginColor = Color.WHITE.clone();
        this._viewer = viewer;
        this._scene = viewer.scene;
    }
    SceneControl.prototype._layer3DTileClassificationHelperSwitch = function (isActive) {
        if (isActive === void 0) { isActive = true; }
        // const
        if (isActive) {
            var l3DC = this._layer3DTileClassification;
        }
    };
    // 地形, 地球, 影像相关
    SceneControl.prototype._earthOn = function () {
        return __awaiter(this, void 0, void 0, function () {
            var scene;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        scene = this._viewer.scene;
                        // scene.globe = new Globe();
                        scene.globe.show = true;
                        return [4 /*yield*/, this._imageOn()];
                    case 1:
                        _a.sent();
                        return [4 /*yield*/, this._terrainOn()];
                    case 2:
                        _a.sent();
                        return [4 /*yield*/, this._globalDepthTestOn()];
                    case 3:
                        _a.sent();
                        return [2 /*return*/];
                }
            });
        });
    };
    SceneControl.prototype._earthOff = function () {
        return __awaiter(this, void 0, void 0, function () {
            var scene;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        scene = this._viewer.scene;
                        return [4 /*yield*/, this._imageOff()];
                    case 1:
                        _a.sent();
                        return [4 /*yield*/, this._terrainOff()];
                    case 2:
                        _a.sent();
                        return [4 /*yield*/, this._globalDepthTestOff()];
                    case 3:
                        _a.sent();
                        // scene.globe = null as any;
                        scene.globe.show = false;
                        return [2 /*return*/];
                }
            });
        });
    };
    SceneControl.prototype._imageOn = function (urlTpl, _a) {
        if (urlTpl === void 0) { urlTpl = img_sat_google_wgs84; }
        var _b = _a === void 0 ? {} : _a, _c = _b.tilingScheme, tilingScheme = _c === void 0 ? new WebMercatorTilingScheme() : _c, _d = _b.maximumLevel, maximumLevel = _d === void 0 ? 21 : _d;
        return __awaiter(this, void 0, void 0, function () {
            var _e, viewer, pC, ly;
            return __generator(this, function (_f) {
                _e = this, viewer = _e._viewer, pC = _e._pCache;
                ly = pC.get(urlTpl);
                if (ly) {
                    viewer.imageryLayers.contains(ly) ||
                        viewer.imageryLayers.addImageryProvider(ly);
                }
                else {
                    ly = viewer.imageryLayers.addImageryProvider(new UrlTemplateImageryProvider({
                        url: urlTpl,
                        credit: '',
                        tilingScheme: tilingScheme,
                        maximumLevel: maximumLevel
                    }));
                    pC.set(urlTpl, ly);
                }
                return [2 /*return*/];
            });
        });
    };
    SceneControl.prototype._imageOff = function (urlTpl) {
        return __awaiter(this, void 0, void 0, function () {
            var _a, viewer, pC, ly;
            return __generator(this, function (_b) {
                _a = this, viewer = _a._viewer, pC = _a._pCache;
                if (urlTpl) {
                    ly = pC.get(urlTpl);
                    if (!ly)
                        return [2 /*return*/];
                    viewer.imageryLayers.contains(ly) && viewer.imageryLayers.remove(ly);
                    pC.delete(urlTpl);
                }
                else {
                    viewer.imageryLayers.removeAll();
                    pC.clear();
                }
                return [2 /*return*/];
            });
        });
    };
    SceneControl.prototype._terrainOn = function (urlTpl, option) {
        if (urlTpl === void 0) { urlTpl = trr_world; }
        if (option === void 0) { option = {
            requestWaterMask: true,
            requestVertexNormals: true
        }; }
        return __awaiter(this, void 0, void 0, function () {
            var _a, viewer, pC, ly;
            return __generator(this, function (_b) {
                _a = this, viewer = _a._viewer, pC = _a._pCache;
                ly = pC.get(urlTpl);
                // console.log('pC.get(urlTpl)', pC.get(urlTpl));
                if (ly) {
                    viewer.terrainProvider = ly;
                }
                else {
                    ly = new CesiumTerrainProvider({
                        // url: trr_china
                        url: trr_huizhou
                    });
                    pC.set(urlTpl, ly);
                }
                viewer.terrainProvider = ly;
                return [2 /*return*/];
            });
        });
    };
    SceneControl.prototype._terrainOff = function () {
        return __awaiter(this, void 0, void 0, function () {
            var viewer;
            return __generator(this, function (_a) {
                viewer = this._viewer;
                viewer.terrainProvider = new EllipsoidTerrainProvider();
                return [2 /*return*/];
            });
        });
    };
    SceneControl.prototype._globalDepthTestOn = function () {
        return __awaiter(this, void 0, void 0, function () {
            var viewer;
            return __generator(this, function (_a) {
                viewer = this._viewer;
                viewer.scene.globe && (viewer.scene.globe.depthTestAgainstTerrain = true);
                return [2 /*return*/];
            });
        });
    };
    SceneControl.prototype._globalDepthTestOff = function () {
        return __awaiter(this, void 0, void 0, function () {
            var viewer;
            return __generator(this, function (_a) {
                viewer = this._viewer;
                viewer.scene.globe && (viewer.scene.globe.depthTestAgainstTerrain = false);
                return [2 /*return*/];
            });
        });
    };
    SceneControl.prototype.loadLayer3DTile = function (url, autoFocus) {
        if (url === void 0) { url = tt; }
        if (autoFocus === void 0) { autoFocus = true; }
        return __awaiter(this, void 0, void 0, function () {
            var layer3DTile, viewer, scene, cSta, state;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        layer3DTile = new Cesium3DTileset({
                            url: url,
                            maximumScreenSpaceError: 16,
                            maximumNumberOfLoadedTiles: 1024,
                            pointCloudShading: {
                                attenuation: true,
                                maximumAttenuation: 2,
                                geometricErrorScale: 2
                            }
                        });
                        viewer = this._viewer;
                        scene = viewer.scene;
                        scene.primitives.add(layer3DTile);
                        return [4 /*yield*/, Instance.getInstanceStateControl()];
                    case 1:
                        cSta = _a.sent();
                        state = cSta.state;
                        //设置颜色模式为替换Cesium3DTileStyle
                        layer3DTile['colorBlendMode'] = 1;
                        // TODO 设置颜色模式
                        return [4 /*yield*/, layer3DTile['readyPromise']];
                    case 2:
                        // TODO 设置颜色模式
                        _a.sent();
                        this._layer3DTile = layer3DTile;
                        console.log('layer3DTile ready.');
                        autoFocus && viewer.zoomTo(layer3DTile);
                        window['layer3DTile'] = layer3DTile;
                        window['viewer'] = viewer;
                        // 异步启动内容解析流程
                        // const cWo = await Instance.getInstanceWorkerControl();
                        // const wPFP = cWo.createInstancePFP();
                        // wPFP.startFromUrl(url);
                        // this.doAssembleStyle();
                        return [2 /*return*/, layer3DTile];
                }
            });
        });
    };
    SceneControl.prototype.loadLayerPointCloud = function (url, clear) {
        if (url === void 0) { url = tt; }
        if (clear === void 0) { clear = false; }
        return __awaiter(this, void 0, void 0, function () {
            var layerPointCloud, viewer, scene;
            return __generator(this, function (_a) {
                layerPointCloud = new Cesium3DTileset({
                    url: url,
                    pointCloudShading: {
                        attenuation: true,
                        maximumAttenuation: 2,
                        geometricErrorScale: 2
                    }
                });
                layerPointCloud.style = new Cesium3DTileStyle({
                    pointSize: '5.0'
                });
                viewer = this._viewer;
                scene = viewer.scene;
                if (clear)
                    scene['_primitives'].removeAll();
                scene.primitives.add(layerPointCloud);
                window['layerPointCloud'] = layerPointCloud;
                // @ts-ignore
                viewer.zoomTo(layerPointCloud);
                this._layer3DTile = layerPointCloud;
                layerPointCloud['skipStyleSet'] = true;
                return [2 /*return*/, layerPointCloud];
            });
        });
    };
    SceneControl.prototype.loadClassificationTile = function (tileset) {
        if (tileset === void 0) { tileset = tc; }
        var scene = this._viewer.scene;
        var layer3DTileClassification = (this._layer3DTileClassification = new Cesium3DTileset({
            url: tileset,
            maximumScreenSpaceError: 16,
            maximumNumberOfLoadedTiles: 1024,
            classificationType: ClassificationType.CESIUM_3D_TILE
        }));
        scene.primitives.add(layer3DTileClassification);
        // todo debug only
        window['layer3DTileClassification'] = layer3DTileClassification;
        return layer3DTileClassification;
    };
    SceneControl.prototype.unloadLayer = function (layer) {
        return __awaiter(this, void 0, void 0, function () {
            var viewer, scene;
            return __generator(this, function (_a) {
                viewer = this._viewer;
                scene = viewer.scene;
                return [2 /*return*/, scene.primitives.contains(layer) && scene.primitives.remove(layer)];
            });
        });
    };
    Object.defineProperty(SceneControl.prototype, "isEarthVisible", {
        get: function () {
            return this._scene.globe && true;
        },
        set: function (val) {
            if (val) {
                this._earthOn();
            }
            else {
                this._earthOff();
            }
        },
        enumerable: true,
        configurable: true
    });
    SceneControl.prototype.doAssembleStyle = function () {
        var _layer3DTile = this._layer3DTile;
        if (!_layer3DTile || _layer3DTile['skipStyleSet'])
            return;
        var _layerStyleConf = this._layerStyleConf;
        var colorOption = {
            // evaluateColor: function(feature, result) {
            //   return Color.clone(Color.YELLOW, result);
            // }
            conditions: [
            // [
            //   'true',
            //   !_layerStyleConf['opacityCover']
            //     ? 'rgba(${red}, ${green}, ${blue},' +
            //       _layerStyleConf['opacity'] +
            //       ')'
            //     : 'rgba(64,64,128,' + _layerStyleConf['opacity'] + ')'
            // ]
            ]
        };
        // 组装颜色设置条件
        // @ts-ignore
        var colors = _layerStyleConf.colors, hideIds = _layerStyleConf.hideIds, highLightIds = _layerStyleConf.highLightIds;
        // for (const key in colors) {
        //   // @ts-ignore
        //   colorOption.conditions.unshift([
        //     "regExp('_' + String(${DbId}) + '_').test('_" +
        //       colors[key].ids.join('_') +
        //       "_')",
        //     key
        //   ]);
        // }
        // // 组装高亮清单
        // highLightIds.length
        //   ? colorOption.conditions.unshift([
        //       "regExp('_' + String(${DbId}) + '_').test('_" +
        //         highLightIds.join('_') +
        //         "_')",
        //       'rgba(223,193,26,1)'
        //     ])
        //   : '';
        // // 组装隐藏对象条件
        // hideIds.length
        //   ? colorOption.conditions.unshift([
        //       "regExp('_' + String(${DbId}) + '_').test('_" +
        //         hideIds.join('_') +
        //         "_')",
        //       'rgba(1,1,1,0)'
        //     ])
        //   : '';
        // @ts-ignore
        _layer3DTile.style = new Cesium3DTileStyle({
            color: colorOption,
            show: 'true',
            meta: {
                description: '"Building DbId ${DbId}"'
            }
        });
        this.forceRender(100);
    };
    SceneControl.prototype.doSetColorStyle = function (ids, color) {
        var _a;
        var colors = this._layerStyleConf['colors'];
        colors[color]
            ? (_a = colors[color].ids).push.apply(_a, ids) : (colors[color] = { ids: ids });
        this.doAssembleStyle();
    };
    SceneControl.prototype.doSetVisibleStyle = function (ids, isSHow) {
        // @ts-ignore
        var hideIds = this._layerStyleConf.hideIds;
        ids.forEach(function (id) {
            if (isSHow) {
                hideIds.includes(id) ? hideIds.splice(hideIds.indexOf(id), 1) : '';
            }
            else {
                !hideIds.includes(id) ? hideIds.push(id) : '';
            }
        });
        this.doAssembleStyle();
    };
    SceneControl.prototype.doSetHighLightStyle = function (ids) {
        this._layerStyleConf['highLightIds'] = ids;
        this.doAssembleStyle();
    };
    SceneControl.prototype.doSetOpacityStyle = function (opacity, cover) {
        if (cover === void 0) { cover = false; }
        var _layerStyleConf = this._layerStyleConf;
        _layerStyleConf['opacity'] = opacity;
        _layerStyleConf['opacityCover'] = cover;
        this.doAssembleStyle();
    };
    SceneControl.prototype.resetCamera = function () {
        var _a = this, viewer = _a._viewer, lyStack = _a._layerStack;
        var camera = viewer.camera, scene = viewer.scene;
        if (lyStack.length) {
            var tar = lyStack[lyStack.length - 1];
        }
    };
    SceneControl.prototype.doSetImagerLayer = function (url) {
        return __awaiter(this, void 0, void 0, function () {
            var _viewer, imgProvider, imagery;
            return __generator(this, function (_a) {
                _viewer = this._viewer;
                imgProvider = new SingleTileImageryProvider({
                    url: url
                });
                imagery = _viewer.imageryLayers.addImageryProvider(imgProvider);
                imagery.alpha = 1.0;
                return [2 /*return*/];
            });
        });
    };
    SceneControl.prototype.addLocationMarker = function (option) {
        var _viewer = this._viewer;
        var label = option.label, position = option.position, image = option.image, id = option.id;
        var entityOption = {
            position: Cartesian3.fromDegrees(Number(position.long) || 0, Number(position.lat) || 0, position.elevation || 2000),
            id: id,
            billboard: {
                disableDepthTestDistance: Number.POSITIVE_INFINITY,
                image: image || require('../assets/img/location.png'),
                width: 64,
                height: 64
            },
            label: {
                text: label || '没有输入文本',
                font: '14pt monospace',
                style: LabelStyle.FILL_AND_OUTLINE,
                outlineWidth: 2,
                verticalOrigin: VerticalOrigin.TOP,
                pixelOffset: new Cartesian2(0, -64)
            }
        };
        // @ts-ignore
        return _viewer.entities.add(entityOption);
    };
    SceneControl.prototype.removeById = function (id) {
        var _viewer = this._viewer;
        _viewer.entities.removeById(id);
    };
    /** *****************************************
     *  强制刷新, 持续一定时间
     ********************************************/
    SceneControl.prototype.forceRender = function (timespan) {
        if (timespan === void 0) { timespan = TIMESPAN_INSTANT; }
        return __awaiter(this, void 0, void 0, function () {
            var viewer, scene;
            var _this = this;
            return __generator(this, function (_a) {
                viewer = this._viewer;
                scene = viewer.scene;
                if (!scene.requestRenderMode)
                    return [2 /*return*/, this];
                return [2 /*return*/, new Promise(function (resolve) {
                        scene.requestRenderMode = false;
                        setTimeout(function () {
                            scene.requestRenderMode = true;
                            resolve(_this);
                        }, timespan);
                    })];
            });
        });
    };
    Object.defineProperty(SceneControl.prototype, "scene", {
        get: function () {
            return this._scene;
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(SceneControl.prototype, "viewer", {
        get: function () {
            return this._viewer;
        },
        enumerable: true,
        configurable: true
    });
    return SceneControl;
}());
export default SceneControl;
