<!-- 空域划设面板 -->
<template>
  <div class="panel-kyhs flex flex-col aside-left-inner">
    <div class="title-main">空域划设</div>
    <el-steps :active="currentStep" finish-status="success" align-center>
      <el-step title="空域划设" />
      <el-step title="空域评估" />
    </el-steps>

    <div class="flex-1 relative mb-4">
      <Transition name="emerge-left">
        <el-form ref="formRef" v-show="currentStep === 0" :model="form" :rules="rules" label-position="left"
          size="large" class="p-form p-main" hide-required-asterisk>
          <el-form-item label="名称" prop="name">
            <el-input v-model="form.name" clearable></el-input>
          </el-form-item>
          <el-form-item label="类型" prop="areaType">
            <el-select v-model="form.areaType" placeholder="">
              <el-option v-for="item in airSpaceTypes" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="类型" prop="type">
            <el-radio-group v-model="form.type" size="large">
              <el-radio-button label="长期" value="长期" />
              <el-radio-button label="临时" value="临时" />
            </el-radio-group>
          </el-form-item>
          <template v-if="form.type === '临时'">
            <el-form-item label="日期" prop="startDate">
              <el-date-picker v-model="form.startDate" value-format="YYYY-MM-DD" type="date"
                class="flex-1"></el-date-picker>
              <div class="mx-3">--</div>
              <el-date-picker v-model="form.endDate" value-format="YYYY-MM-DD" type="date"
                class="flex-1"></el-date-picker>
            </el-form-item>
            <el-form-item label="时间" prop="startTime">
              <el-time-select v-model="form.startTime" :max-time="form.endTime" placeholder="" start="00:00"
                step="00:15" end="23:45" class="flex-1" />
              <div class="mx-3">--</div>
              <el-time-select v-model="form.endTime" :min-time="form.startTime" placeholder="" start="00:00"
                step="00:15" end="23:45" class="flex-1" />
            </el-form-item>
            <el-form-item label="划设方式" prop="dataType">
              <el-radio-group v-model="form.dataType" size="large">
                <el-radio label="手动划设" value="手动划设" />
                <el-radio label="导入" value="导入" />
              </el-radio-group>
            </el-form-item>
          </template>
          <el-form-item label="类型" prop="drawType" v-if="form.dataType === '手动划设'">
            <el-radio-group v-model="form.drawType" size="large" class="content-between h-24">
              <el-radio-button v-for="item in drawTypes" :label="item.label" :value="item.value" />
            </el-radio-group>
          </el-form-item>
          <el-form-item label="上传文件" prop="file" v-else>
            <el-upload v-model:file-list="form.file" action="" class="single-uplaod">
              <div class="upload-trigger">点击上传文件</div>
            </el-upload>
          </el-form-item>
          <el-form-item label="高度" prop="height">
            <el-input v-model="form.height" type="number" clearable>
              <template #suffix>
                <span>米</span>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item label="顶半径" prop="topRadius" v-if="['mesh', 'point'].includes(form.drawType)">
            <el-input v-model="form.topRadius" type="number" clearable>
              <template #suffix>
                <span>米</span>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item label="底半径" prop="bottomRadius" v-if="form.drawType === 'mesh'">
            <el-input v-model="form.bottomRadius" type="number" clearable>
              <template #suffix>
                <span>米</span>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item label="绘制空域">
            <el-button class="btn-secondary" @click="handleDraw">绘制</el-button>
          </el-form-item>
          <el-form-item label="网格查询">
            <el-button :disabled="!hasDraw" class="btn-secondary">查询网格</el-button>
          </el-form-item>
        </el-form>
      </Transition>
      <Transition name="emerge-right">
        <div v-show="currentStep === 1" class="p-main">
          <div class="msg-safe mb-2">当前空域无冲突!</div>

          <div v-for="item in results" :key="item.title" class="mb-3">
            <div class="title-sub">
              {{ item.title }}
              <div class="flex-1 flex justify-between items-center pl-2">
                <span class="risk-label" :class="item.level === '低风险' ? 'green' : 'orange'">{{ item.level
                }}</span>
                <span class="btn-inline">重新评估</span>
              </div>
            </div>
            <table class="table-default stripe mt-2">
              <thead>
                <tr>
                  <th v-for="th in item.cols">{{ th }}</th>
                  <th class="w-20">地图显示</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="row in item.details">
                  <td v-for="key in Object.keys(item.cols)">{{ row[key] }}</td>
                  <td class="w-20">
                    <el-checkbox size="large" v-model="row.display"></el-checkbox>
                  </td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>
      </Transition>
    </div>
    <div class="text-center">
      <template v-if="currentStep === 0">
        <el-button :disabled="!hasDraw" class="btn-main" @click="toNext">下一步</el-button>
      </template>
      <template v-if="currentStep === 1">
        <el-button class="btn-main" @click="toPrev">上一步</el-button>
        <el-button class="btn-main" @click="handleSave" :loading="loading.save">保存</el-button>
      </template>
    </div>

  </div>
</template>

<script setup>
import { onBeforeUnmount, reactive, ref, watch } from 'vue';
import { drawArea, clearDraw } from '@/utils/map/addLayer'
import { airSpaceTypes } from '@/utils/options';
import { hexToRgb } from '@/utils/tools';
import { useMapStore } from '@/store/map';
import { AddArea } from '@/service/http';

const mapStore = useMapStore()

const currentStep = ref(0)

const form = ref({
  areaType: '1',
  dataType: '手动划设',
  type: '长期',
  drawType: 'rectangle',
  height: '100',
  topRadius: '150',
  bottomRadius: '50'
})

const rules = {
  name: [{ required: true, message: '请输入空域名称', trigger: 'none' }],
  height: [{ required: true, message: '此项不可为空', trigger: 'none' }],
  topRadius: [{ required: true, message: '此项不可为空', trigger: 'none' }],
  bottomRadius: [{ required: true, message: '此项不可为空', trigger: 'none' }],
}

const drawTypes = [
  { label: '矩形', value: 'rectangle', geoType: '2' },
  { label: '圆柱', value: 'circle', geoType: '1' },
  { label: '多面体', value: 'polygon', geoType: '3' },
  { label: '圆台', value: 'mesh', geoType: '6' },
  { label: '圆锥', value: 'point', geoType: '4' },
]

const results = ref([
  {
    title: '空域评估',
    level: '低风险',
    cols: { areaName: '冲突空域', height: '冲突高度' },
    details: [
      { areaName: '虹桥机场净空区', height: '112-120', display: false },
      { areaName: '虹桥机场净空区', height: '112-120', display: false },
    ]
  },
  {
    title: '计划冲突',
    level: '低风险',
    cols: { areaName: '冲突空域', height: '冲突高度' },
    details: [
      { areaName: '合生汇-黄兴公园美团飞行计划', height: '112-120', display: false },
      { areaName: '合生汇-黄兴公园美团飞行计划', height: '112-120', display: false },
    ]
  },
  {
    title: '障碍物分析',
    level: '高风险',
    cols: { time: '冲突时段', object: '冲突空域', height: '冲突高度' },
    details: [
      { time: '01-249:00-01-25 10-00', object: '建筑物', height: '112-120', display: false },
      { time: '01-249:00-01-25 10-00', object: '建筑物', height: '112-120', display: false },
    ]
  },
  {
    title: '地面安全评估',
    level: '高风险',
    cols: { element: '要素', coverage: '覆盖率' },
    details: [
      { element: '路面', coverage: '40%', display: false },
      { element: '道路', coverage: '20%', display: false },
      { element: '综合占比', coverage: '60%', display: false },
    ]
  }
])

const hasDraw = ref(false)

function handleDraw() {
  formRef.value.validateField(['height', 'topRadius', 'bottomRadius'], async (isValid) => {
    if (!isValid) return
    if (hasDraw.value) {
      clearDraw()
      await new Promise((res) => {
        setTimeout(() => res(), 500);
      })
    }
    // 处理绘制
    const color = hexToRgb(airSpaceTypes.find(i => i.value === form.value.areaType).color, 0.5)
    drawArea({
      ...form.value,
      color
    })
  })
}

let drawGeometry

watch(() => mapStore.draw_geometry, (val) => {
  console.log('draw_geometry:', val)
  drawGeometry = val
  hasDraw.value = true
}, { deep: true })

const formRef = ref(null)

function toNext() {
  formRef.value.validate(valid => {
    if (valid) {
      currentStep.value = 1
    }
  })
}

function toPrev() {
  currentStep.value = 0
}

const loading = reactive({
  save: false
})

function handleSave() {
  loading.save = true
  let params = {
    ...form.value,
    spaceType: form.value.areaType,
    geoType: drawTypes.find(i => i.value === form.value.drawType).geoType,
    upRadius: form.value.topRadius,
    downRadius: form.value.bottomRadius,
    shape: ''
  }
  const { x, y, z } = drawGeometry
  switch (params.geoType) {
    case '1':
    case '2':
    case '3':
      params.shape = JSON.stringify({
        height: params.height,
        rings: drawGeometry.rings
      })
      break;
    case '4':
      params.shape = JSON.stringify({
        point: { x, y, z },
        height: params.height,
        radius: params.upRadius
      })
      break;
    case '6':
      params.shape = JSON.stringify({
        point: { x, y, z },
        height: params.height,
        topRadius: params.upRadius,
        bottomRadius: params.downRadius
      })
      break;
  }
  AddArea(params).then(({data: res}) => {
    if(res.msg==='success') {
      ElMessage({ offset: 90, type: 'success', message: '保存成功' })
    } else {
      ElMessage({ offset: 90, type: 'error', message: `保存失败，${res.msg}` })
    }
  }).catch((e) => {
    ElMessage({ offset: 90, type: 'error', message: `保存失败，${e}` })
  }).finally(() => {
    loading.save = false
  })
}

onBeforeUnmount(() => {
  clearDraw()
})

</script>

<style lang="scss">
@use '../../../assets/styles/panel-form.scss';
</style>

<style lang="scss" scoped>
.panel-kyhs {
  :deep(.p-form) {
    .el-form-item__label {
      width: 105px;
    }
  }
}
</style>