//加载地图控件
import CityGis from "@/utils/map/CityGis.Bridge";
import { ElMessage } from 'element-plus'
import 'element-plus/es/components/message/style/css'
import {onLocationBoat} from '@/utils/map/Boat'
import {refreshDepthPoints} from '@/utils/map/Layer'
import bus from '@/utils/bus';
import {setMultiBoatHistory} from '@/utils/map/Boat'

let bridge
let calculateFinish = false
// let drawGeometry = null
let drawResult = null
let showBoat = false
let showDepthPoints = false
let mapExtent
let mapScale
let clickGraphic

export function initBridge(){
    bridge = new CityGis.Bridge({
        id: "i_map",
        url: "http://10.83.68.108:8090/mapVue/#/map", //4.23版本政务网
        // url: "http://10.83.68.108:8090/mapWidgetVue/#/map", //4.26版本政务网
        // url: "http://localhost:8081/#/map", //政务网
        onReady: function(){
            console.log("地图创建完成");
        }
    });

    bridge.addEventListener((arg) => {
        switch (arg.action) {
            case "MapIsReady":
                break;
            case "MapExtentChanged":
                console.log(arg)
                mapExtent = arg.data.extent
                mapScale = arg.data.scale
                if(showBoat){
                    onLocationBoat()
                }
                if(showDepthPoints){
                    refreshDepthPoints()
                }
                break;
            case "MapClickObject":
                clickGraphic = arg.data.graphic
                // 点击船舶则打开船舶面板
                if(clickGraphic.attributes.mmsi){
                    bus.emit('ueRec_BoatClick',{'mmsi':clickGraphic.attributes.mmsi})
                }

                break
            default:
                console.log(JSON.stringify(arg.data, null, 4))
        }
    });
}

// 获取地图范围
export function getMapExtent() {
    return mapExtent
}

// 获取地图比例尺
export function getMapScale() {
    return mapScale
}

/*切换底图
* 基础地图：baseMap
* 遥感地图：airMap
*/
export function changeMap(type){
    let params = {
        "ActionName": "ChangeBaseMap",
        "Parameters": {
            "title": type,
            "opacity": 1
        }
    };
    bridge.Invoke(params);
}

/**
 * 设置透明度
 * 参数 opacity 范围 0-1，0全透明，1不透明
 */
export function setOpacity(opacity){
    let params = {
        "ActionName": "SetOpacity",
        "Parameters": {
            "opacity": opacity
        }
    };
    bridge.Invoke(params);
}


/**
 * 添加图层
 * @param data 地图参数
 * @param isShow 显隐控制 true 显示，false 隐藏
 */
export function addLayer(data){
    let params = {
        "ActionName": "AddLayer",
        "Parameters": {
            "id": data.id,
            "title": data.title,
            "visible": data.visible,
            "opacity": data.opacity,
            // "url": "http://10.83.68.109:6080/arcgis/rest/services/ghjg_cxall/MapServer",
            "url": data.url,
            "type": data.type,
            "token": data.token,
            // "is_goto": data.is_goto,
            "elevationInfo": data.elevationInfo
        }
    };
    bridge.Invoke(params);
}

/* 定位船舶 */
/*参数格式：
[
    {
        "mmsi": "413266820",
        "shipNameCn": "苏州号",
        "shipTypeName": "客船",
        "direction": 245,
        "velocity": 0,
        "shipBreadth": 22,
        "shipLength": 154,
        "mapx": 2755.61767,
        "mapy": 1521.00687
    }
]*/
export function addBoats(boats){
    let params = {
        "ActionName": "AddBoat",
        "Parameters": {
            "scale": boats.scale,
            "goto": boats.goto,
            "data": boats.data,
            "singleBoat": boats.singleBoat
        }
    };
    // console.log('定位：'+JSON.stringify(params))
    bridge.Invoke(params);
}

/* 绘制船舶轨迹 */
/*参数格式：
[
    {
        "mapx": 2755.61767,
        "mapy": 1521.00687,
        "time": "2021/1/18 9:40:53"
    },
    {
        "mapx": 2705.61767,
        "mapy": 1481.00687,
        "time": "2021/1/18 10:07:19"
    }
]*/
export function setBoatHistory(datas){
    let params = {
        "ActionName": "SetBoatHistory",
        "Parameters": {
            "data":datas
        }
    };
    bridge.Invoke(params);
}

/* 绘制多船轨迹 */
/*参数格式：
datas:[
[
    {
        "mmsi": 123456789,
        "mapx": 2755.61767,
        "mapy": 1521.00687,
        "direction": 0,
        "gpsTime": "2021/1/18 9:40:53"
    },
    {
        "mmsi": 123456789,
        "mapx": 2705.61767,
        "mapy": 1481.00687,
        "direction": 0,
        "gpsTime": "2021/1/18 10:07:19"
    }
    ],[
{
        "mmsi": 123456790,
        "mapx": 2755.61767,
        "mapy": 1521.00687,
        "direction": 0,
        "gpsTime": "2021/1/18 9:40:53"
    },
    {
        "mmsi": 123456790,
        "mapx": 2705.61767,
        "mapy": 1481.00687,
        "direction": 0,
        "gpsTime": "2021/1/18 10:07:19"
    }
    ]
]*/
export function setAreaBoatHistory(param){
    let params = {
        "ActionName": "SetAreaBoatHistory",
        "Parameters": {
            "startTime": param.startTime,
            "endTime": param.endTime,
            "data":param.datas
        }
    };
    bridge.Invoke(params);
}

/**
 * 开始：start，
 * 暂停：pause，
 * 继续：resume，
 * 停止：stop
 * @param type
 */
export function playBoatHistory(type){
    let params = {
        "ActionName": "PlayBoatHistory",
        "Parameters": {
            "status": type
        }
    };
    bridge.Invoke(params);
}

/**
 * 开始：start，
 * 暂停：pause，
 * 继续：resume，
 * 停止：stop
 * @param type
 */
export function playMultiBoatHistory(type){
    let params = {
        "ActionName": "PlayMultiBoatHistory",
        "Parameters": {
            "status": type
        }
    };
    bridge.Invoke(params);
    bridge.addEventListener((arg) => {
        switch (arg.action) {
            case "MapIsReady":
                break;
        }
    });
}

/**
 * 清除船舶轨迹
 * @constructor
 */
export function clearBoatHistory(){
    let params = {
        "ActionName": "ClearBoatHistory",
        "Parameters": {}
    };
    bridge.Invoke(params);
}

/*查询服务*/
/*参数格式：
{
    "ActionName": "LayerQuery",
    "Parameters": {
        "title": "ghjg_cxall",
        "layerid": "0",
        "where": "视频点名称='华江石油码头'",
        "outFields": [
            "*"
        ],
        "returnGeometry": true,
        "is_draw": true,
        "symbol": {
            "type": "simple-marker",
            "style": "circle",
            "color": [
                255,
                0,
                0
            ],
            "size": 10
        }
    }
}*/
export function layerQuery(paramData){
    let params = {
        "ActionName": "LayerQuery",
        "Parameters": {
            "title": paramData.title,
            "layerid": paramData.layerId,
            "where": paramData.where,
            "outFields": [
                "*"
            ],
            "returnGeometry": true,
            "is_draw": paramData.is_draw == null?true:paramData.is_draw,
            "is_clear": paramData.is_clear == null?true:paramData.is_clear,
            "symbol": paramData.symbol
        }
    };
    console.log("params",params)
    bridge.Invoke(params);
    bridge.addEventListener((arg) => {
        if(arg.action == "ReturnDataList"){
            console.log(arg)
            if(arg.status == false){
                this.$message({
                    showClose: true,
                    message: "未查询到结果！",
                    type: "warning"
                })
                return
            }
            // 回调函数
            if(paramData.callback == 'pjylPortHandle'){
                this.pjylPortHandle(arg)
            }else if(paramData.callback == 'djldPortHandle'){
                this.djldPortHandle(arg)
            }
        }
    });
}
/*重置*/
export function resetMap(){
    let params = {
        "ActionName": "ResetMap"
    };
    bridge.Invoke(params);
}

/*全景*/
export function fullExtent(){
    let params = {
        "ActionName": "FullExtent"
    };
    bridge.Invoke(params);
}

/*测距/测面积*/
/*测距：distance   测面积：area*/
export function calculation(type){
    let g_type
    calculateFinish = false
    if(type == "distance"){
        g_type = "polyline"
    }
    if(type == "area"){
        g_type = "polygon"
    }

    let params = {
        "ActionName": "Calculation",
        "Parameters": {
            "type": g_type,
            "is_show": false
        }
    };
    bridge.Invoke(params);
    bridge.addEventListener((arg) => {
        if(arg.action == "Calculation" && calculateFinish == false){
            calculateFinish = true
            ElMessage.warning("测量结果：" + arg.data.result)
        }
    });
}

/*图层开关*/
export function layerControl(data){
    if(data == "" || data == null){
        return
    }
    this.mapClickLayers = []
    if(data.visible == true){
        // this.mapClickLayers = data.sublayers
        let sublayers = data.sublayers.split(",")
        for(let i=0;i<sublayers.length;i++){
            this.mapClickLayers.push(sublayers[i])
        }
    }
    let params = {
        "ActionName": "LayerControl",
        "Parameters": {
            "title": data.title,
            "visible": data.visible,
            "opacity": data.opacity,
            "sublayers": data.sublayers  // 倒序
        }
    };
    bridge.Invoke(params);
}

/*绘制点线面*/
/*参数说明：
    point 点；
    polyline 线；
    polygon 面；*/
export function draw(type,isBack){
    let params = {
        "ActionName": "Draw",
        "Parameters": {
            "type": type
        }
    };
    bridge.Invoke(params);
    bridge.addEventListener((arg) => {
        if(arg.action == "DrawComplete"){
            drawResult = arg.data
            // drawGeometry = arg.data.geometry
            if(isBack == 'setMultiBoatHistory'){
                setMultiBoatHistory(drawResult)
            }
        }
    });
}

// 标记图形
export function addGraphic(datas){
    console.log("addGraphic:",datas)
    let params = {
        "ActionName": "AddGraphic",
        "Parameters": {
            "type": datas.type,
            "is_edit": datas.edit,
            "is_clear": datas.clear,
            "is_temp": datas.temp,
            "is_goto": datas.goto,
            "data": datas.data,
            "attributes": datas.attributes,
            "symbol": datas.symbol,
            "textSymbol": datas.textSymbol,
            "title": datas.title
        }
    };
    bridge.Invoke(params);
}

// 设置摄像机
export function setCamera(data){
    let params = {
        "ActionName": "SetCamera",
        "Parameters": {
            "position": {
                "x": data.x,
                "y": data.y,
                "z": data.z,
                "spatialReference": 102100
            },
            "heading": data.heading,
            "tilt": data.tilt,
        }
    };
    bridge.Invoke(params);
}

/**
 * 清空地图
 * 下面是支持的图层，可多选
 * layers:['sketchLayer','bufferLayer','tempLayer','boatLayer','boatPathLayer','boatGraphicLayer']
 * is_draw 对应图形绘制
 * is_search 对应点查询和图形标记
 * */
export function clearMap(data){
    let params = {
        "ActionName": "ClearMap",
        "Parameters": {
            "is_draw": data.is_draw,
            "is_search": data.is_search,
            // "is_position": data.is_position,
            "layers": data.layers
        }
    };
    bridge.Invoke(params);
}

export function getDrawResult(){
    return drawResult
}

/**
 * 开启船舶模拟
 * */
export function openBoatDriving(data){
    let params = {
        "ActionName": "AddBoatDriving",
        "Parameters": {
            "mmsi": data.mmsi,
            "shipName": data.shipName,
            "shipTypeName": data.shipTypeName,
            "direction": data.direction,
            "mapx": data.mapx,
            "mapy": data.mapy
        }
    };
    bridge.Invoke(params);
}

/**
 * 关闭船舶模拟
 * */
export function closeBoatDriving(data){
    let params = {
        "ActionName": "CloseBoatDriving",
        "Parameters": {}
    };
    bridge.Invoke(params);
}

export function setShowDepthPointsState(data){
    showDepthPoints = data
}
