<template>
    <div class="container">
        <div style="position: absolute;top: 20px;left: 20px;z-index: 9;">
            <div style="display: flex;">
                <el-select
                v-model="typeValue"
                placeholder="Select"
                style="width: 150px;background: black;"
                @change="changType"
                >
                <el-option
                    v-for="item in options"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                />
                </el-select>
                <el-input v-if="typeValue != 6" v-model="inputAddress" style="max-width: 200px;height: 32px;margin: 0px 10px;background: black;" placeholder="输入URL地址……" />
                <div style="padding: 0px 10px;" v-if="typeValue == 6">
                    <el-upload
                        ref="uploadRef"
                        action=""
                        :auto-upload="false"
                        :file-list="fileList"
                        :show-file-list="false"
                        accept=".json,.geojson"
                        :on-change="handleChange"
                    >
                    <template #trigger>
                        <el-button type="primary">上传文件</el-button>
                    </template>
                    </el-upload>
                </div>
                <el-button type="primary" @click="parse">解析</el-button>
            </div>
        </div>
        <Map style="overflow: hidden;"></Map>
        <div class="infoDialog" v-show="infoDialogShow">
            <div class="close" @click="closeWin">×</div>
            <div class="content" v-if="nowPoint != null">
                <el-scrollbar>
                    <div class="item" v-for="info in nowPointInfo" :key="info">{{info.key}}: {{ info.value }}</div>
                </el-scrollbar>
            </div>
        </div>
    </div>
</template>

<script>
import { ElMessage } from 'element-plus'
import Map from "@/views/example/Map.vue";
import { toRaw } from "vue";
export default {
    name: "",
    components: {
       Map
    },
    data() {
        return {
            listData:[],
            fileList: [],
            dataJson:[],
            wmslayer: {},
            pointImg:require('@static/images/point.png'),
            geometryArr:[],
            mapHandle:null,
            infoDialogShow:false,
            nowPoint: null,
            nowPointInfo:null,
            typeValue:'1',
            inputAddress:'http://121.43.55.7:8889/geoserver/kdyjs/wms',
            options:[
                {
                    value: '1',
                    label: '栅格WMS服务',
                },
                {
                    value: '2',
                    label: '栅格WMTS服务',
                },{
                    value: '3',
                    label: '栅格ArcGis服务',
                },
                {
                    value: '4',
                    label: '3dtiles数据',
                },
                // {
                //     value: '5',
                //     label: '矢量数据',
                // },
                {
                    value: '6',
                    label: '矢量文件',
                }
            ]
        };
    },
    mounted() {
        
    },
    methods: {
        beforeUpload(file) {
            const maxSize = 2; // 限制为2MB
            if (file.size / 1024 / 1024 > maxSize) {
                ElMessage({
                    type: 'error',
                    message: `文件大小不能超过 ${maxSize}MB！`,
                })
                return false;
            }
            return true;
        },
        handleChange(files,fileLists){
            let that = this;
            if (fileLists.length >1) {
                fileLists.shift();
            }
            that.fileList = fileLists;
            let reader = new FileReader();
            reader.readAsText(that.fileList[0].raw, "UTF-8");
            reader.onload = (evt) => {
                that.dataJson = JSON.parse(evt.target.result);
                console.log(that.dataJson); // 输出解析后的JSON数据
                ElMessage({
                    type: 'success',
                    message: `文件处理成功，请解析上图展示`,
                })
            };
        },
        closeWin() {
            this.infoDialogShow = false;
            this.nowPoint = null;
            this.nowPointInfo = null;
        },
        dwanMap(){
            let that = this;
            if(that.geometryArr.length>0){
                that.geometryArr.map(function (info) {
                    viewer.entities.remove(info)
                })
            }
            that.geometryArr = that.dataJson.features.map(function (info) {
                if(info.geometry.type == "Point"){
                    return that.addPoint(info)
                }else if(info.geometry.type == "LineString"){
                    return that.addLine(info)
                }else{
                    return that.addPolygon(info)
                }
                
            })
            that.pointTCHandle();
        },
        addPolygon(param){
            let arr = [];
            param.geometry.coordinates.forEach(element => {
                element.forEach(e => {
                    arr.push(e[0]);
                    arr.push(e[1]);
                })
            });
            return viewer.entities.add(new SkyScenery.Entity({
                name: " polygon",
                polygon: {
                    hierarchy: {
                        positions: SkyScenery.Cartesian3.fromDegreesArray(arr)
                    },
                    heightReference: SkyScenery.HeightReference.CLAMP_TO_GROUND,
                    material: SkyScenery.Color.CYAN.withAlpha(0.5)
                },
                info: {
                    coor: [arr[0], arr[1]],
                    properties: param.properties
                },
            }));
        },
        addLine(param){
            return viewer.entities.add({
                name: "line",
                polyline: {
                    //经纬度数组转世界坐标，带高度的话是fromDegreesArrayHeights
                    positions: SkyScenery.Cartesian3.fromDegreesArray(param.geometry.coordinates),
                    width: 2,
                    material: SkyScenery.Color.CYAN,
                    info: {
                        properties: param.properties
                    },
                }
            });
        },
        addPoint(param){
            let that = this;
            return viewer.entities.add(new SkyScenery.Entity({
                name:"point",
                position: SkyScenery.Cartesian3.fromDegrees(param.geometry.coordinates[0], param.geometry.coordinates[1]),
                type: "point",
                info: {
                  coor: [param.geometry.coordinates[0], param.geometry.coordinates[1]],
                  properties: param.properties
                },
                billboard: {
                  image: that.pointImg,
                  disableDepthTestDistance: Number.POSITIVE_INFINITY,
                  scale: 0.3,
                  horizontalOrigin: SkyScenery.HorizontalOrigin.CENTER,
                  verticalOrigin: SkyScenery.VerticalOrigin.BOTTOM,
                }
              }));
        },
        // 点击事件绑定
        pointTCHandle() {
            let that = this;
            if (!this.mapHandle) {
                this.mapHandle = new SkyScenery.ScreenSpaceEventHandler(viewer.canvas, this);
                this.mapHandle.setInputAction(function (movement) {
                    that.infoDialogShow = false
                    const pickedObject = viewer.scene.pick(movement.position);

                    let cartesian = viewer.camera.pickEllipsoid(
                        movement.position,
                        viewer.scene.globe.ellipsoid
                    );
                    // 空间坐标转世界坐标(弧度)
                    let cartographic = SkyScenery.Cartographic.fromCartesian(cartesian);
                    // 弧度转为角度（经纬度）
                    let lon = SkyScenery.Math.toDegrees(cartographic.longitude); // 经度值
                    let lat = SkyScenery.Math.toDegrees(cartographic.latitude); // 纬度值
                    let center = [lon,lat]
                    if (SkyScenery.defined(pickedObject) && SkyScenery.defined(pickedObject.id)) {
                        const entity = pickedObject.id;
                        that.infoDialogShow = true
                        that.nowPoint = entity.info;
                        that.nowPointInfo =  Object.keys(that.nowPoint.properties).map(key => ({ key, value: that.nowPoint.properties[key] }));
                        that.nowPoint["type"] = "info";
                        // let xy = that.lonlatConvertToScreenXY(entity.info.coor)
                        let xy = that.lonlatConvertToScreenXY(center)
                        document.querySelector(".infoDialog").style.top = (xy.y - 230) + "px";
                        document.querySelector(".infoDialog").style.left = (xy.x - 100) + "px";
                    } else {
                        // console.log('未拾取到实体');
                    }
                }, SkyScenery.ScreenSpaceEventType.LEFT_CLICK);
                viewer.scene.postRender.addEventListener(that.updatePosition, this);
            } else {
                toRaw(this.mapHandle).destroy();
                this.mapHandle = null
                that.nowPointInfo = null
                viewer.scene.postRender.removeEventListener(that.updatePosition, this);
            }
        },
        // 经纬度转屏幕坐标
        lonlatConvertToScreenXY(lonlat) {
            // 定义经纬度
            var longitude = SkyScenery.Math.toRadians(lonlat[0]); // 例如：东经116.391度
            var latitude = SkyScenery.Math.toRadians(lonlat[1]); // 例如：北纬39.907度
            var height = 0; // 高度，通常在地表为0
            // 将经纬度转换为笛卡尔坐标
            // var cartographic = SkyScenery.Cartographic.fromDegrees(longitude, latitude, height);
            var cartesian = SkyScenery.Cartesian3.fromRadians(longitude, latitude, height, viewer.scene.globe.ellipsoid);
            // 将笛卡尔坐标转换为窗口坐标
            var canvasCoordinates = viewer.scene.cartesianToCanvasCoordinates(cartesian);
            return canvasCoordinates
        },
        // 位置更新
        updatePosition() {
            try {
                if (this.nowPoint != null) {
                    const obj = toRaw(this.nowPoint);
                    let xy = this.lonlatConvertToScreenXY(obj.coor)
                    if (!xy) {
                        document.querySelector(".infoDialog").style.top = "-9999px";
                        document.querySelector(".infoDialog").style.left = "-9999px";
                    } else {
                        document.querySelector(".infoDialog").style.top = (xy.y - 230) + "px";
                        document.querySelector(".infoDialog").style.left = (xy.x - 100) + "px";
                    }
                }
            } catch (error) {
                // debugger
            }
        },
        addWMTSLayer(param) {
            let matrixIds = [];
            for (let i = 0; i < 19; i++) {
                matrixIds[i] = i + 1;
            }
            // this.removeMapLayer();
            // console.log('[ WMTS ] >'+param)
            let layer = viewer.imageryLayers.addImageryProvider(
                new SkyScenery.WebMapTileServiceImageryProvider({
                    url: param.url,
                    layer: param.layers, // 固定的 cia  img  vec  cva 四种类型
                    style: "default",
                    format: "tiles",
                    // format:"image/png",
                    tileMatrixSetID: "w",
                    TileMatrixLabels: matrixIds,
                    subdomains: ["t0", "t1", "t2", "t3", "t4", "t5", "t6", "t7"],
                    minimumLevel: 1,
                    maximumLevel: 18,
                    tilingScheme: new SkyScenery.WebMercatorTilingScheme()
                })
            );
            this.wmslayer.mapItemLayer = layer;
        },
        addWMSLayer(param) {
            // console.log('[ WMS ] >'+param)
            let layer =  viewer.imageryLayers.addImageryProvider(
                new SkyScenery.WebMapServiceImageryProvider({
                    url: param.url,
                    layers: param.layers, //固定的已发布的类型
                    parameters: {
                        TRANSPARENT: true,
                        format: "image/png"
                    }
                })
            );
            this.wmslayer.mapItemLayer = layer;
        },
        addARCGISLayer(param){
            // console.log('[ ArcGisMapServer ] >'+param)
            // this.removeMapLayer();
            // 添加地图服务
            let layer =  viewer.imageryLayers.addImageryProvider(
                // 此处使用的地图服务地址也可存放在配置文件中
                new SkyScenery.ArcGisMapServerImageryProvider({
                    url: param.url
                })
            );
            this.wmslayer.mapItemLayer = layer;
        },
        removeMapLayer(){
            // console.log('[ eee ] >')
            if(this.wmslayer.mapItemLayer){
                viewer.imageryLayers.remove(toRaw(this.wmslayer.mapItemLayer))
                delete this.wmslayer.mapItemLayer;
            }
            
        },
        getVectorData(param){
            let that = this;
            fetch(param.url, {
                method: 'GET',
            }).then(response => response.json()) // 假设服务器返回 JSON 数据
                .then(data => {
                    console.log('[ eee ] >')
                    that.dataJson = data.result;
                    that.closeWin()
                    that.dwanMap()
                })
        },
        add3dtilesData(param){
            console.log('[ add3dtilesData ] >'+param)
            let tile1 = new SkyScenery.add3DTilesData(param.url, viewer)
            tile1.readyPromise.then(function (tileset) {
                viewer.zoomTo(tile1)
            });
        },
        changType(){
            let that = this;
            // this.inputAddress = '';
            if(that.typeValue == 1){
                let curUrl = 'http://121.43.55.7:8889/geoserver/kdyjs/wms';
                that.inputAddress = curUrl;
            }else if(that.typeValue == 2){
                let type = "vec"; //cia  img  vec  cva
                let curUrl = "https://{s}.tianditu.gov.cn/"+type+"_w/wmts?tk=f74e6c0cc247c42af05f7053e0b5fb9b";
                that.inputAddress = curUrl;
             
            }else if(that.typeValue == 3){
                let curUrl = 'https://service-api.onemap.sh.gov.cn/data-service-manage-service/MapProxyApi/eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhcHBsaWNhdGlvbl9pZCI6NjEsImFwcGxpY2F0aW9uX25hbWUiOiLpnZLmtabkuozkuInnu7TmnI3liqHns7vnu58iLCJleHAiOjIwNDY2Nzg0MDN9.IKUMdjUX4U1jncIUNren-iotL7duXI90aLECMjpvUX8/shmap_normal_web/MapServer';
                that.inputAddress = curUrl;
            }else if(that.typeValue == 4){
                let curUrl = "http://121.43.55.7:65456/shzx/tileset.json";
                that.inputAddress = curUrl;
            }else if(that.typeValue == 5){
                let curUrl = "http://121.43.55.7:10018/kdyjs/shop/recommend?type=1&size=20&banned=1,2,3";
                that.inputAddress = curUrl;
            }else if(that.typeValue == 6){
                that.inputAddress = "";
            }
        },
        parse(){
            let that = this;
            if( that.typeValue != 6 && that.inputAddress == ''){
                return ElMessage({
                    type: 'error',
                    message: `输入地址不能为空！请输入地址后进行解析`,
                })
            }
            console.log('[ eee ] >')
            //  typeValue:'1',
            // inputAddress:'',
            
            if(that.typeValue == 1){
                // let curUrl = that.inputAddress;
                let curUrl = 'http://121.43.55.7:8889/geoserver/kdyjs/wms';
                that.inputAddress = curUrl;
                let param = {url:curUrl,layers:'kdyjs:CourtyardFace'}
                that.addWMSLayer(param)

            }else if(that.typeValue == 2){
                let type = "vec"; //cia  img  vec  cva
                let curUrl = "https://{s}.tianditu.gov.cn/"+type+"_w/wmts?tk=f74e6c0cc247c42af05f7053e0b5fb9b";
                that.inputAddress = curUrl;
                let param = {url:curUrl,layers:type}
                that.addWMTSLayer(param)
             
            }else if(that.typeValue == 3){
                // let curUrl = that.inputAddress;
                let curUrl = 'https://service-api.onemap.sh.gov.cn/data-service-manage-service/MapProxyApi/eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhcHBsaWNhdGlvbl9pZCI6NjEsImFwcGxpY2F0aW9uX25hbWUiOiLpnZLmtabkuozkuInnu7TmnI3liqHns7vnu58iLCJleHAiOjIwNDY2Nzg0MDN9.IKUMdjUX4U1jncIUNren-iotL7duXI90aLECMjpvUX8/shmap_normal_web/MapServer';
                that.inputAddress = curUrl;
                let param = {url:curUrl,layers:'arcgisLayer'}
                that.addARCGISLayer(param)
            }else if(that.typeValue == 4){
                // let curUrl = that.inputAddress;
                let curUrl = "http://121.43.55.7:65456/shzx/tileset.json";
                that.inputAddress = curUrl;
                let param = {url:curUrl}
                that.add3dtilesData(param);
            }else if(that.typeValue == 5){
                // let curUrl = that.inputAddress;
                let curUrl = "https://kdyjs-proxy.metamaker.cn/proxy_map/static/json/%E6%A5%BC%E5%AE%87%E6%95%B0%E6%8D%AE-20250820.geojson";
                that.inputAddress = curUrl;
                let param = {url:curUrl}
                that.getVectorData(param);
            }else if(that.typeValue == 6){
                //上传GeoJson文件解析数据并上图
                if(this.mapHandle){
                    toRaw(this.mapHandle).destroy();
                    this.mapHandle = null
                    that.nowPointInfo = null
                }
                that.closeWin()
                that.dwanMap()
                
            }
            
        }
    },
    beforeDestroy() {
        viewer = undefined
    }
};
</script>
<style lang="less" scoped>

.container {
    width: 100%;
    padding: 0px;
    margin: 0 auto;
    overflow: hidden;
}
.infoDialog {
    position: absolute;
    top: 0px;
    left: 0px;
    max-width: 500px;
    height: 200px;
    // background: #01346f99;
    background: #ffffff;
    border-radius: 10px;

    .close {
      font-size: 24px;
      position: absolute;
      top: 6px;
      right: 8px;
      line-height: 24px;
      width: 24px;
      height: 24px;
      cursor: pointer;
      // color: #ffffff;
      color: #000000;
    }

    .content {
      height: 160px;
      // color: #ffffff;
      color: #000000;
      margin: 30px 0px 10px 20px;
      overflow: auto;
      .item {
        line-height: 30px;
        margin-right: 20px;
      }
    }
  }
</style>