<template>
    <div class="containner">
        <div class="title">
            <LeftOutlined @click="backPage" />
            <div>航点航线</div>
            <SaveOutlined @click="saveAirLine"/>

            <a-button type="primary" size="middle" @click="areaOptionsShow = !areaOptionsShow">
                航线设置
                <ControlOutlined />
            </a-button>

            <div style="flex:1;">
                <a-input  size="middle" v-model:value="submitForm.airLineName" placeholder="航线名称" />
            </div>
            
        </div>

         <!-- 航线信息 -->
         <div class="area-info">
            <div class="item">
                <div>航点数量</div>
                <div>{{ props.airPoints.length }}</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="air-point-list">
            
            <div class="air-point-item">
                <!-- <div class="cel">经度</div>
                <div class="cel">纬度</div> -->
                <div class="cel">航点</div>
                <div class="cel">高度</div>
                <div class="cel">偏航角</div>
                <div class="cel">水平角</div>
                <div class="cel">俯仰角</div>
                <div class="cel">照片</div>
            </div>

            <div class="air-point-item" v-for="(item,index) in props.airPoints" :key="index">
                <!-- <div class="cel">{{item.lng}}</div>
                <div class="cel">{{item.lat}}</div> -->
                <div class="cel" @click="checkPoint(item)">
                    <img src="/map/air-point.png" width="18" alt="">
                    {{index+1}}
                </div>
                <div class="cel">{{item.alt}}</div>
                <div class="cel">{{item.aircraftHorizontalAngle}}</div>
                <div class="cel">{{item.cameraHorizontalAngle}}</div>
                <div class="cel">{{item.cameraVerticalAngle}}</div>
                <div class="cel">{{item.focalLength}}</div>
            </div>
        </div>
       
        <!-- 航线配置 -->
        <div class="area-options" v-if="areaOptionsShow">

            <div class="item">
                <div class="label">参考起飞点</div>
                <div class="content">
                    <a-button type="link" style="color:#408eff" @click="setFlyPoint()">
                        <img src="./start-fly.png" style="width:24px;height:24px;position:relative;left:-2px;top:-2px;" alt="">
                        设置起飞点
                    </a-button>
                </div>
            </div>

            

            <div class="item flex-column">
                <div class="label">飞向首航点模式</div>
                <div class="content">
                    <div class="radio-box">
                        <div v-for="(item,index) in missionConfigOptions.flyToWaylineMode" :key="index"
                            :class=" missionConfig.flyToWaylineMode == item.value ? 'radio-item-active':'radio-item'" 
                            @click="missionConfig.flyToWaylineMode = item.value"
                            >
                            {{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 style="width:100px;"  placeholder="" v-model:value="missionConfig.takeOffSecurityHeight"></a-input>
                </div>
                <div class="unit"> m</div>
            </div>

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

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


            <div class="item flex-column">
                <div class="label">航线结束动作</div>
                <div class="content">
                    <div class="radio-box">
                        <div v-for="(item,index) in missionConfigOptions.finishAction" :key="index"
                            :class=" missionConfig.finishAction == item.value ? 'radio-item-active':'radio-item'" 
                            @click="missionConfig.finishAction = item.value"
                            >
                            {{item.label}}
                        </div>
                    </div>
                </div>
            </div>

            <div class="item flex-column">
                <div class="label">失控是否继续执行航线</div>
                <div class="content">
                    <div class="radio-box">
                        <div v-for="(item,index) in missionConfigOptions.exitOnRCLost" :key="index"
                            :class=" missionConfig.exitOnRCLost == item.value ? 'radio-item-active':'radio-item'" 
                            @click="missionConfig.exitOnRCLost = item.value"
                            >
                            {{item.label}}
                        </div>
                    </div>
                </div>
            </div>

            <div class="item flex-column" v-if="missionConfig.exitOnRCLost == 'executeLostAction'">
                <div class="label">失控动作类型</div>
                <div class="content">
                    <div class="radio-box">
                        <div v-for="(item,index) in missionConfigOptions.executeRCLostAction" :key="index"
                            :class=" missionConfig.executeRCLostAction == item.value ? 'radio-item-active':'radio-item'" 
                            @click="missionConfig.executeRCLostAction = item.value"
                            >
                            {{item.label}}
                        </div>
                    </div>
                </div>
            </div>

            <div class="item flex-column">
                <div class="label">高度模式</div>
                <div class="content">
                    <div class="radio-box">
                        <div v-for="(item,index) in folderConfigOptions.executeHeightMode" :key="index"
                            :class=" folder.executeHeightMode == item.value ? 'radio-item-active':'radio-item'" 
                            @click="folder.executeHeightMode = item.value"
                            >
                            {{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 style="width:100px;" placeholder="" v-model:value="folder.autoFlightSpeed"></a-input>
                </div>
                <div class="unit"> m/s</div>
            </div>

            
            
           
        </div>

    </div>
</template>
<script lang="ts" setup>
import {ref,defineEmits,defineProps} from 'vue'
import { SaveOutlined,LeftOutlined,AppstoreOutlined,DownOutlined,ControlOutlined} from '@ant-design/icons-vue';

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

import {uploadXmlFile,addAirLine} from '@/api/sys/workplan';
import { Modal, message } from 'ant-design-vue';
import {missionConfigOptions,folderConfigOptions}  from '../waylineConfig/index.ts';

const emits = defineEmits(["setFlyPoint","checkPoint","exitDraw"])

const props = defineProps(["airPoints","airInfo","polygonAirForm"])

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

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

const checkPoint = (e)=>{
    emits("checkPoint",e);
}

// 航线基本信息
const missionConfig = ref(
    {
        "flyToWaylineMode": "safely",
        "finishAction": "goHome",
        "exitOnRCLost": "executeLostAction",
        "executeRCLostAction": "goBack",
        "takeOffSecurityHeight": 20,
        "globalTransitionalSpeed": 15,
        "globalRTHHeight": 100,
        "droneInfo": {
            "droneEnumValue": 100,
            "droneSubEnumValue": 1
        },
        "waylineAvoidLimitAreaMode": 0,
        "payloadInfo": {
            "payloadEnumValue": 99,
            "payloadSubEnumValue": 2,
            "payloadPositionIndex": 0
        }
    }
)

// 航点基本信息
const folder = ref({
    "templateId": 0,
    "executeHeightMode": "WGS84",
    "waylineId": 0,
    "distance": 410.047576904297,
    "duration": 80.3239784240723,
    "autoFlightSpeed": 10,
    "Placemark": []
})

// 航点详细信息
const pointInfo = ref({
    "Point": {
        "coordinates": "118.294611278,35.135603162"
    },
    "index": 0,
    "executeHeight": 172.948656023051,
    "waypointSpeed": 10,
    "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": 0,
        "actionGroupStartIndex": 0,
        "actionGroupEndIndex": 0,
        "actionGroupMode": "sequence",
        "actionTrigger": {
        "actionTriggerType": "reachPoint"
        },
        "action": [
        {
            "actionId": 0,
            "actionActuatorFunc": "rotateYaw",
            "actionActuatorFuncParam": {
            "aircraftHeading": 0,
            "aircraftPathMode": "counterClockwise"
            }
        },
        {
            "actionId": 1,
            "actionActuatorFunc": "gimbalRotate",
            "actionActuatorFuncParam": {
            "gimbalHeadingYawBase": "north",
            "gimbalRotateMode": "absoluteAngle",
            "gimbalPitchRotateEnable": 1,
            "gimbalPitchRotateAngle": 0,
            "gimbalRollRotateEnable": 0,
            "gimbalRollRotateAngle": 0,
            "gimbalYawRotateEnable": 0,
            "gimbalYawRotateAngle": 0,
            "gimbalRotateTimeEnable": 0,
            "gimbalRotateTime": 0,
            "payloadPositionIndex": 0
            }
        },
        {
            "actionId": 2,
            "actionActuatorFunc": "zoom",
            "actionActuatorFuncParam": {
            "focalLength": 24,
            "isUseFocalFactor": 0,
            "payloadPositionIndex": 0
            }
        }
        ]
    },
    "waypointGimbalHeadingParam": {
        "waypointGimbalPitchAngle": 0,
        "waypointGimbalYawAngle": 0
    },
    "isRisky": 0,
    "waypointWorkType": 0
})

const handlerPointInfo = ()=>{
    props.airPoints?.forEach((item,index)=>{
        let point = {
            "Point": {
                "coordinates": item.lng+","+item.lat
            },
            "index": index,
            "executeHeight": item.alt,
            "waypointSpeed": 10,
            "waypointHeadingParam": {
                "waypointHeadingMode": "followWayline",             // 飞行器偏航角模式 ：
                "waypointHeadingAngle": 0,                          // 飞行器偏航角 [-180, 180] 当且仅当“wpml:waypointHeadingMode”为“smoothTransition”时必需
                "waypointPoiPoint": "0.000000,0.000000,0.000000",   // 兴趣点    仅当wpml:waypointHeadingMode为towardPOI时必需
                "waypointHeadingAngleEnable": 0,
                "waypointHeadingPathMode": "followBadArc",          // 飞行器偏航角转动方向
                "waypointHeadingPoiIndex": 0
            },
            "waypointTurnParam": {
                "waypointTurnMode": "toPointAndStopWithDiscontinuityCurvature",
                "waypointTurnDampingDist": 0
            },
            "useStraightLine": 1,
            "actionGroup": {
                "actionGroupId": 0,
                "actionGroupStartIndex": 0,
                "actionGroupEndIndex": 0,
                "actionGroupMode": "sequence",
                "actionTrigger": {
                "actionTriggerType": "reachPoint"
                },
                "action": [
                    {
                        "actionId": 0,
                        "actionActuatorFunc": "rotateYaw",
                        "actionActuatorFuncParam": {
                        "aircraftHeading": 0,
                        "aircraftPathMode": "counterClockwise"
                        }
                    },
                    {
                        "actionId": 1,
                        "actionActuatorFunc": "gimbalRotate",
                        "actionActuatorFuncParam": {
                        "gimbalHeadingYawBase": "north",
                        "gimbalRotateMode": "absoluteAngle",
                        "gimbalPitchRotateEnable": 1,
                        "gimbalPitchRotateAngle": 0,
                        "gimbalRollRotateEnable": 0,
                        "gimbalRollRotateAngle": 0,
                        "gimbalYawRotateEnable": 0,
                        "gimbalYawRotateAngle": 0,
                        "gimbalRotateTimeEnable": 0,
                        "gimbalRotateTime": 0,
                        "payloadPositionIndex": 0
                        }
                    },
                    {
                        "actionId": 2,
                        "actionActuatorFunc": "zoom",
                        "actionActuatorFuncParam": {
                        "focalLength": 24,
                        "isUseFocalFactor": 0,
                        "payloadPositionIndex": 0
                        }
                    }
                ]
            },
            "waypointGimbalHeadingParam": {              // 云台参数
                "waypointGimbalPitchAngle": 0,           // 云台 垂直俯仰角参数 [-90, -30]
                "waypointGimbalYawAngle": 0              // 云台 水平偏航角度
            },
            "isRisky": 0,
            "waypointWorkType": 0
        }
        folder.value.Placemark.push(point);
    })
}

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

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

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

    handlerPointInfo();

    const builder = new XMLBuilder();

    let lineData = {...waylinesJson.value}

    let obj = handlerPrefixWpml(lineData);

    let xmlString = builder.build(obj);

    let xmlString2 = xmlString.replace(/<\/?\d+>/g, "")

    let xmlString3 = xmlString2.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">`)

    console.log("xmlString3",xmlString3);


return null;
    handlerCreateFile(xmlString3);
}

// 处理wmpl:前缀 
const handlerPrefixWpml = (obj) => {
  for (const key in obj) {

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

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

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


// 保存表单
const submitForm = ref({
    "id": "",
    "airLineName": null, 
    "airLineType": "waypoint",
    "uavId": "",
    "flyToFirstPointMode": "", 
    "safeTakeoffAltitude": 0, 
    "safeTakeoffSpeed": 0,  
    "globalRouteSpeed": 0, 
    "taskCompletionAction": "", 
    "outOfControlOption": "",
    "typeOfOutOfControlAction": "",
    "globalWayPointType": "",
    "ptzControlMode": "",
    "aircraftYawAngleMode": "",
    "wpml": ""
})

// 生成xml文件
const handlerCreateFile =async (content)=>{

    const blob = new Blob([content], { type: 'wmpl/plain' });
  
    // 创建FormData对象用于上传
    const formData = new FormData();

    formData.append('xmlFile', blob);
    

    let res = await uploadXmlFile(formData);

    if(res){

        submitForm.value.wpml = res.path;

        let addAirLineRes =await addAirLine(submitForm.value);

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

    }else{
        message.error("操作失败！");

    }

}

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

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

.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;
    gap:12px;
}
.area-info .item{
    flex:1;
    color:#fff;
    text-align: center;
    display:flex;
    gap:12px;
    flex-direction: column;
}

.area-options{
    width:400px;
    height: calc( 100vh - 160px);
    padding:10px;
    position: absolute;
    left:4px;
    top:70px;
    overflow-y:auto;
    line-height:32px;
    background:#101010;
}

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

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

}

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

.air-point-list{
    width:100%;
    height: calc( 100vh - 260px);
    padding:10px;
    overflow-y:auto;
    line-height:32px;
    text-align: center;
}

.air-point-item{
    display:flex;
    gap:15px;
    border-bottom:1px solid rgba(255,255,255,0.2);
    padding:6px 0px;
}
.air-point-item .cel{
    flex:1;
    color:#fff;
}

.radio-box{
    width:100%;
    display: flex;
    overflow: hidden;
    border:0.5px solid #3B4154 ;
    font-size:12px;
}
.radio-box .radio-item{
    flex:1;
    color:#8A92A6 ;
    text-align: center;
    background:#222738 ;
    cursor:pointer;

}

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


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



::v-deep .ant-select-selector{
    border:none!important;
    color:#fff!important;
    background:#3F4150!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 ;
}

::v-deep .ant-input-number{
    color:#fff!important;
    background:#3F4150!important;
    border:0px !important;
}

::v-deep .ant-input-number-input{
    color:#fff!important;
    border:0px !important;
}
</style>