/**
 * 船舶地图组件功能，通过调用封装好的基础地图组件实现特定业务功能
 */
import { fullExtent, clearMap, calculation, changeMap, setCamera,
    layerControl, layerQuery, addGraphic, draw, getDrawResult,
    addBoats, setBoatHistory, playBoatHistory, clearBoatHistory,
    openBoatDriving,closeBoatDriving,setAreaBoatHistory, playMultiBoatHistory,
    getMapScale,getMapExtent
} from '@/utils/map/ArcgisUtil'
import {GetHpjShip,GetBoatAISHistoryByMMSI,GetShipHistoryByArea,GetHpjShipWithWarn} from "@/apis/ship";
import {setCenter} from '@/utils/map/Common'
import {nextTick} from "vue";
import bus from "@/utils/bus";
import {GetLshbBoatPath} from "@/apis/ssky";

let boatInterval;
let showBoat = false;
let multiStartTime = null
let multiEndTime = null
let currentBoatMmsi = null

// 船舶定位
export function locationBoat(mmsi,isShow){
    console.log('船舶mmsi:'+mmsi)
    currentBoatMmsi = mmsi
    if(isShow){
            GetHpjShip().then(res=>{
                let data = res.Result.data
                let boats = {
                    "scale": 2000,
                    "goto": true,
                    "data": [],
                    "singleBoat":true
                }
                for(let i=0;i<data.length;i++){
                    if(data[i].DEVICEID == mmsi){
                        let boat = {
                            "mmsi": data[i].DEVICEID,
                            "shipNameCn": data[i].BOATNAME,
                            "shipTypeName": data[i].SHIPTYPENAME,
                            "direction": data[i].DIRECTION,
                            "velocity": data[i].VELOCITY,
                            "shipBreadth": data[i].SHIPBREADTH,
                            "shipLength": data[i].SHIPLENGTH,
                            "mapx": data[i].MAPX,
                            "mapy": data[i].MAPY
                        }
                        boats.data.push(boat)
                    }
                }
                // console.log('定位：'+JSON.stringify(boats))
                addBoats(boats)
            })

    }else{
        if (!showBoat){
            clearMap({is_draw: false, is_search:true, layers: ['boatLayer','boatPathLayer','boatGraphicLayer']})
        }else{
            clearMap({is_draw: false, is_search:true, layers: []})
        }
    }
}

// 船舶撒点
export function setBoat(isShow){
    if(isShow) {
        if (!showBoat){
            showBoat = true
        }else{
            return
        }

        onLocationBoat()
        if (boatInterval != null) {
            clearInterval(boatInterval)
        }
        boatInterval = setInterval(onLocationBoat, 5000)
    }else{
        if (showBoat){
            showBoat = false
        }
        if (boatInterval != null) {
            clearInterval(boatInterval)
        }
        clearMap({is_draw: false, is_search:true, layers: ['boatLayer','boatPathLayer','boatGraphicLayer']})
    }
}

// 加载船舶
export function onLocationBoat(){
    let extent = getMapExtent()
    GetHpjShipWithWarn({
        maxMapx:extent.xmax + 100,
        minMapx:extent.xmin - 100,
        maxMapy:extent.ymax + 100,
        minMapy:extent.ymin - 100,
        hour: 0.5
    }).then(res=>{
        if(!showBoat){
            return
        }
        let data = res.Result.data
        let boats = {
            "scale": getMapScale(),
            "goto": false,
            "data": [],
            "singleBoat":false
        }
        for(let i=0;i<data.length;i++){
            let boat = {
                "mmsi": data[i].DEVICEID,
                "shipNameCn": data[i].BOATNAME,
                "shipTypeName": data[i].SHIPTYPENAME,
                "direction": data[i].DIRECTION,
                "velocity": data[i].VELOCITY,
                "shipBreadth": data[i].SHIPBREADTH,
                "shipLength": data[i].SHIPLENGTH,
                "mapx": data[i].MAPX,
                "mapy": data[i].MAPY,
                "warnStatus": Object.keys(data[i].MAP).length == 0 ? 0: 1
            }
            boats.data.push(boat)
        }
        addBoats(boats)
    })
}

bus.on('playBoatPath', (params) => {
    nextTick(() => {
        setBoatPath(params)
    },{immediate: true});
})

// 设置船舶历史轨迹
export  function setBoatPath(data){
    currentBoatMmsi = data.mmsi
    GetBoatAISHistoryByMMSI({
        deviceId:data.mmsi,
        startTime:data.startTime,
        endTime:data.endTime
    }).then(res=>{
        let data = res.Result.data
        let historyPoints=[]
        for(let i=0;i<data.length;i++){
            let boat = {
                "mmsi": data[i].DEVICEID,
                "mapx": data[i].MAPX,
                "mapy": data[i].MAPY,
                "direction": data[i].DIRECTION,
                "shipTypeName": data[i].SHIPTYPENAME,
                "shipName": data[i].BOATNAME,
                "gpstime": data[i].GPSTIME
            }
            historyPoints.push(boat)
        }
        setBoatHistory(historyPoints)
        // setTimeout(function() {
        //     playBoatHistory('start')
        // }, 5000);

    })
}

/**
 * 船舶轨迹播放
 * 开始：start，
 * 暂停：pause，
 * 继续：resume，
 * 停止：stop
 * @param type
 */
bus.on('playBoatHistoryPath', (type) => {
    playBoatHistory(type)
    if(type == "stop"){
        clearBoatHistoryPath();
    }
    // 定位
    locationBoat(currentBoatMmsi,true)
})

/**
 * 清除船舶轨迹
 *
 * data 不为空表示清除单船
 */
export function clearBoatHistoryPath(data){
    console.log('清除船舶')
    if(data != null && showBoat == true){
        return
    }
    clearBoatHistory()
    clearMap({is_draw: true, is_search:true, layers: ['boatLayer','boatPathLayer','boatGraphicLayer']})
}

/***
 * 区域船舶轨迹回放 绘制区域并触发查询
 * @param startTime
 * @param endTime
 * @param isShow
 */
export function drawArea(startTime,endTime,isShow){
    if(isShow){
        multiStartTime = startTime
        multiEndTime = endTime
        draw('polygon',"setMultiBoatHistory");
    }else{
        clearBoatHistoryPath();
        playMultiBoatHistory('stop');
    }

}

export function setMultiBoatHistory(drawResult){
    GetShipHistoryByArea({
        "minMapx": drawResult.extent.xmin,
        "minMapy": drawResult.extent.ymin,
        "maxMapx": drawResult.extent.xmax,
        "maxMapy": drawResult.extent.ymax,
        "startTime": multiStartTime,
        "endTime": multiEndTime
    }).then(res => {
        if(res.code === "200"){
            if(res.data){
                if(res.data.Rows){
                    setAreaBoatHistory({
                        startTime: multiStartTime,
                        endTime: multiEndTime,
                        datas:res.data.Rows
                    })
                    playAreaBoatHistory('start')
                }
            }
        }
    })
}

/***
 * 多船轨迹回放
 * @param type
 */
export function playAreaBoatHistory(type){
    playMultiBoatHistory(type);
    if(type == "stop"){
        clearBoatHistoryPath();
    }
}

/**
 * 模拟驾驶
 * */
export function boatDriving(data,isShow){
    if(isShow){
        openBoatDriving(data)
    }else{
        closeBoatDriving()
        // clearMap({is_draw: false, is_search:true, layers: ['boatLayer','boatPathLayer','boatGraphicLayer']})
        // setCenter()
        locationBoat(data.mmsi,true)
    }
}

/**
 * 历史航班轨迹查询
 * data:{routeTypeId:1,mmsi:413863314,startTime:'2023-09-13 20:25:00'}
 */
// bus.on('djldBoatHistory',(data)=>{
export function djldBoatHistory(data,isShow) {
    if(isShow){
        GetLshbBoatPath(data).then(res => {
            let data = res.data.Rows
            let historyPoints = []
            for (let i = 0; i < data.length; i++) {
                let boat = {
                    "mmsi": data[i].mmsi,
                    "mapx": Number(data[i].mapx),
                    "mapy": Number(data[i].mapy),
                    "direction": data[i].direction,
                    "shipTypeName": data[i].shipTypeName,
                    "shipName": data[i].shipName,
                    "gpstime": data[i].gpsTime
                }
                historyPoints.push(boat)
            }
            setBoatHistory(historyPoints)
        })
    }else{
        clearBoatHistoryPath()
    }

}
// })
