<template>
    <div class="container">
        <div class="title">
            <span v-if="props.workPlanStatus === 'edit'">编辑计划</span>
            <span v-else-if="props.workPlanStatus === 'create'">创建计划</span>
            <span v-else-if="props.workPlanStatus === 'detail'">计划详情</span>
        </div>
        <div class="body-container">
            <a-form
                ref="formRef"
                :layout="'vertical'"
                :model="submitForm"
                :rules="rules"
                :label-col="labelCol"
                :wrapper-col="wrapperCol"
                :size="'middle'"
            >
                    <div class="group-container">
                        <a-form-item ref="name" label="计划名称" name="taskName">
                            <a-input v-model:value="submitForm.taskName" placeholder="请输入计划名称" />
                        </a-form-item>
                    </div>

                    <div class="group-container">
                        <!-- <a-form-item ref="name" label="任务类型" name="taskType">
                            <div class="radio-box">
                                <div v-for="(item,index) in taskTypeOptions" :key="index"
                                    :class=" submitForm.taskType == item.value ? 'radio-item-active':'radio-item'" 
                                    @click="submitForm.taskType = item.value"
                                    >
                                    {{item.label}}
                                </div>
                            </div>
                        </a-form-item> -->

                        <!-- <a-form-item ref="name" label="选择项目" name="name">
                            <a-button type="primary" style="width:100%;" @click="selectAriLine" v-show="!submitForm.airLineId">
                                <PlusOutlined />
                                选择项目
                            </a-button>
    
                            <div class="select-item" v-show="submitForm.airLineId">
                                <div class="item-name">{{submitForm.taskAirLineName}}</div>
                                <div class="item-operate" @click="selectAriLine">
                                    <MoreOutlined />
                                </div>
                            </div>
                        </a-form-item> -->

    
                        <a-form-item ref="name" label="选择航线" name="name">
                            <a-button type="primary" style="width:100%;" @click="selectAriLine" v-show="!submitForm.airLineId">
                                <PlusOutlined />
                                选择航线
                            </a-button>
    
                            <div class="select-item" v-show="submitForm.airLineId">
                                <div class="item-name">{{submitForm.taskAirLineName}}</div>
                                <div class="item-operate" @click="selectAriLine">
                                    <MoreOutlined />
                                </div>
                            </div>
                        </a-form-item>
    
                        <a-form-item ref="name" label="选择设备" name="name">
                            <a-button type="primary" style="width:100%;"  @click="selectAircraft" v-show="!submitForm.taskDronePort">
                                <PlusOutlined />
                                选择设备
                            </a-button>
    
                            <div class="select-item" v-show="submitForm.taskDronePort">
                                <div class="item-name">{{submitForm.taskDronePortName}}</div>
                                <div class="item-operate" @click="selectAircraft">
                                    <MoreOutlined  />
                                </div>
                            </div>
    
                        </a-form-item>
                    </div>

                    <div class="group-container">
                        <a-form-item ref="accuracy" label="任务精度" name="accuracy">

                            <div class="radio-box">
                                <div v-for="(item,index) in waylinePrecisionTypeOptions" :key="index"
                                    :class=" submitForm.waylinePrecisionType == item.value ? 'radio-item-active':'radio-item'" 
                                    @click="submitForm.waylinePrecisionType = item.value"
                                    >
                                    {{item.label}}
                                </div>
                            </div>
    
                            
                        </a-form-item>
    
                        <a-form-item ref="accuracy" label="任务策略" name="accuracy">
    
                            <div class="radio-box">
                                <div v-for="(item,index) in periodicFormulaOptions" :key="index"
                                    :class=" submitForm.taskType == item.value ? 'radio-item-active':'radio-item'" 
                                    @click="submitForm.taskType = item.value"
                                    >
                                    {{item.label}}
                                </div>
                            </div>
                         
                        </a-form-item> 


                        <!-- 单次定时 -->
                        <a-form-item v-if="submitForm.taskType == 1" label="设置时间">
                            <a-date-picker v-model:value="onceTime" valueFormat="YYYY-M-D HH:mm:ss" style="width:100%;" show-time placeholder="选择时间" @change="onOnceTimeChange"  />
                        </a-form-item> 

                        <!-- 重复定时 -->
                        <div v-if="submitForm.taskType == 2">
                            <a-form-item  ref="accuracy" label="选择日期"  name="accuracy">
                                <a-range-picker v-model:value="repeatTime.date" valueFormat="YYYY-M-D"  style="width:100%;"   @change="onRepeatDateChange" />
                            </a-form-item> 
    
                            <a-form-item ref="accuracy" label="选择时间" name="accuracy">
                                <a-time-picker  v-model:value="repeatTime.time" format="HH:mm:ss" valueFormat="H:m:s" style="width:100%;"   @change="onRepeatTimeChange" />
                            </a-form-item> 

                            <a-form-item ref="accuracy" label="重复频率" name="accuracy">
                                <div class="repeat-time">
                                    <div>每</div>
                                    <div>
                                        <a-input v-model:value="repeatTime.count"></a-input>
                                    </div>
                                    <div>
                                        <a-select
                                            ref="select"
                                            v-model:value="repeatTime.type"
                                            @change="handleRepeatTypeChange"
                                            >
                                            <a-select-option value="date">天</a-select-option>
                                            <!-- <a-select-option value="week">周</a-select-option> -->
                                            <!-- <a-select-option value="month">月</a-select-option> -->
                                        </a-select>
                                    </div>
                                </div>
                                <div class="week-container" v-if="repeatTime.type == 'week'">
                                    <div v-for="(item,index) in weekdays" :class="item.checked ? 'week-item-active':'week-item'" @click="item.checked=!item.checked" >{{item.label}}</div>
                                </div>
                            </a-form-item> 
                        </div>
                    </div>
                    

                    <div class="group-container">
                        
                        <div style="display:flex;color:#fff;font-size:12px;padding:20px 0px;">
                            <div style="flex:1;">智能巡检</div>
                            <div>
                                <a-switch v-model:checked="submitForm.aiInspection"
                                    checked-color="#3A57E8"
                                    un-checked-color="#cccccc"
                                />
                            </div>
                        </div>
    
                        <a-form-item ref="outOfContact" label="返航高度（相对机场返航高度）" name="outOfContact">
                            <div class="return-height">
                                <div @click="submitForm.returnAltitude-=100">-100</div>
                                <div @click="submitForm.returnAltitude-=10">-10</div>
                                <div @click="submitForm.returnAltitude-=1">-1</div>
                                <div>
                                    <a-input type="text" size="small" v-model:value="submitForm.returnAltitude" style="width:40px;"></a-input>
                                </div>
                                <div>m</div>
                                <div @click="submitForm.returnAltitude+=1">+1</div>
                                <div @click="submitForm.returnAltitude+=10">+10</div>
                                <div @click="submitForm.returnAltitude+=100">+100</div>
                            </div>
                        </a-form-item>
    
                        <a-form-item ref="outOfContact" label="航线飞行中失控" name="lossOfControlAction">
                            <div class="radio-box">
                                <div v-for="(item,index) in lossOfControlActionOptions" :key="index"
                                    :class=" submitForm.lossOfControlAction == item.value ? 'radio-item-active':'radio-item'" 
                                    @click="submitForm.lossOfControlAction = item.value"
                                    >
                                    {{item.label}}
                                </div>
                            </div>
                       
                        </a-form-item>
    
                        <a-form-item ref="outOfContact" label="完成动作" name="outOfContact" v-if="submitForm.lossOfControlAction == 1">
                            <div class="radio-box">
                                <div v-for="(item,index) in continuationModeOptions" :key="index"
                                        :class=" submitForm.continuationMode == item.value ? 'radio-item-active':'radio-item'" 
                                        @click="submitForm.continuationMode = item.value"
                                    >
                                    {{item.label}}
                                </div>
                            </div>
                        </a-form-item>
                    </div>
                 
            </a-form>
        </div>
        <div class="footer-container">
            <div >
                <a-button v-if="!paramValue" @click="resetForm"  style="width:100%;">取消</a-button>
            </div>

            <div v-if="submitForm.status == 0">
                <a-button style="width:100%;" type="primary" @click="onSubmit" v-if="props.workPlanStatus == 'create'">创建</a-button>
                <!-- <a-button style="width:100%;" type="primary" @click="onSubmit" v-if="props.workPlanStatus == 'edit'">编辑</a-button> -->
            </div>

            <div v-if="props.workPlanStatus == 'detail' && submitForm.status == 5">
                <a-button style="width:100%;" type="primary" @click="toImageList()">结果</a-button>
            </div>

            
        </div>
    </div>

</template>
<script lang="ts" setup>
import { ref, defineEmits, defineProps, watch } from "vue";
import { PlusOutlined,LeftOutlined,DeleteOutlined,MoreOutlined } from '@ant-design/icons-vue';
import { addTask,editTask } from "@/api/sys/workplan";

import { Modal, message } from 'ant-design-vue';
import { useRoute,useRouter } from 'vue-router'
const router = useRoute()
const routerer = useRouter();
const paramValue = router.query.taskid

const formRef = ref();
const labelCol = { span: 24 };
const wrapperCol = { span: 24 };
const props = defineProps({
    "checkedAriLine":{
        type:Object
    },
    "checkedDronePort":{
        type:Object
    },
    "formData":{
        type:Object,
        default: ()=>({
            "id": null,
            "taskName": null,
            "taskType": 0,
            "taskAirLineName": null,
            "taskDronePortName": null,
            "taskDronePort": null,
            "taskAirLine": null,
            "returnAltitude": 20,
            "lossOfControlAction": 1,
            "continuationMode": 0,
            "aiInspection": null,
            "status": 0,
            "periodicFormula": null,
            "airLineId": null,
            "createId": 0,
            "createTime": "",
            "waylinePrecisionType": 0,
            "scheduledStartTime": "",
            "scheduledEndTime": "",
            "executeTime": "",
            "completedTime": "",
            "planExecuteDuration": 0,
            "actualExecuteDuration": 0,
            "workspaceId": null,
            "expectedFileCount": 0,
            "uploadedFileCount": 0,
            "flightId": null,
            "reason": null,
            "externalTaskId": null
        })
    },
    "editMode":{
        type:String,
        default:"add"
    },
    "workPlanStatus":{
        type:String,
        default:""
    }
});


const submitForm = ref({
  "id": null,
  "taskName": null,
  "taskType": 0,
  "taskAirLineName": null,
  "taskDronePortName": null,
  "taskDronePort": null,
  "taskAirLine": null,
  "returnAltitude": 20,
  "lossOfControlAction": 1,
  "continuationMode": 0,
  "aiInspection": null,
  "status": 0,
  "periodicFormula": null,
  "airLineId": null,
  "createId": 0,
  "createTime": "",
  "waylinePrecisionType": 0,
  "scheduledStartTime": "",
  "scheduledEndTime": "",
  "executeTime": "",
  "completedTime": "",
  "planExecuteDuration": 0,
  "actualExecuteDuration": 0,
  "workspaceId": null,
  "expectedFileCount": 0,
  "uploadedFileCount": 0,
  "flightId": null,
  "reason": null,
  "externalTaskId": null,
})


const weekdays = ref([
    {
        'label':'周日',
        'checked':false
    },{
        'label':'周一',
        'checked':false
    },{
        'label':'周二',
        'checked':false
    },{
        'label':'周三',
        'checked':false
    },{
        'label':'周四',
        'checked':false
    },{
        'label':'周五',
        'checked':false
    },{
        'label':'周六',
        'checked':false
    }
])
const onceTime = ref(null);
const repeatTime = ref({
    date:null, 
    time:null,
    count:1,
    type:'date'
});
const visible = ref(false);

const handlerDisplayCronTime = ()=>{
    if(props.formData.taskType == 1){
        let cronArray = props.formData.periodicFormula.split(" ");
        onceTime.value = cronArray[6]+"-"+cronArray[4]+"-"+cronArray[3] +" "+cronArray[2]+":"+cronArray[1]+":"+cronArray[0]
    }else if(props.formData.taskType == 2){
        let cronArray = props.formData.periodicFormula.split(" ");
        console.log("cronArray",cronArray);
        let days = cronArray[3].split("-")
        repeatTime.value.date = [cronArray[6]+"-"+cronArray[4]+"-"+days[0], cronArray[6]+"-"+cronArray[4]+"-"+days[1]]
        console.log(" repeatTime.value.date", repeatTime.value.date);
        repeatTime.value.time = cronArray[2]+":"+cronArray[1]+":"+cronArray[0]
    }
}

// 去查看结果
const toImageList = () => {
    console.log("formData",props.formData.id);


    routerer.push({
        path: '/system/mediaLibrary',
        query: {
            flightId:props.formData.id
        }
    });
}

// 回显时间
if(props.formData){
    handlerDisplayCronTime();
}

const handleOk = ()=>{

}
const handlerSetTime = ()=>{
    visible.value = true;
}
const handleCancel = () => {
    visible.value = false
}

// const submitForm = ref({
//     taskName:null,               // 任务名称
//     taskType:0,                  // 任务类型
//     taskDronePort:null,          // 执行机场s
//     taskAirLine:null,            // 航线id
//     returnAltitude:0,            // 返航高度
//     lossOfControlAction:"executeLostAction",    // 返航失控动作
//     continuationMode:"goBack",       // 续飞模式
//     aiInspection:null,           // AI巡检            
//     periodicFormula:0,        // 周期公式
//     airLineId:1,                 // 航线记录id
//     waylinePrecisionType:0,   // 任务精度
//     taskAirLineName : null,
//     taskDronePortName : null,
// })




if(props.formData){
    submitForm.value = props.formData
}

watch(
    ()=> props.formData,
    (newVal,oldVal)=>{
        submitForm.value = newVal;
    },
    {
        deep:true
    }
)

watch(
    ()=>props.checkedAriLine,
    (newVal,oldVal)=>{
        submitForm.value.taskAirLineName = newVal.airLineName;
        submitForm.value.airLineId = newVal.id;
    }
)

watch(
    ()=>props.checkedDronePort,
    (newVal,oldVal)=>{
        console.log("newVal",newVal);
        submitForm.value.taskDronePortName = newVal.name;
        submitForm.value.taskDronePort = newVal.id;
    }
)

const emit = defineEmits(['selectAriLine','cancleCraete',"selectAircraft","successCreatePlan"]);

const removeAirLine = ()=>{
    props.checkedAriLine.value = {};
}

const selectAriLine = ()=> {
    emit("selectAriLine",true)
}

const selectAircraft = ()=>{
    emit("selectAircraft",true)
}

// 任务类型
const taskTypeOptions = ref([
    {
        value:0,
        label:"普通任务"
    },
    // {
    //     value:1,
    //     label:"蛙跳任务"
    // }
])

// 任务精度
const waylinePrecisionTypeOptions = ref([
    {
        value:0,
        label:"高精度RTK"
    },
    {
        value:1,
        label:"GNSS"
    }
])

// 飞行中失控
const lossOfControlActionOptions = ref([
    {
        value:0,
        label:"继续执行航线"
    },{
        value:1,
        label:"执行失控动作"
    }
])

// 失控动作
const continuationModeOptions = ref([
    {
        value:0,
        label:"返航"
    },{
        value:1,
        label:"悬停"
    },{
        value:2,
        label:"降落"
    }
])

// 周期公式
const periodicFormulaOptions = ref([
    {
        value:0,
        label:"立即"
    },{
        value:1,
        label:"单次定时"
    },{
        value:2,
        label:"重复定时"
    }
])

const rules = {
    "taskName":[
        { required: true, message: "计划名称不能为空！", trigger: "blur" }, 
    ],
    "onceTime":[
        { required: true, message: "时间不能为空！", trigger: "blur" }, 
    ]
};

const onSubmit = () => {

     formRef.value.validate().then(
        ()=>{

            if(submitForm.value.taskType == 1){
                onOnceTimeChange();
            }

            if(submitForm.value.taskType == 2){
                handleRepeatTypeChange();
            }


            if(props.formData){
                // 编辑
                let data = {...submitForm.value}
            
                let res =  editTask(data);
                if(res){
                    message.success("操作成功！");
                    emit("successCreatePlan");
                }else{
                    message.error("操作失败！");
                }
            }else{
                if(paramValue){
                    submitForm.value.externalTaskId = paramValue
                }
                // 创建
                let res =  addTask(submitForm.value);
                if(res){
                    message.success("操作成功！");
                    emit("successCreatePlan");
                }else{
                    message.error("操作失败！");
                }
            }
        }
    ).catch(()=>{

    })


};

const resetForm = () => {
    emit("cancleCraete");
    formRef.value.resetFields();
};

const changeCron = ()=>{

}

const togglePopover = (e)=> {

}

// 处理单次定时日期
const onOnceTimeChange = () => {
    if(!onceTime.value){
        message.warning("请设置任务定时时间");
        return null;
    }

    let time = new Date(onceTime.value);

    let secondTime = time.getSeconds();
    let minutisTime = time.getMinutes();
    let hourTime = time.getHours();

    let dayTime =time.getDate();
    let monthTime = time.getMonth()+1;
    let yearTime = time.getFullYear();

    let cronTime = secondTime+" "+minutisTime+" "+ hourTime+" "+ dayTime+" "+monthTime+" ? "+yearTime

    submitForm.value.periodicFormula = cronTime;
}


// 选择日期
const onRepeatDateChange = (e) =>{
    // handleRepeatTypeChange(repeatTime.value.type);
}

// 选择时间
const onRepeatTimeChange = (e) => {
    // handleRepeatTypeChange(repeatTime.value.type);
}

// 重复定时
const handleRepeatTypeChange = ()=>{


    if(submitForm.value.taskType == 2 && !repeatTime.value.date){
        message.warning("选择日期！");
        return null;
    }
    
    if(submitForm.value.taskType == 2 && !repeatTime.value.time ){
        message.warning("选择时间！");
        return null;
    }

    // 获取时间
    let timeArray = repeatTime.value?.time?.split(":");
    
    let startDate = new Date(repeatTime.value?.date[0]).getDate();
    let endDate = new Date(repeatTime.value?.date[1]).getDate();
    let month = new Date(repeatTime.value?.date[0]).getMonth()+1;
    let year = new Date(repeatTime.value?.date[0]).getFullYear();

    let cronTime = "";
    
    switch(repeatTime.value.type){
        case 'date':
            cronTime = timeArray[2]+" "+timeArray[1]+" "+timeArray[0]+" "+ startDate +"-"+ endDate +" "+month+" ? "+year
            break;
        case 'week':
            let weekday = "";
            weekdays.value?.forEach((item,index)=>{
                if(item.checked){
                    weekday += index+","
                }
            })

            weekday = weekday.slice(0, -1);

            cronTime = timeArray[2]+" "+timeArray[1]+" "+timeArray[0]+" "+ startDate +"-"+ endDate +" "+month+" "+weekday+" "+year
            break;

        case 'month':
            
            break;
    }
    
    submitForm.value.periodicFormula = cronTime;

}

</script>

<style scoped>
.container{
    width:100%;
    height:100%;
    background: #0D0E15;
    box-shadow: 0px 10px 30px 0px rgba(0,0,6,0.15), 0px 10px 30px 1px rgba(0,0,6,0.15), inset 0px 0px 20px 8px rgba(58,87,232,0.73);
    border-radius: 6px;
    position:relative;
}
.title{
    padding:15px 15px;
    color:#fff;
    border-bottom:1px solid rgba(255,255,255,0.15);
}
.body-container{
    width:100%;
    margin:0px;
    height: calc( 100% - 110px);
    overflow-y: auto;
    padding:10px 15px;
}
.group-container{
    padding:15px;
    background:#262E4C;
    border-radius: 10px;
    margin:10px 0px;
}

.footer-container{
    padding:20px;
    width: calc( 100% - 10px);
    position:absolute;
    bottom:0px;
    left:0px;
    display:flex;
    gap:20px;
}
.footer-container div{
    flex:1;
}
.ant-form-item{
    margin-bottom:12px;
}

.select-item{
    width:100%;
    display: flex;
    color:#fff;
    border:1px solid #3B4154;
    padding:0px;
    border-radius: 15px;

}

.select-item .item-name{
    flex:1;
    border-right:1px solid #3B4154;
    padding:4px;
}
.select-item .item-operate{
    width:40px;
    text-align: center;
    padding:4px;
    cursor: pointer;
}

.repeat-time{
    display:flex;
    color:#fff;
    gap:12px;
    line-height: 32px;
}

.week-container{
    width:100%;
    display:flex;
    color:#fff;
    gap:8px;
    padding:12px 0px;
}
.week-item{
    padding:3px 5px;
    background:#050608;
    border-radius: 4px;
    font-size:12px;
    cursor:pointer;
}

.week-item-active{
    padding:3px 5px;
    background:#3A57E8;
    border-radius: 4px;
    font-size:12px;
    cursor:pointer;
}
.radio-box{
    width:100%;
    display: flex;
    overflow: hidden;
    border:0.5px solid #3B4154 ;
    background:#050608;
    font-size:13px;
    border-radius: 15px;
}


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

}

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

.return-height{
    display:flex;
    gap:5px;
}

.return-height div{
    flex:1;
    color: #fff ;
    background:#333B56;
    font-size:12px;
    padding:3px;
    text-align: center;
    cursor:pointer;
    border-radius: 15px;
}

::v-deep .ant-form-item-label > label{
    color:#ffffff!important;
    font-size:12px;
}


::v-deep .ant-select-selector{
    border:none!important;
    color:#fff!important;
    background:#050608 !important;
    border-radius: 3px!important;
    border-radius: 15px!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-btn-default{
    background:none!important;
    border:none!important;
    outline:none!important;
    color:#fff!important;
    height:30px !important;
    background:#29305477!important;
}

::v-deep .ant-btn-primary{
    background:#3A57E8!important;
    border-radius:3px!important;
}

::v-deep .ant-radio-button-wrapper-checked{
    background:#3A57E8!important;
}

::v-deep .ant-radio-button-wrapper{
    border-radius: 2px !important;
}

::v-deep .ant-switch{
    background:#ccc!important;
}

::v-deep .ant-switch-checked{
    background:#3A57E8!important;
}


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

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

::v-deep .ant-btn{
    border-radius: 15px!important;
}

::v-deep .ant-picker{
    background:#050608 !important;
    border:0px solid #ccc!important;
    color:#fff!important;
    border-radius: 15px!important;
}

::v-deep .ant-picker::placeholder{
    color:#fff!important;
}

::v-deep .ant-picker .ant-picker-input >input{
    color:#fff!important;
}

::v-deep .ant-picker .ant-picker-input >input::placeholder{
    color:#fff!important;
}


/*修改 a-input 浏览器自动填充文本颜色*/
/* 修改自动填充时的输入框样式 */
::v-deep .ant-input:-webkit-autofill {
  -webkit-text-fill-color: #ffffff; /* 修改文字颜色（红色） */
  transition: background-color 5000s ease-in-out 0s; /* 防止背景色闪烁 */
}
</style>