<template>
    <div class="containner">

        <div class="title">
            <LeftOutlined @click="backPage" />
            <div style="flex:1;">
                <a-input v-model:value="props.airLineForm.airLineName"  size="middle" placeholder="航线名称" />
            </div>
            <!-- <div>面状航线</div> -->
            <SaveOutlined @click="saveAirLine" style="font-size:20px;" />

           
        </div>

        <!-- 数据统计 -->
        <div class="area-info">
            <div class="item">
                <div>测区面积</div>
                <div>{{props.airInfo.area}} m²</div>
            </div>
            <div class="bar"></div>
            <div class="item">
                <div>航线长度</div>
                <div>{{props.airInfo.length}} km</div>
            </div>
            <div class="bar"></div>
            <div class="item">
                <div>预计用时</div>
                <div>{{props.airInfo.time}} mins</div>
            </div>
            <div class="bar"></div>
            <div class="item">
                <div>照片数量</div>
                <div>{{props.airInfo.picture}} </div>
            </div>
            
        </div>
        
        <!-- 航线配置 -->
        <div class="area-options" >

            <div class="item">
                <div class="label">选择机场
                    <br/>
                    <span style="font-size:12px;color:#ccc;"> {{props.templateKmlConfig?.missionConfig.takeOffRefPoint}} </span>
                </div>
                <div class="content">
                    <a-button type="link" style="color:#408eff" @click="setTakeOffPoint()">
                        <img src="./start-fly.png" style="width:24px;height:24px;position:relative;left:-2px;top:-2px;" alt="">
                        选择机场
                    </a-button>
                </div>
            </div>
            
            <div class="item">
                <div class="label">GSD(地面采样距离)
                    <a-tooltip placement="topLeft">
                        <template #title>
                            <div class="tooltip-text">
                                <p>GSD（Ground Sample Distance）指的是地面采样距离。在无人机测绘中，GSD是指像素大小，即每个像素代表的实际距离。GSD越小，图像分辨率越高，但数据量也会增加。调整GSD将影响航线高度等参数。</p>
                            </div>
                        </template>
                        <InfoCircleOutlined />
                      </a-tooltip>
                </div>
                <div class="content">
                    <a-input type="number" style="width:100px;" placeholder="" v-model:value="calculatParam.gsd" @change="onGsdChange"></a-input>
                </div>
                <div class="unit"> cm/pixel</div>
            </div>

            <div class="item flex-column">
                <div class="label">高度模式
                    <a-tooltip placement="topLeft" >
                        <template #title>

                            <div class="tooltip-text">
                                <p>海拔高度：航点高度值相对于海平面高度保持不变。</p>

                                <p>相对起飞点高度（ALT）：航点高度值相对起飞点的高度保持不变。</p>

                                <p>相对地形高度（AGL）：航点高度值相对仿地文件管理中的模型文件保持不变</p>
                            </div>

                        </template>
                        <InfoCircleOutlined />
                    </a-tooltip>
                </div>
                <div class="content">
                    <div class="radio-box">
                        <div v-for="(item,index) in folderConfigOptions.executeHeightMode" :key="index"
                            :class="heightMode == item.value ? 'radio-item-active':'radio-item'" 
                            @click="heightMode = item.value;handlerHeightMode();"
                            >
                            {{item.label}}
                        </div>
                    </div>
                </div>
                <div class="description">
                    <img src="/map/executeHeightMode.png" alt="">
                </div>
            </div>

            <div class="item">
                <div class="label">航线高度</div>
                <div class="content">
                    <!--  -->
                    <a-input type="number" style="width:100px;" placeholder="" v-model:value="calculatParam.height" @change="onHeightChange"></a-input>
                </div>
                <div class="unit"> m</div>
            </div>

            <div class="item">
                <div class="label">航向重叠率</div>
                <div class="content">
                    <!--  -->
                    <a-input type="number" style="width:100px;" placeholder="" v-model:value="calculatParam.overlapX"></a-input>
                </div>
                <div class="unit"> % </div>
            </div>

            <div class="item">
                <div class="label">旁向重叠率</div>
                <div class="content">
                    <!--  -->
                    <a-input type="number" style="width:100px;" placeholder="" v-model:value="calculatParam.overlapY" @change="onOverlayYChange"></a-input>
                </div>
                <div class="unit"> %</div>
            </div>


            <!-- <div class="item">
                <div class="label">航线间距</div>
                <div class="content">
                    <a-input style="width:100px;" placeholder="" v-model:value="calculatParam.spacing" disabled></a-input>
                </div>
                <div class="unit"> m</div>
            </div> -->

            <div class="item">
                <div class="label">主航线角度</div>
                <div class="content">
                    <!-- calculatParam.overlapAngle -->
                    <a-input type="number" style="width:100px;" placeholder="" v-model:value="calculatParam.overlapAngle"></a-input>
                </div>
                <div class="unit"> °</div>
            </div>


            <div class="item flex-column">
                <div class="label">
                    飞向首航点模式
                    <a-tooltip placement="topLeft" >
                        <template #title>
                            <p> 垂直爬升：飞行器爬升到航线起始点高度后，再飞向航线起始点。</p>
                            <p>倾斜爬升：飞行器爬升到"安全起飞高度"后，再直线飞到航线起始点。</p>
                            <p>安全起飞高度：是相对起飞点的高度值。</p>
                        </template>
                        <InfoCircleOutlined />
                    </a-tooltip>
                </div>
                <div class="content">
                    <div class="radio-box">
                        <div v-for="(item,index) in missionConfigOptions.flyToWaylineMode" :key="index"
                            :class=" props.templateKmlConfig?.missionConfig.flyToWaylineMode == item.value ? 'radio-item-active':'radio-item'" 
                            @click="props.templateKmlConfig.missionConfig.flyToWaylineMode = item.value;handlerFlyToWaylineMode();"
                            >
                            {{item.label}}
                        </div>
                    </div>
                </div>
                <div class="description">
                    <img src="/map/flyToWaylineMode.png" alt="">
                </div>
            </div>

            <div class="item">
                <div class="label">安全起飞高度</div>
                <div class="content">
                    <a-input  type="number" style="width:100px;"  placeholder="" v-model:value="props.templateKmlConfig.missionConfig.takeOffSecurityHeight"></a-input>
                </div>
                <div class="unit"> m </div>
            </div>

            <div class="item">
                <div class="label">全局航线过渡速度</div>
                <div class="content">
                    <a-input type="number" style="width:100px;" placeholder="" v-model:value="props.templateKmlConfig.missionConfig.globalTransitionalSpeed"></a-input>
                </div>
                <div class="unit"> m/s </div>
            </div>

            <div class="item">
                <div class="label">全局返航高度</div>
                <div class="content">
                    <a-input type="number"  style="width:100px;" placeholder="" v-model:value="props.templateKmlConfig.missionConfig.globalRTHHeight"></a-input>
                </div>
                <div class="unit"> m</div>
            </div>

            <div class="item">
                <div class="label">全局航线飞行速度</div>
                <div class="content">
                    <a-input  type="number"  style="width:100px;" placeholder="" v-model:value="props.templateKmlConfig.Folder.autoFlightSpeed"></a-input>
                </div>
                <div class="unit"> m/s</div>
            </div>


            <div class="item">
                <div class="label">拍照模式</div>
                <div class="content">
                    <a-select
                        ref="select"
                        style="width:162px;"
                        v-model:value="props.templateKmlConfig.Folder.Placemark.shootType"
                        @change="handlerShootType"
                    >
                        <a-select-option value="time">等时间间隔拍照</a-select-option>
                        <a-select-option value="distance">等距离间隔拍照</a-select-option>
                    </a-select>
                </div>
            </div>

            <!-- <div class="item">
                <div class="label">航线起始点</div>
                <div class="content">
                    <a-button type="link" style="color:#408eff" @click="setTakeOffPoint()">
                        选择起飞点
                    </a-button>
                </div>
            </div> -->

            <div class="item">
                <div class="label">自定义限飞区绕行</div>
                <div class="content">
                    <a-switch v-model:checked="waylineAvoidLimitAreaMode"  @change="handlerWaylineAvoidLimitAreaMode"  />
                </div>
            </div>

            <div class="item">
                <div class="label">航线绕行</div>
                <div class="content">
                    <a-switch v-model:checked="bypass" @change="handlerByPass" />
                </div>
            </div>
        </div>
    </div>
</template>
<script lang="ts" setup>
import {ref,defineEmits,defineProps,watch} from 'vue'
import { SaveOutlined,LeftOutlined,InfoCircleOutlined } from '@ant-design/icons-vue';
import {missionConfigOptions,folderConfigOptions}  from '../waylineConfig/index.ts';
import {uploadXmlFile,addAirLine,editAirLine} from '@/api/sys/workplan';
import { message } from 'ant-design-vue';
import { XMLParser, XMLBuilder } from 'fast-xml-parser';
import JSZip from "jszip";
import { saveAs } from "file-saver"; 
import {templateStr} from '../waylineConfig/template'
// 航线计算
import {uavModel,calculateHeight,calculateGsd,calculateSpacing,calculateInterval} from '../lib/calculateAirLine'


const emits = defineEmits(["setTakeOffPoint","exitDraw","calculatParamChange"])


const props = defineProps({
    "airInfo":{
        type:Object
    },
    "polygonAirForm":{
        type:Object
    },
    "airPoints":{
        type:Object
    },
    "airLineForm":{
        type:Object
    },
    "waylineInfo":{
        type:Object
    },
    "editModel":{
        type:String,
        default:"add"
    },
    "templateKmlConfig":{
        type:Object
    },
    "waylineWpmlConfig":{
        type:Object
    },
    "polygon":{
        type:Object
    }
})


const airInfo = ref({
    area:0.0,
    length:0.0,
    time:'4m 11s',
    picture:23
})

const setTakeOffPoint = ()=>{
    emits("setTakeOffPoint");
}

// 航线计算参数
const calculatParam = ref({
    gsd:2,
    overlapY:70,
    overlapX:80,
    overlapAngle:0,
    height:0,
    spacing:0,
    safeyFlyHeight:20,
})


/////////////////////////////////////////监听航线计算数据变化/////////////////////////////////////////

watch(
    () => calculatParam.value,
    (newVal,oldVal) => {
        emits("calculatParamChange",newVal)
    },
    {deep:true}
)


// 判断创建和编辑模式设置高度
if(props.editModel == 'edit'){

    calculatParam.value.gsd = calculateGsd(props.templateKmlConfig.Folder.Placemark.height,uavModel['m4td']);

    calculatParam.value.overlapAngle = props.templateKmlConfig.Folder.Placemark.direction;
}

// 根据gsd 计算 航线高度
calculatParam.value.height = calculateHeight(calculatParam.value.gsd,uavModel['m4td']);

// 根据旁向重叠率就计算航线间距
calculatParam.value.spacing =  calculateSpacing(calculatParam.value.gsd,calculatParam.value.overlapY/100,uavModel['m4td'])



// 监听gsd改变
const onGsdChange = ()=>{
    calculatParam.value.height = calculateHeight(calculatParam.value.gsd,uavModel['m4td']);
    onOverlayYChange();
}

// 监听飞行高度改变
const onHeightChange = () => {
    calculatParam.value.gsd = calculateGsd(calculatParam.value.height,uavModel['m4td']);
    onOverlayYChange();
}

// 监听旁像重叠率
const onOverlayYChange = ()=>{
    calculatParam.value.spacing =  calculateSpacing(calculatParam.value.gsd,calculatParam.value.overlapY/100,uavModel['m4td'])
}

// 航线基本配置
const missionConfig = ref(
    {
        "flyToWaylineMode": "safely",            // 爬升模式  safely  pointToPoint
        "finishAction": "goHome",                // 航线结束动作 
        "exitOnRCLost": "executeLostAction",     // 失控是否继续执行航线
        "executeRCLostAction": "goBack",         // 失控动作类型
        "takeOffSecurityHeight": 20,             // 安全起飞高度
        "globalTransitionalSpeed": 15,           // 全局航线过渡速度
        "globalRTHHeight": 100,                  // 全局返航高度
        "droneInfo": {                           // 飞行器机型信息
            "droneEnumValue": 100,
            "droneSubEnumValue": 1
        },
        "autoRerouteInfo": {                     // 航线绕行
            "transitionalAutoRerouteMode": 1,
            "missionAutoRerouteMode": 1
        },
        "waylineAvoidLimitAreaMode": 0,
        "payloadInfo": {                         // 负载机型信息
            "payloadEnumValue": 99,              // 负载机型主类型
            "payloadSubEnumValue": 2,
            "payloadPositionIndex": 0            // 负载挂载位置
        }
    }
)

// 判断是否编辑
if(props.waylineInfo){
    missionConfig.value = props.waylineInfo.missionConfig
}

watch(
    () => missionConfig.value,
    (newVal,oldVal) => {
        calculatParam.value.safeyFlyHeight = missionConfig.value.takeOffSecurityHeight;
    },
    {deep:true}
)

// 航点基本配置
const folder = ref({
    "templateId": 0,
    "executeHeightMode": "WGS84",
    "waylineId": 0,
    "distance": 1391.755859375,
    "duration": 200.941531419754,
    "autoFlightSpeed": 8.2,                          // 全局航线飞行速度
    "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:[]
})

// 是否编辑
if(props.waylineInfo){
    folder.value = props.waylineInfo.Folder
}

// 航点详细信息
const pointInfo =  {
    "Point": {
        "coordinates": "118.295430406842,35.1352868743403"      // 坐标
    },
    "index": 0,                                                 // 序号
    "executeHeight": 167,                                       // 高度
    "waypointSpeed": 12.7125370218057,                          // 飞行速度
    "waypointHeadingParam": {                                   // 飞行器参数
        "waypointHeadingMode": "followWayline",                 // 偏航角模式  和航线角度一致         
        "waypointHeadingAngle": -96.9990577342362,                 
        "waypointPoiPoint": "0.000000,0.000000,0.000000",
        "waypointHeadingAngleEnable": 1,
        "waypointHeadingPathMode": "followBadArc",
        "waypointHeadingPoiIndex": 0
    },
    "waypointTurnParam": {
        "waypointTurnMode": "toPointAndStopWithDiscontinuityCurvature",
        "waypointTurnDampingDist": 0
    },
    "useStraightLine": 1,
    "actionGroup": [
        {
            "#text": "z",
            "actionGroupId": 0,
            "actionGroupStartIndex": 0,
            "actionGroupEndIndex": 13,
            "actionGroupMode": "sequence",
            "actionTrigger": {
                "actionTriggerType": "betweenAdjacentPoints"
            },
            "action": [
                {
                    "actionId": 0,
                    "actionActuatorFunc": "gimbalAngleLock"
                },
                {
                    "actionId": 1,
                    "actionActuatorFunc": "gimbalRotate",
                    "actionActuatorFuncParam": {
                        "gimbalHeadingYawBase": "aircraft",
                        "gimbalRotateMode": "absoluteAngle",
                        "gimbalPitchRotateEnable": 1,
                        "gimbalPitchRotateAngle": -90,
                        "gimbalRollRotateEnable": 0,
                        "gimbalRollRotateAngle": 0,
                        "gimbalYawRotateEnable": 0,
                        "gimbalYawRotateAngle": 0,
                        "gimbalRotateTimeEnable": 0,
                        "gimbalRotateTime": 10,
                        "payloadPositionIndex": 0
                    }
                },
                {
                    "actionId": 2,
                    "actionActuatorFunc": "startTimeLapse",
                    "actionActuatorFuncParam": {
                        "payloadPositionIndex": 0,
                        "useGlobalPayloadLensIndex": 0,
                        "payloadLensIndex": "visable",
                        "minShootInterval": 1.52472746372223
                    }
                }
            ]
        },
        {
            "actionGroupId": 1,
            "actionGroupStartIndex": 0,
            "actionGroupEndIndex": 13,
            "actionGroupMode": "sequence",
            "actionTrigger": {
                "actionTriggerType": "multipleTiming",
                "actionTriggerParam": 2
            },
            "action": {
                "actionId": 0,
                "actionActuatorFunc": "gimbalRotate",
                "actionActuatorFuncParam": {
                "gimbalHeadingYawBase": "aircraft",
                "gimbalRotateMode": "absoluteAngle",
                "gimbalPitchRotateEnable": 1,
                "gimbalPitchRotateAngle": -90,
                "gimbalRollRotateEnable": 0,
                "gimbalRollRotateAngle": 0,
                "gimbalYawRotateEnable": 0,
                "gimbalYawRotateAngle": 0,
                "gimbalRotateTimeEnable": 0,
                "gimbalRotateTime": 10,
                "payloadPositionIndex": 0
                }
            }
        }
    ],
    "waypointGimbalHeadingParam": {
        "waypointGimbalPitchAngle": 0,
        "waypointGimbalYawAngle": 0
    },
    "isRisky": 0,
    "waypointWorkType": 0
}

// 处理航点数据
const handlerPointInfo = ()=>{

    if(props.airPoints?.length<=0){
        message.warning("请绘制航测区域！");
        return null;
    }

    let placemarkArray = [];

    props.airPoints?.forEach((item,index)=>{
        let point = {
            "Point": {
                "coordinates": item.lng+","+item.lat    // 坐标
            },
            "index": index,                                                  // 序号
            "executeHeight": item.alt,                                       // 高度
            "waypointSpeed": 12.7125370218057,                              // 航点速度
            "waypointHeadingParam": {                                   // 飞行器参数
                "waypointHeadingMode": "followWayline",                 // 偏航角模式  和航线角度一致         
                "waypointHeadingAngle": -96.9990577342362,                 
                "waypointPoiPoint": "0.000000,0.000000,0.000000",
                "waypointHeadingAngleEnable": 1,
                "waypointHeadingPathMode": "followBadArc",
                "waypointHeadingPoiIndex": 0
            },
            "waypointTurnParam": {
                "waypointTurnMode": "toPointAndStopWithDiscontinuityCurvature",
                "waypointTurnDampingDist": 0
            },
            "useStraightLine": 1,
            "actionGroup": [
                {
                    "#text": "z",
                    "actionGroupId": 0,
                    "actionGroupStartIndex": 0,
                    "actionGroupEndIndex": 13,
                    "actionGroupMode": "sequence",
                    "actionTrigger": {
                        "actionTriggerType": "betweenAdjacentPoints"
                    },
                    "action": [
                        {
                            "actionId": 0,
                            "actionActuatorFunc": "gimbalAngleLock"
                        },
                        {
                            "actionId": 1,
                            "actionActuatorFunc": "gimbalRotate",
                            "actionActuatorFuncParam": {
                                "gimbalHeadingYawBase": "aircraft",
                                "gimbalRotateMode": "absoluteAngle",
                                "gimbalPitchRotateEnable": 1,
                                "gimbalPitchRotateAngle": -90,
                                "gimbalRollRotateEnable": 0,
                                "gimbalRollRotateAngle": 0,
                                "gimbalYawRotateEnable": 0,
                                "gimbalYawRotateAngle": 0,
                                "gimbalRotateTimeEnable": 0,
                                "gimbalRotateTime": 10,
                                "payloadPositionIndex": 0
                            }
                        },
                        {
                            "actionId": 2,
                            "actionActuatorFunc": "startTimeLapse",
                            "actionActuatorFuncParam": {
                                "payloadPositionIndex": 0,
                                "useGlobalPayloadLensIndex": 0,
                                "payloadLensIndex": "visable",
                                "minShootInterval": 1.52472746372223
                            }
                        }
                    ]
                },
                {
                    "actionGroupId": 1,
                    "actionGroupStartIndex": 0,
                    "actionGroupEndIndex": 13,
                    "actionGroupMode": "sequence",
                    "actionTrigger": {
                        "actionTriggerType": "multipleTiming",
                        "actionTriggerParam": 2
                    },
                    "action": {
                        "actionId": 0,
                        "actionActuatorFunc": "gimbalRotate",
                        "actionActuatorFuncParam": {
                        "gimbalHeadingYawBase": "aircraft",
                        "gimbalRotateMode": "absoluteAngle",
                        "gimbalPitchRotateEnable": 1,
                        "gimbalPitchRotateAngle": -90,
                        "gimbalRollRotateEnable": 0,
                        "gimbalRollRotateAngle": 0,
                        "gimbalYawRotateEnable": 0,
                        "gimbalYawRotateAngle": 0,
                        "gimbalRotateTimeEnable": 0,
                        "gimbalRotateTime": 10,
                        "payloadPositionIndex": 0
                        }
                    }
                }
            ],
            "waypointGimbalHeadingParam": {
                "waypointGimbalPitchAngle": 0,
                "waypointGimbalYawAngle": 0
            },
            "isRisky": 0,
            "waypointWorkType": 0
        }
        placemarkArray.push(point);
    });
    props.waylineWpmlConfig.Folder.Placemark = placemarkArray;
    // folder.value.Placemark = placemarkArray;

    return true;
}

// waylines.json 数据
const waylinesJson = ref(
    {
    "kml": {
            "Document": {
                "missionConfig":missionConfig.value,
                "Folder":folder.value
            }
        }
    }
)

// 保存航线
const saveAirLine = ()=>{

    // 处理template.json
    handlerTemplateKml();

    // 处理航点
    handlerWaylineWpml();

    let handlerResult =  handlerPointInfo();




    if(handlerResult){
        // 将template中的 missionConfig 赋值 给wayline
        props.waylineWpmlConfig.missionConfig = props.templateKmlConfig.missionConfig

        const builder = new XMLBuilder();

        // 带wpml前缀的 template json数据
        let templateJson = {kml:{Document:props.templateKmlConfig}}
        let templateWpmlJson = handlerPrefixWpml(templateJson);
        let templateXmlStr = builder.build(templateWpmlJson);
        let templateXmlStrTemp = templateXmlStr.replace(/<\/?\d+>/g, "")
        let templateXml = templateXmlStrTemp.replace("<kml>",`<?xml version="1.0" encoding="UTF-8"?><kml xmlns="http://www.opengis.net/kml/2.2" xmlns:wpml="http://www.dji.com/wpmz/1.0.6">`)

        // 带wpml前缀的 wayline json数据
        let waylineJosn = {kml:{Document:props.waylineWpmlConfig}}
        let waylienWpmlJson = handlerPrefixWpml(waylineJosn);
        let waylineXmlStr = builder.build(waylienWpmlJson);
        let waylineXmlStrTemp = waylineXmlStr.replace(/<\/?\d+>/g, "")
        let waylineXml = waylineXmlStrTemp.replace("<kml>",`<?xml version="1.0" encoding="UTF-8"?><kml xmlns="http://www.opengis.net/kml/2.2" xmlns:wpml="http://www.dji.com/wpmz/1.0.6">`)
       
        // 创建压缩文件
        handlerCreateFile(templateXml,waylineXml);
    }

}

// 处理wpml:前缀 
const handlerPrefixWpml = (obj) => {

  for (const key in obj) {

    
    if (typeof obj[key] === 'object' && obj[key] !== null && !Array.isArray(obj[key])) {    // 如果是对象

        handlerPrefixWpml(obj[key]); // 递归处理嵌套对象

        const newAttrs = {};

        for (const attrName in obj[key]) {
            // 检查属性名是否首字母小写
            if (/^[a-z]/.test(attrName)) {
                newAttrs[`wpml:${attrName}`] = obj[key][attrName];
            } else {
                newAttrs[attrName] = obj[key][attrName];
            }
        }

        obj[key] = newAttrs;

    }else if(typeof obj[key] === 'object' && obj[key] !== null && Array.isArray(obj[key])){      // 如果是数组
        console.log("数组："+obj[key]);
    
        handlerPrefixWpml(obj[key]); // 递归处理嵌套对象

        const newAttrs = [];

        for (const attrName in obj[key]) {
            // 检查属性名是否首字母小写
            if (/^[a-z]/.test(attrName)) {
                newAttrs[`wpml:${attrName}`] = obj[key][attrName];
            } else {
                newAttrs[attrName] = obj[key][attrName];
            }
        }

        obj[key] = newAttrs;
    }
  }
  return obj;
}


// 生成xml文件，创建航线
const handlerCreateFile =async (templateXml,waylineXml)=>{

    const blob =await convertXmlToKmz(templateXml,waylineXml);

    // 创建FormData对象用于上传
    const formData = new FormData();

    formData.append('xmlFile', blob,"面状航线.kmz");

    let res = await uploadXmlFile("默认文件夹/面状航线",formData);

    if(res){
        props.airLineForm.wpml = res.path;
        // props.airLineForm.lineData =  {type:2}

        let addAirLineRes = null;

        if(props.editModel == 'add'){

            addAirLineRes =await addAirLine(props.airLineForm);

        }else if(props.editModel == 'edit'){

             addAirLineRes =await editAirLine(props.airLineForm);

        }

        if(addAirLineRes){
            message.success("操作成功！");
            backPage();
        }else{
            message.error("操作失败！");
        }
    }else{
        message.error("操作失败！");
    }
}

// xml文本转换为wpml和kml文件
const convertXmlToKmz =async (templateXml,waylineXml)=>{

    const zip = new JSZip();

    // 1. 创建 "wmpz" 文件夹
    const wmpzFolder = zip.folder("wpmz");

    // 2. 向文件夹中添加文件
    wmpzFolder.file("wayline.wpml", waylineXml);
    wmpzFolder.file("template.kml", templateXml);

    // 3. 生成 KMZ (ZIP) 文件
    const kmzBlob = await zip.generateAsync({ type: "blob" });

    // 下载航线文件
    // saveAs(kmzBlob, "output.kmz");

    return kmzBlob;
}

// 退出绘制
const backPage = ()=>{
    emits("exitDraw")
}

///////////////////////////////////////////////处理配置模式///////////////////////////////
// 处理创建时间 编辑时间
const handlerCreateOrUpdateTime = () => {

    let date = new Date();

    if(props.editModel == 'add'){
        props.templateKmlConfig.createTime = date.getTime();
        props.templateKmlConfig.updateTime = date.getTime();
    }else if(props.editModel == 'edit'){
        props.templateKmlConfig.updateTime = date.getTime();
    }

}

// 航线高度设置
const handlerAirLineHeight = () => {
    
    // 设置高度
    props.templateKmlConfig.Folder.Placemark.height = calculatParam.value.height;
    props.templateKmlConfig.Folder.Placemark.ellipsoidHeight = calculatParam.value.height;
    // props.templateKmlConfig.missionConfig.waylineCoordinateSysParam?.surfaceRelativeHeight = calculatParam.value.height;

    // 重叠率
    props.templateKmlConfig.Folder.Placemark.overlap.orthoCameraOverlapH = calculatParam.value.overlapX;
    props.templateKmlConfig.Folder.Placemark.overlap.orthoCameraOverlapW = calculatParam.value.overlapY;

    // 航线角度
    props.templateKmlConfig.Folder.Placemark.direction = calculatParam.value.overlapAngle

}
// 处理测绘区域
const handlerPolygon = () => {
    let polygonStr = ``;
    for(let i=0;i<props.polygon.length-1;i++){
        console.log(props.polygon[i]);
        polygonStr = polygonStr + `
        ${props.polygon[i][0]},${props.polygon[i][1]},${props.polygon[i][2]}`
    }
    props.templateKmlConfig.Folder.Placemark.Polygon.outerBoundaryIs.LinearRing.coordinates = polygonStr;
}

// 处理高度模式
const heightMode = ref("relativeToStartPoint");
const handlerHeightMode = () => {

    switch(heightMode.value){

        case "EGM96":    // 海拔高度
            props.templateKmlConfig.Folder.waylineCoordinateSysParam = {
                "coordinateMode": "WGS84",
                "heightMode": "EGM96",
                "globalShootHeight": 90
            };
            break;

        case "relativeToStartPoint": // 相对起飞点模式
            props.templateKmlConfig.Folder.waylineCoordinateSysParam = {
                "coordinateMode": "WGS84",
                "heightMode": "relativeToStartPoint",
                "globalShootHeight": 90
            };
            break;

        case "realTimeFollowSurface": //  相对地形模式
            props.templateKmlConfig.Folder.waylineCoordinateSysParam = {
                "coordinateMode": "WGS84",
                "heightMode": "EGM96",
                "globalShootHeight": 90,
                "surfaceFollowModeEnable": 1,
                "isRealtimeSurfaceFollow": 0,   // 预加载地形文件
                "surfaceRelativeHeight": 90,
                "dsmFile": "wpmz/res/dsm/wgs84_ASTGTMV003_N35E118_dem_7.tif"
            };
            break;
    }

}

handlerHeightMode();

// 获取地形数据
const getDEMData = () => {

}

// 处理飞行到首航点模式
const handlerFlyToWaylineMode = ()=>{

    // 更新航线
    console.log(props.templateKmlConfig.missionConfig.flyToWaylineMode)
}

// 限飞区
const waylineAvoidLimitAreaMode = ref(false);
const handlerWaylineAvoidLimitAreaMode = (e) => {
    if(e){
        props.templateKmlConfig.missionConfig.waylineAvoidLimitAreaMode = 1;
    }else{
        props.templateKmlConfig.missionConfig.waylineAvoidLimitAreaMode = 0;
    }
}

// 处理绕行
const bypass = ref(true);
const handlerByPass = (e) => {
    if(e){
        props.templateKmlConfig.missionConfig.autoRerouteInfo.transitionalAutoRerouteMode = 1;
        props.templateKmlConfig.missionConfig.autoRerouteInfo.missionAutoRerouteMode = 1;
    }else{
        props.templateKmlConfig.missionConfig.autoRerouteInfo.transitionalAutoRerouteMode = 0;
        props.templateKmlConfig.missionConfig.autoRerouteInfo.missionAutoRerouteMode = 0;
    }
}

// 处理拍照模式
const handlerShootType = (e) => {
    console.log(e);
}

/////////////////////////////////////////航点数据处理/////////////////////////////////////

// 处理生成template.json
const handlerTemplateKml = () => {

    // 处理时间和日期
    handlerCreateOrUpdateTime();

    // 计算数据处理
    handlerAirLineHeight();

    // 测绘区域处理
    handlerPolygon();
}

// 处理生成wayline.json
const handlerWaylineWpml = () => {

    // 处理基础配置
    props.waylineWpmlConfig.missionConfig = props.templateKmlConfig.missionConfig;

    // 处理统计数据
    handlerStatistics();

    // 处理航点
    handelrAirPoint();

}

// 航线计算数据处理
const handlerStatistics = () => {

    props.waylineWpmlConfig.Folder.distance = props.airInfo.length;
    props.waylineWpmlConfig.Folder.duration = props.airInfo.time;

}

// 处理航线数据
const handelrAirPoint = () => {

    // alert(props.templateKmlConfig.Folder.autoFlightSpeed);

    props.airPoints.forEach((item,index)=>{
        let point = null;

        // 根据高度模式 设置高度
        let height = 0;

        // 计算间隔时间
        let spaceTime = (calculateInterval(calculatParam.value.gsd,calculatParam.value.overlapX/100,uavModel['m4td']) / props.templateKmlConfig.Folder.autoFlightSpeed)


        // 处理第1个航点
        if(index == 0){
            point = {
                "Point": {
                    "coordinates":item.lng+","+item.lat 
                },
                "index": item.id,
                "executeHeight": item.alt,
                "waypointSpeed": props.templateKmlConfig.Folder.autoFlightSpeed,
                "waypointHeadingParam": {
                    "waypointHeadingMode": "followWayline",
                    "waypointHeadingAngle": -96.9990577342362,
                    "waypointPoiPoint": "0.000000,0.000000,0.000000",
                    "waypointHeadingAngleEnable": 1,
                    "waypointHeadingPathMode": "followBadArc",
                    "waypointHeadingPoiIndex": 0
                },
                "waypointTurnParam": {
                    "waypointTurnMode": "toPointAndStopWithDiscontinuityCurvature",
                    "waypointTurnDampingDist": 0
                },
                "useStraightLine": 1,
                "actionGroup": [
                    {
                        "actionGroupId": 0,
                        "actionGroupStartIndex": item.id,
                        "actionGroupEndIndex": props.airPoints.length - 3,
                        "actionGroupMode": "sequence",
                        "actionTrigger": {
                            "actionTriggerType": "betweenAdjacentPoints"
                        },
                        "action": [
                            {
                                "actionId": 0,
                                "actionActuatorFunc": "gimbalAngleLock"
                            },
                            {
                                "actionId": 1,
                                "actionActuatorFunc": "gimbalRotate",
                                "actionActuatorFuncParam": {
                                "gimbalHeadingYawBase": "aircraft",
                                "gimbalRotateMode": "absoluteAngle",
                                "gimbalPitchRotateEnable": 1,
                                "gimbalPitchRotateAngle": -90,
                                "gimbalRollRotateEnable": 0,
                                "gimbalRollRotateAngle": 0,
                                "gimbalYawRotateEnable": 0,
                                "gimbalYawRotateAngle": 0,
                                "gimbalRotateTimeEnable": 0,
                                "gimbalRotateTime": 10,
                                "payloadPositionIndex": 0
                                }
                            },
                            {
                                "actionId": 2,
                                "actionActuatorFunc": "startTimeLapse",
                                "actionActuatorFuncParam": {
                                "payloadPositionIndex": 0,
                                "useGlobalPayloadLensIndex": 0,
                                "payloadLensIndex": "visable",
                                "minShootInterval":spaceTime
                                }
                            }
                        ]
                    },
                    {
                        "actionGroupId": 1,
                        "actionGroupStartIndex": item.id,
                        "actionGroupEndIndex": props.airPoints.length - 3,
                        "actionGroupMode": "sequence",
                        "actionTrigger": {
                            "actionTriggerType": "multipleTiming",
                            "actionTriggerParam": 2
                        },
                        "action": {
                        "actionId": 0,
                        "actionActuatorFunc": "gimbalRotate",
                        "actionActuatorFuncParam": {
                            "gimbalHeadingYawBase": "aircraft",
                            "gimbalRotateMode": "absoluteAngle",
                            "gimbalPitchRotateEnable": 1,
                            "gimbalPitchRotateAngle": -90,
                            "gimbalRollRotateEnable": 0,
                            "gimbalRollRotateAngle": 0,
                            "gimbalYawRotateEnable": 0,
                            "gimbalYawRotateAngle": 0,
                            "gimbalRotateTimeEnable": 0,
                            "gimbalRotateTime": 10,
                            "payloadPositionIndex": 0
                        }
                        }
                    }
                ],
                "waypointGimbalHeadingParam": {
                    "waypointGimbalPitchAngle": 0,
                    "waypointGimbalYawAngle": 0
                },
                "isRisky": 0,
                "waypointWorkType": 0
            }
        }else if(index == props.airPoints.length -1){ // 处理最后1个航点
            point = {
                "Point": {
                    "coordinates":item.lng+","+item.lat 
                },
                "index": item.id,
                "executeHeight": item.alt,
                "waypointSpeed": props.templateKmlConfig.Folder.autoFlightSpeed,
                "waypointHeadingParam": {
                    "waypointHeadingMode": "followWayline",
                    "waypointHeadingAngle": 0,
                    "waypointPoiPoint": "0.000000,0.000000,0.000000",
                    "waypointHeadingAngleEnable": 0,
                    "waypointHeadingPathMode": "followBadArc",
                    "waypointHeadingPoiIndex": 0
                }, 
                "waypointTurnParam": {
                    "waypointTurnMode": "toPointAndStopWithDiscontinuityCurvature",
                    "waypointTurnDampingDist": 0
                },
                "useStraightLine": 1,
                "actionGroup": {
                    "actionGroupId": 6,
                    "actionGroupStartIndex": item.id,
                    "actionGroupEndIndex": item.id,
                    "actionGroupMode": "sequence",
                    "actionTrigger": {
                        "actionTriggerType": "reachPoint"
                    },
                    "action": [
                        {
                            "actionId": 0,
                            "actionActuatorFunc": "stopTimeLapse",
                            "actionActuatorFuncParam": {
                                "payloadPositionIndex": 0,
                                "payloadLensIndex": "visable"
                            }
                        },
                        {
                            "actionId": 1,
                            "actionActuatorFunc": "gimbalAngleUnlock"
                        }
                    ]
                },
                "waypointGimbalHeadingParam": {
                "waypointGimbalPitchAngle": 0,
                "waypointGimbalYawAngle": 0
                },
                "isRisky": 0,
                "waypointWorkType": 0
            }
        }else if(index == props.airPoints.length -2){ // 处理倒数第2个航点
            point = {
                "Point": {
                    "coordinates":item.lng+","+item.lat 
                },
                "index": item.id,
                "executeHeight": item.alt,
                "waypointSpeed": props.templateKmlConfig.Folder.autoFlightSpeed,
                "waypointHeadingParam": {
                    "waypointHeadingMode": "followWayline",
                    "waypointHeadingAngle": -44.6751949389683,
                    "waypointPoiPoint": "0.000000,0.000000,0.000000",
                    "waypointHeadingAngleEnable": 1,
                    "waypointHeadingPathMode": "followBadArc",
                    "waypointHeadingPoiIndex": 0
                },
                "waypointTurnParam": {
                    "waypointTurnMode": "toPointAndStopWithDiscontinuityCurvature",
                    "waypointTurnDampingDist": 0
                },
                "useStraightLine": 1,
                "actionGroup": [
                    {
                        "actionGroupId": 3,
                        "actionGroupStartIndex": item.id,
                        "actionGroupEndIndex": item.id,
                        "actionGroupMode": "sequence",
                        "actionTrigger": {
                        "actionTriggerType": "reachPoint"
                        },
                        "action": [
                            {
                                "actionId": 0,
                                "actionActuatorFunc": "gimbalRotate",
                                "actionActuatorFuncParam": {
                                "gimbalHeadingYawBase": "aircraft",
                                "gimbalRotateMode": "absoluteAngle",
                                "gimbalPitchRotateEnable": 1,
                                "gimbalPitchRotateAngle": -45,
                                "gimbalRollRotateEnable": 0,
                                "gimbalRollRotateAngle": 0,
                                "gimbalYawRotateEnable": 1,
                                "gimbalYawRotateAngle": 0,
                                "gimbalRotateTimeEnable": 0,
                                "gimbalRotateTime": 10,
                                "payloadPositionIndex": 0
                                }
                            },
                            {
                                "actionId": 1,
                                "actionActuatorFunc": "hover",
                                "actionActuatorFuncParam": {
                                "hoverTime": 0.5
                                }
                            }
                        ]
                    },
                    {
                        "actionGroupId": 4,
                        "actionGroupStartIndex": item.id,
                        "actionGroupEndIndex": item.id+1,
                        "actionGroupMode": "sequence",
                        "actionTrigger": {
                            "actionTriggerType": "betweenAdjacentPoints"
                        },
                        "action": [
                            {
                                "actionId": 0,
                                "actionActuatorFunc": "gimbalAngleLock"
                            },
                            {
                                "actionId": 1,
                                "actionActuatorFunc": "gimbalRotate",
                                "actionActuatorFuncParam": {
                                "gimbalHeadingYawBase": "aircraft",
                                "gimbalRotateMode": "absoluteAngle",
                                "gimbalPitchRotateEnable": 1,
                                "gimbalPitchRotateAngle": -45,
                                "gimbalRollRotateEnable": 0,
                                "gimbalRollRotateAngle": 0,
                                "gimbalYawRotateEnable": 0,
                                "gimbalYawRotateAngle": 0,
                                "gimbalRotateTimeEnable": 0,
                                "gimbalRotateTime": 10,
                                "payloadPositionIndex": 0
                                }
                            },
                            {
                                "actionId": 2,
                                "actionActuatorFunc": "startTimeLapse",
                                "actionActuatorFuncParam": {
                                "payloadPositionIndex": 0,
                                "useGlobalPayloadLensIndex": 0,
                                "payloadLensIndex": "visable",
                                "minShootInterval": spaceTime
                                }
                            }
                        ]
                    },
                    {
                        "actionGroupId": 5,
                        "actionGroupStartIndex": item.id,
                        "actionGroupEndIndex": item.id+1,
                        "actionGroupMode": "sequence",
                        "actionTrigger": {
                        "actionTriggerType": "multipleTiming",
                            "actionTriggerParam": 2
                        },
                        "action": {
                            "actionId": 0,
                            "actionActuatorFunc": "gimbalRotate",
                            "actionActuatorFuncParam": {
                                "gimbalHeadingYawBase": "aircraft",
                                "gimbalRotateMode": "absoluteAngle",
                                "gimbalPitchRotateEnable": 1,
                                "gimbalPitchRotateAngle": -45,
                                "gimbalRollRotateEnable": 0,
                                "gimbalRollRotateAngle": 0,
                                "gimbalYawRotateEnable": 0,
                                "gimbalYawRotateAngle": 0,
                                "gimbalRotateTimeEnable": 0,
                                "gimbalRotateTime": 10,
                                "payloadPositionIndex": 0
                            }
                        }
                    }
                ],
                "waypointGimbalHeadingParam": {
                    "waypointGimbalPitchAngle": 0,
                    "waypointGimbalYawAngle": 0
                },
                "isRisky": 0,
                "waypointWorkType": 0
            }
        }else{ // 处理中间航点
            point = {
                "Point": {
                    "coordinates":item.lng+","+item.lat 
                },
                "index": item.id,
                "executeHeight": item.alt,
                "waypointSpeed": props.templateKmlConfig.Folder.autoFlightSpeed,
                "waypointHeadingParam": {
                    "waypointHeadingMode": "followWayline",
                    "waypointHeadingAngle": -96.9993404112147,
                    "waypointPoiPoint": "0.000000,0.000000,0.000000",
                    "waypointHeadingAngleEnable": 1,
                    "waypointHeadingPathMode": "followBadArc",
                    "waypointHeadingPoiIndex": 0
                },
                "waypointTurnParam": {
                    "waypointTurnMode": "coordinateTurn",
                    "waypointTurnDampingDist": 10
                },
                "useStraightLine": 1,
                "waypointGimbalHeadingParam": {
                    "waypointGimbalPitchAngle": 0,
                    "waypointGimbalYawAngle": 0
                },
                "isRisky": 0,
                "waypointWorkType": 0
            }
        }

        props.waylineWpmlConfig.Folder.Placemark.push(point);
    })

    console.log(" props.waylineWpmlConfig", props.waylineWpmlConfig);
}

</script>

<style scoped>
.container{
    width:100%;
    height:100%;
    color:#fff;
}

.title{
    padding:20px;
    font-size:16px;
    color:#ffffff;
    display:flex;
    gap:12px;
    line-height:24px;
}

.area-info{
    width:100%;
    border-top:1px solid rgba(255,255,255,0.2);
    border-bottom:1px solid rgba(255,255,255,0.2);
    display:flex;
    padding:20px 0px;
}
.area-info .item{
    flex:1;
    color:#fff;
    text-align: center;
    display:flex;
    gap:12px;
    flex-direction: column;
}

.area-options{
    width:100%;
    height: calc( 100vh - 260px);
    padding:10px;
    overflow-y:auto;
    line-height:32px;
}

.area-options .item{
    padding:10px;
    margin:15px 0px;
    background:#232323;
    color:#fff;
    display:flex;
    border-radius:3px;
}
.area-options .item .label{
    flex:1;
}
.area-options .item .content{
    cursor:pointer;
}

.flex-column{
    flex-direction: column;
    gap:10px;
}


.radio-box{
    width:100%;
    display: flex;
    overflow: hidden;
    border:0.5px solid #3B4154 ;
    background:#050608;
    font-size:13px;
    border-radius: 19px;
    height:38px;
    line-height:38px;
}

.description{
    text-align: center;
}

.description img{
}

.radio-box .radio-item{
    flex:1;
    color:#8A92A6 ;
    text-align: center;
    cursor:pointer;

}

.radio-box .radio-item-active{
    flex:1;
    color:#fff;
    text-align: center;
    background:#3A57E8 ;
    border-radius: 19px;
    cursor:pointer;
}

.area-options .item .unit{
    min-width: 60px;
    text-align:center;

}


::v-deep .ant-radio-group {
    display: block;
    width: 100%;
}



::v-deep .ant-select-selector{
    border:none!important;
    color:#fff!important;
    background:#3c3c3c!important;
    border-radius: 3px!important;
}


::v-deep .ant-select-selection-placeholder {
    color:rgba(255, 255, 255, 0.533)!important;
  }
::v-deep .ant-select-arrow {
    color:rgba(255, 255, 255, 0.533)!important;
  }
::v-deep .ant-select-selection-search-input::placeholder{
    color:rgba(255, 255, 255, 0.933)!important;
}


::v-deep .ant-tree {
    background:none!important;
    color:#fff!important;
}

::v-deep .ant-tree-treenode-selected{
    background:#3a57e877!important;
}

::v-deep .ant-tree-treenode-selected::before{
    background:none!important;
}

::v-deep .ant-tree-treenode-selected::after{
    content:"";
    height:28px;
    width:4px;
    background:#3A57E8;
    position:absolute;
    top:0px;
    left:0px;
}

::v-deep .ant-input{
    background:#3c3c3c!important ;
    border:none!important;
    border-top-left-radius: 3px !important;
    border-bottom-left-radius: 3px !important;
    color:#fff!important;
}

::v-deep .ant-input::placeholder{
    color:rgba(255, 255, 255, 0.533)!important;
}


::v-deep .ant-btn-default{
    background:none!important;
    border:none!important;
    outline:none!important;
    color:#fff!important;
    height:30px !important;
    background:#3F4150!important ;
}

.tooltip-text{
    font-size:12px;
}
</style>