<template>
    <div>
        <div class="map-out-container">
            <div class="map-inner-container">
                <Map 
                    :workPlanFormShow="workPlanFormShow" 
                    :editMode="editMode" 
                    :airLineForm="airLineForm" 
                    @exitDraw="exitDraw" @flyToThere="flyToThere" 
                    :wayline="wayline" 
                    :waylineInfo="waylineInfo"
                    :templateKmlConfig="templateKmlConfig"
                    :waylineWpmlConfig="waylineWpmlConfig"
                    ></Map>
            </div>
        </div>

        <!-- 航线库 -->
        <div v-if="ariLineShow" style="width:566px;position:absolute;top:30px;left:30px;z-index:1;height: calc( 100vh - 164px);overflow-y:hidden;">
            <airLineList :title="'航线管理'" @startEditAirLine="startEditAirLine" @setCurrentFolder="setCurrentFolder" @checkAriLine="checkAriLine" @previewAirLine="previewAirLine" @createAirLine="handlerCreateAirLine"></airLineList>
        </div>

        <!-- 新建航线 -->
        <div v-if="createAirLineShow" style="width:566px;position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);z-index:1;height: calc( 100vh - 164px);overflow-y:hidden;">
            <createAirLine :airLineForm="airLineForm" @createAirLine="handlerCreateAirLineForm"  :currentFolder="currentFolder"   @cancle="cancleCreateAirLine"></createAirLine>
        </div>

        <!-- 导入航线 -->
        <div v-if="importAirLineShow" style="width:566px;position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);z-index:1;height: calc( 100vh - 164px);overflow-y:hidden;">
            <importAirLine @createAirLine="handlerCreateAirLineForm" :currentFolder="currentFolder" @cancle="cancleImportAirLine"></importAirLine>
        </div>

    </div>
</template>
<script lang="ts" setup>
import {ref,watch,onMounted,defineEmits} from 'vue';
import airLineList from '../workplan/components/airLineList.vue';
import createAirLine from '../workplan/components/createAirLine.vue'
import importAirLine from '../workplan/components/importAirLine.vue'
import Map from '../workplan/components/map.vue'
import AirPolygon from './components/airPolygon.vue';
import {getAirLine} from '@/api/sys/workplan';

import JSZip from 'jszip';
import axios from 'axios';

import { XMLParser, XMLBuilder } from 'fast-xml-parser';

const emits = defineEmits(["updateAirLineLise"])

// 模式 add  edit  detail
const editMode = ref("add");

// airLine form
const airLineForm = ref({
    "id": null,
    "airLineName": null,
    "airLineType": null,
    "uavId": null,
    "flyToFirstPointMode": null,
    "safeTakeoffAltitude": 0,
    "safeTakeoffSpeed": 0,
    "globalRouteSpeed": 0,
    "taskCompletionAction": null,
    "outOfControlOption": null,
    "typeOfOutOfControlAction": null,
    "globalWayPointType": null,
    "ptzControlMode": null,
    "aircraftYawAngleMode": null,
    "createTime": null,
    "wpml": null,
    "taskOffLng": 0,
    "taskOffLat": 0,
    "folder": null,
    // "lineData":null,
}); 

// template.kml
const templateKmlConfig = ref({
    "author": 17861857725,
    "createTime": 1749689844431,
    "updateTime": 1753241338101,
    "missionConfig": {
      "flyToWaylineMode": "pointToPoint",
      "finishAction": "goHome",
      "exitOnRCLost": "goContinue",
      "executeRCLostAction": "goBack",
      "takeOffSecurityHeight": 20,
      "takeOffRefPoint": "",
      "takeOffRefPointAGLHeight": 4.169064385,
      "globalTransitionalSpeed": 15,
      "globalRTHHeight": 100,
      "droneInfo": {
        "droneEnumValue": 100,
        "droneSubEnumValue": 1
      },
      "autoRerouteInfo": {
        "transitionalAutoRerouteMode": 1,
        "missionAutoRerouteMode": 1
      },
      "waylineAvoidLimitAreaMode": 0,
      "payloadInfo": {
        "payloadEnumValue": 99,
        "payloadSubEnumValue": 0,
        "payloadPositionIndex": 0
      }
    },
    "Folder": {
      "templateType": "mapping2d",
      "templateId": 0,
      "waylineCoordinateSysParam": {
        "coordinateMode": "WGS84",
        "heightMode": "EGM96",
        "globalShootHeight": 90,
        "surfaceFollowModeEnable": 1,
        "isRealtimeSurfaceFollow": 0,
        "surfaceRelativeHeight": 90,
        "dsmFile": "wpmz/res/dsm/wgs84_ASTGTMV003_N35E118_dem_7.tif"
      },
      "autoFlightSpeed": 12.7,
      "Placemark": {
        "caliFlightEnable": 0,
        "elevationOptimizeEnable": 1,
        "smartObliqueEnable": 0,
        "quickOrthoMappingEnable": 0,
        "facadeWaylineEnable": 0,
        "isLookAtSceneSet": 0,
        "shootType": "time",
        "direction": 83,
        "margin": 0,
        "efficiencyFlightModeEnable": 0,
        "overlap": {
          "orthoCameraOverlapH": 80,
          "orthoCameraOverlapW": 70,
          "inclinedCameraOverlapH": 80,
          "inclinedCameraOverlapW": 70
        },
        "Polygon": {
          "outerBoundaryIs": {
            "LinearRing": {
              "coordinates": "118.293794766158,35.1353688096117,0\n                              118.295429169407,35.1353304409052,0\n                              118.295487507293,35.1332925168381,0\n                              118.293672196844,35.1331918267775,0"
            }
          }
        },
        "ellipsoidHeight": 90,
        "height": 90
      },
      "payloadParam": {
        "payloadPositionIndex": 0,
        "focusMode": "firstPoint",
        "meteringMode": "average",
        "returnMode": "singleReturnStrongest",
        "samplingRate": 240000,
        "scanningMode": "repetitive",
        "imageFormat": "visable",
        "photoSize": ""
      }
    }
  })

// wayline.wpml
const waylineWpmlConfig = ref({
      "missionConfig": {
        "flyToWaylineMode": "pointToPoint",
        "finishAction": "goHome",
        "exitOnRCLost": "goContinue",
        "executeRCLostAction": "goBack",
        "takeOffSecurityHeight": 20,
        "globalTransitionalSpeed": 15,
        "globalRTHHeight": 100,
        "droneInfo": {
          "droneEnumValue": 100,
          "droneSubEnumValue": 1
        },
        "autoRerouteInfo": {
          "transitionalAutoRerouteMode": 1,
          "missionAutoRerouteMode": 1
        },
        "waylineAvoidLimitAreaMode": 0,
        "payloadInfo": {
          "payloadEnumValue": 99,
          "payloadSubEnumValue": 0,
          "payloadPositionIndex": 0
        }
      },
      "Folder": {
        "templateId": 0,
        "executeHeightMode": "WGS84",
        "waylineId": 0,
        "distance": 1259.17163085938,
        "duration": 145.652896165848,
        "autoFlightSpeed": 12.7,
        "startActionGroup": {
          "action": [
            {
              "actionId": 0,
              "actionActuatorFunc": "gimbalRotate",
              "actionActuatorFuncParam": {
                "gimbalHeadingYawBase": "aircraft",
                "gimbalRotateMode": "absoluteAngle",
                "gimbalPitchRotateEnable": 1,
                "gimbalPitchRotateAngle": -90,
                "gimbalRollRotateEnable": 0,
                "gimbalRollRotateAngle": 0,
                "gimbalYawRotateEnable": 1,
                "gimbalYawRotateAngle": 0,
                "gimbalRotateTimeEnable": 0,
                "gimbalRotateTime": 10,
                "payloadPositionIndex": 0
              }
            },
            {
              "actionId": 1,
              "actionActuatorFunc": "hover",
              "actionActuatorFuncParam": {
                "hoverTime": 0.5
              }
            },
            {
              "actionId": 2,
              "actionActuatorFunc": "setFocusType",
              "actionActuatorFuncParam": {
                "cameraFocusType": "manual",
                "payloadPositionIndex": 0
              }
            },
            {
              "actionId": 3,
              "actionActuatorFunc": "focus",
              "actionActuatorFuncParam": {
                "focusX": 0,
                "focusY": 0,
                "focusRegionWidth": 0,
                "focusRegionHeight": 0,
                "isPointFocus": 0,
                "isInfiniteFocus": 1,
                "payloadPositionIndex": 0,
                "isCalibrationFocus": 0
              }
            },
            {
              "actionId": 4,
              "actionActuatorFunc": "hover",
              "actionActuatorFuncParam": {
                "hoverTime": 1
              }
            }
          ]
        },
        "Placemark": []
      }
    })

// 当前目录
const currentFolder = ref(null);

// 更新当前目录
const setCurrentFolder = (folder)=>{
    currentFolder.value = folder;
    importAirLineShow.value = true;
}


const flyToTherePosition = ref({
    lng:null,
    lat:null,
    alt:null,
})


const flyToThere = (e)=>{
    
}

const planListShow = ref(true);
const workPlanFormShow = ref(false);
const ariLineShow = ref(true);
const aircraftShow = ref(false);
const createAirLineShow = ref(false);
const importAirLineShow = ref(false);

const selectAriLine = ()=> {
    ariLineShow.value = true;
    aircraftShow.value = false;
}

const selectAircraft = ()=>{
    aircraftShow.value = true;
    ariLineShow.value = false;
}

const cancleCraete = ()=>{
    workPlanFormShow.value = false;
    ariLineShow.value = false;
    aircraftShow.value = false;
    planListShow.value = true;
}

const checkedAriLine = ref({});

const checkAriLine = (item)=>{
    if(item){
        ariLineShow.value = false;
        checkedAriLine.value = item;
    }
}

const checkedDronePort = ref({});

const checkDronePort = (item)=>{
    if(item){
        aircraftShow.value = false;
        checkedDronePort.value = item;
    }
}

const formData = ref(null);

const toCreateWorkPlan = (data)=> {
    formData.value = data;
    planListShow.value = false;
    workPlanFormShow.value = true;
}

// 创建航线
const globalFolder = ref(null);
const handlerCreateAirLine = (folder)=>{
    globalFolder.value = folder;
    createAirLineShow.value = true;
}

const cancleCreateAirLine = ()=>{
    createAirLineShow.value = false;
}

const cancleImportAirLine = ()=>{
    emits("updateAirLineLise");
    importAirLineShow.value = false;
}

const handlerCreateAirLineForm = (form)=>{

    // 关闭全部窗口
    workPlanFormShow.value = false;
    ariLineShow.value = false;
    aircraftShow.value = false;
    planListShow.value = false;
    createAirLineShow.value = false;
    
    // 航线表单
    airLineForm.value = form
    airLineForm.value.folder = globalFolder.value;

    console.log("airLineFor121m",airLineForm.value);

}

const successCreatePlan = ()=>{
    workPlanFormShow.value = false;
    ariLineShow.value = false;
    aircraftShow.value = false;
    planListShow.value = true;
}

// 保存航线后退出
const exitDraw = ()=>{
    planListShow.value = false;
    workPlanFormShow.value = true;
    ariLineShow.value = true;
    editMode.value = 'add'
}




// 预览航线
const wayline = ref({});
const waylineInfo = ref(null)
const previewAirLine =async (line,type) => {
    let info =await getAirLine({airLineId:type.value?.id});
    if(info){
        wayline.value = line;
        waylineInfo.value = info;
    }
}

// 查看航线详情
const planDetail =async (item) => {
    formData.value = item;
    console.log("formData",formData.value?.airLineId);

    let info =await getAirLine({airLineId : formData.value?.airLineId});
    if(info){
        // wayline.value = line;
        waylineInfo.value = info;
        wayline.value = await airLineDetail(info);
    }

    workPlanFormShow.value =  true;
}


// 获取wpml文件

const currentPreviewWayLine = ref(null);

const airLineDetail =async (item) => {

    currentPreviewWayLine.value = item;

    try{
        let response  =  await axios.get(item.wpml,{responseType: 'arraybuffer'});
        // 解压kmz文件
        let xmlStr =await extractKmz(response.data);
        let xmlData = xmlStr.replace(/wpml:/g,"");
        const parser = new XMLParser();
        const jsonObj = parser.parse(xmlData);
        return jsonObj.kml.Document;
        
    }catch(e){
        console.error(e);
    }

    
}

// 解压航线文件
const extractKmz = async (kmzBlob)=>{

    const zip = new JSZip();

    const contents = await zip.loadAsync(kmzBlob);
    
    // 查找.wmpl文件
    for (const [filename, file] of Object.entries(contents.files)) {
        if (filename.toLowerCase().endsWith('.wpml')) {
            return await file.async('text');
        }
    }
    
    throw new Error('KMZ文件中未找到WMPL文件');
}

onMounted(()=>{

let element = window.document.getElementsByClassName("mars3d-locationbar")[0]  as HTMLElement;
element.style.bottom = '40px';

})


// 编辑航线
const startEditAirLine = (data,form,type) => {

    // 航线文件template.kml配置信息
    templateKmlConfig.value = data.template.kml.Document

    // 航线wayline.wpml配置信息
    waylineWpmlConfig.value = data.wayline.kml.Document;

    // 航线表信息
    waylineInfo.value = form;

    // 航线表单
    airLineForm.value = form;

    // 设置模式为编辑模式
    editMode.value = type;

    // 关闭全部窗口

    workPlanFormShow.value = false;
    ariLineShow.value = false;
    aircraftShow.value = false;
    planListShow.value = false;
    createAirLineShow.value = false;


}

</script>
<style scoped>
.map-out-container{
    width: 100%;
    height: calc( 100vh - 80px);
    overflow: hidden;
}

.map-inner-container{
    width: calc( 100% + 80px);
    height: calc( 100% + 80px);
    position: relative;
    top:-40px;
    left:-40px;
}
</style>