<template>
  <div class="route-planning-container">
    <!-- 顶部操作栏 -->
    <div class="header-toolbar">
      <a-space>
        <a-button 
          type="primary" 
          @click="handleNewRoute"
          :loading="creating"
        >
          <template #icon><icon-plus /></template>
          新建航线
        </a-button>
        
        <a-button @click="refreshRoutes">
          <template #icon><icon-refresh /></template>
          刷新
        </a-button>
        
        <a-button @click="exportRoutes">
          <template #icon><icon-download /></template>
          导出航线
        </a-button>
      </a-space>
    </div>

    <!-- 主要内容区域 -->
    <div class="main-content">
      <!-- 左侧航线列表 -->
      <div class="left-panel">
        <div class="search-section">
          <a-input-search
            v-model="searchKeyword"
            placeholder="搜索航线名称"
            allow-clear
            @search="handleSearch"
          />
        </div>
        
        <div class="route-list">
          <div class="list-header">
            <span class="header-title">航线名称</span>
            <span class="header-action">操作</span>
          </div>
          
          <div class="list-content">
            <div
              v-for="route in filteredRoutes"
              :key="route.id"
              class="route-item"
              :class="{ active: selectedRoute?.id === route.id }"
              @click="selectRoute(route)"
            >
              <div class="route-info">
                <div class="route-name">{{ route.name }}</div>
                <div class="route-meta">
                  <a-tag size="small" :color="getStatusColor(route.status)">
                    {{ route.status }}
                  </a-tag>
                </div>
              </div>
              
              <div class="route-actions">
                <a-dropdown @click.stop>
                  <a-button type="text" size="small">
                    <template #icon><icon-more /></template>
                  </a-button>
                  <template #content>
                    <a-doption @click="editRoute(route)">
                      <template #icon><icon-edit /></template>
                      编辑
                    </a-doption>
                    <a-doption @click="copyRoute(route)">
                      <template #icon><icon-copy /></template>
                      复制
                    </a-doption>
                    <a-doption @click="deleteRoute(route)" class="danger">
                      <template #icon><icon-delete /></template>
                      删除
                    </a-doption>
                  </template>
                </a-dropdown>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 右侧详情面板 -->
      <div class="right-panel">
        <div v-if="selectedRoute" class="route-detail">
          <div class="detail-header">
            <h2>{{ selectedRoute.name }}</h2>
            <div class="header-tags">
              <a-tag :color="getStatusColor(selectedRoute.status)">
                {{ selectedRoute.status }}
              </a-tag>
            </div>
          </div>
          
          <div class="detail-content">
            <a-tabs>
              <a-tab-pane key="basic" title="基本信息" tab="基本信息">
                <div class="info-grid">
                  <div class="info-item">
                    <label>创建人</label>
                    <span>{{ selectedRoute.creator }}</span>
                  </div>
                  <div class="info-item">
                    <label>施工程师</label>
                    <span>{{ selectedRoute.engineer }}</span>
                  </div>
                  <div class="info-item">
                    <label>创建时间</label>
                    <span>{{ selectedRoute.createTime }}</span>
                  </div>
                  <div class="info-item">
                    <label>适用机型</label>
                    <span>{{ selectedRoute.droneModel }}</span>
                  </div>
                  <div class="info-item">
                    <label>预计耗时</label>
                    <span>{{ selectedRoute.estimatedTime }}</span>
                  </div>
                  <div class="info-item">
                    <label>航线长度</label>
                    <span>{{ selectedRoute.routeLength }}</span>
                  </div>
                </div>
              </a-tab-pane>
              
              <a-tab-pane key="waypoints" title="航点信息" tab="航点信息">
                <div class="waypoints-table">
                  <a-table
                    :data="selectedRoute.waypoints"
                    :columns="waypointColumns"
                    :pagination="false"
                    size="small"
                  />
                </div>
              </a-tab-pane>
              
              <a-tab-pane key="map" title="航线预览" tab="航线预览">
                <div class="map-container">
                  <div class="map-placeholder">
                    <icon-location />
                    <p>航线地图预览</p>
                    <p class="map-info">{{ selectedRoute.name }} 的航线路径</p>
                  </div>
                </div>
              </a-tab-pane>
            </a-tabs>
          </div>
        </div>
        
        <div v-else class="empty-state">
          <a-empty description="选择左侧航线查看详情" />
        </div>
      </div>
    </div>

    <!-- 新建/编辑航线模态框 -->
    <a-modal
      v-model:visible="modalVisible"
      :title="isEdit ? '编辑航线' : '新建航线'"
      width="600px"
      @ok="handleModalOk"
      @cancel="handleModalCancel"
    >
      <a-form ref="formRef" :model="routeForm" layout="vertical">
        <a-form-item label="航线名称" field="name" required>
          <a-input v-model="routeForm.name" placeholder="请输入航线名称" />
        </a-form-item>
        
        <a-form-item label="适用机型" field="droneModel" required>
          <a-select v-model="routeForm.droneModel" placeholder="请选择适用机型">
            <a-option value="DJI M300">DJI M300</a-option>
            <a-option value="DJI M350">DJI M350</a-option>
            <a-option value="Custom T1000">Custom T1000</a-option>
          </a-select>
        </a-form-item>
        
        <a-form-item label="施工程师" field="engineer">
          <a-input v-model="routeForm.engineer" placeholder="请输入施工程师" />
        </a-form-item>
        
        <a-form-item label="预计耗时" field="estimatedTime">
          <a-input v-model="routeForm.estimatedTime" placeholder="如：45 min" />
        </a-form-item>
        
        <a-form-item label="航线描述" field="description">
          <a-textarea v-model="routeForm.description" placeholder="请输入航线描述" />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { Message } from '@arco-design/web-vue'
import type { TableColumnData } from '@arco-design/web-vue'

defineOptions({ name: 'RoutePlanning' })

// 接口定义
interface RouteData {
  id: string
  name: string
  creator: string
  engineer: string
  createTime: string
  droneModel: string
  estimatedTime: string
  routeLength: string
  status: string
  description?: string
  waypoints: WaypointData[]
}

interface WaypointData {
  id: string
  sequence: number
  latitude: number
  longitude: number
  altitude: number
  speed: number
  action: string
}

// 响应式数据
const searchKeyword = ref('')
const selectedRoute = ref<RouteData | null>(null)
const modalVisible = ref(false)
const isEdit = ref(false)
const creating = ref(false)
const formRef = ref()

// 表单数据
const routeForm = reactive({
  name: '',
  droneModel: '',
  engineer: '',
  estimatedTime: '',
  description: ''
})

// 航线数据
const routes = ref<RouteData[]>([
  {
    id: '1',
    name: 'A风场东区航线',
    creator: '张工程师',
    engineer: '张工程师',
    createTime: '2023-10-15',
    droneModel: 'DJI M300',
    estimatedTime: '45 min',
    routeLength: '5.2 km',
    status: '已完成',
    description: 'A风场东区域的常规巡检航线',
    waypoints: [
      { id: '1', sequence: 1, latitude: 39.9042, longitude: 116.4074, altitude: 100, speed: 5, action: '拍照' },
      { id: '2', sequence: 2, latitude: 39.9142, longitude: 116.4174, altitude: 100, speed: 5, action: '悬停' },
      { id: '3', sequence: 3, latitude: 39.9242, longitude: 116.4274, altitude: 100, speed: 5, action: '拍照' }
    ]
  },
  {
    id: '2',
    name: 'B风场西区航线',
    creator: '李工程师',
    engineer: '李工程师',
    createTime: '2023-10-12',
    droneModel: 'DJI M350',
    estimatedTime: '35 min',
    routeLength: '4.8 km',
    status: '进行中',
    description: 'B风场西区域的检测航线',
    waypoints: [
      { id: '4', sequence: 1, latitude: 39.8042, longitude: 116.3074, altitude: 120, speed: 6, action: '拍照' },
      { id: '5', sequence: 2, latitude: 39.8142, longitude: 116.3174, altitude: 120, speed: 6, action: '录像' }
    ]
  }
])

// 航点表格列配置
const waypointColumns: TableColumnData[] = [
  { title: '序号', dataIndex: 'sequence', width: 80 },
  { title: '纬度', dataIndex: 'latitude', width: 120 },
  { title: '经度', dataIndex: 'longitude', width: 120 },
  { title: '高度(m)', dataIndex: 'altitude', width: 100 },
  { title: '速度(m/s)', dataIndex: 'speed', width: 100 },
  { title: '动作', dataIndex: 'action', width: 100 }
]

// 计算属性
const filteredRoutes = computed(() => {
  if (!searchKeyword.value) return routes.value
  return routes.value.filter(route => 
    route.name.toLowerCase().includes(searchKeyword.value.toLowerCase())
  )
})

// 方法
const handleSearch = () => {
  // 搜索逻辑已在 computed 中处理
}

const selectRoute = (route: RouteData) => {
  selectedRoute.value = route
}

const getStatusColor = (status: string) => {
  const colorMap: Record<string, string> = {
    '已完成': 'green',
    '进行中': 'blue',
    '待执行': 'orange',
    '已暂停': 'red'
  }
  return colorMap[status] || 'gray'
}

const handleNewRoute = () => {
  isEdit.value = false
  resetForm()
  modalVisible.value = true
}

const editRoute = (route: RouteData) => {
  isEdit.value = true
  Object.assign(routeForm, {
    name: route.name,
    droneModel: route.droneModel,
    engineer: route.engineer,
    estimatedTime: route.estimatedTime,
    description: route.description || ''
  })
  modalVisible.value = true
}

const copyRoute = (route: RouteData) => {
  const newRoute = {
    ...route,
    id: Date.now().toString(),
    name: `${route.name} - 副本`,
    status: '待执行'
  }
  routes.value.push(newRoute)
  Message.success('航线复制成功')
}

const deleteRoute = (route: RouteData) => {
  const index = routes.value.findIndex(r => r.id === route.id)
  if (index > -1) {
    routes.value.splice(index, 1)
    if (selectedRoute.value?.id === route.id) {
      selectedRoute.value = null
    }
    Message.success('航线删除成功')
  }
}

const resetForm = () => {
  Object.assign(routeForm, {
    name: '',
    droneModel: '',
    engineer: '',
    estimatedTime: '',
    description: ''
  })
}

const handleModalOk = async () => {
  creating.value = true
  try {
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    if (isEdit.value) {
      // 编辑逻辑
      const route = routes.value.find(r => r.id === selectedRoute.value?.id)
      if (route) {
        Object.assign(route, routeForm)
        selectedRoute.value = route
      }
      Message.success('航线更新成功')
    } else {
      // 新建逻辑
      const newRoute: RouteData = {
        id: Date.now().toString(),
        ...routeForm,
        creator: '当前用户',
        createTime: new Date().toLocaleDateString(),
        routeLength: '0 km',
        status: '待执行',
        waypoints: []
      }
      routes.value.push(newRoute)
      selectedRoute.value = newRoute
      Message.success('航线创建成功')
    }
    
    modalVisible.value = false
    resetForm()
  } catch (error) {
    Message.error('操作失败')
  } finally {
    creating.value = false
  }
}

const handleModalCancel = () => {
  modalVisible.value = false
  resetForm()
}

const refreshRoutes = () => {
  Message.success('航线列表已刷新')
}

const exportRoutes = () => {
  Message.success('航线导出成功')
}

// 组件挂载
onMounted(() => {
  // 默认选择第一条航线
  if (routes.value.length > 0) {
    selectedRoute.value = routes.value[0]
  }
})
</script>

<style scoped lang="scss">
.route-planning-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: #f5f5f5;
  
  .header-toolbar {
    padding: 16px 20px;
    background: white;
    border-bottom: 1px solid #e5e5e5;
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
  }
  
  .main-content {
    flex: 1;
    display: flex;
    gap: 1px;
    
    .left-panel {
      width: 400px;
      background: white;
      display: flex;
      flex-direction: column;
      
      .search-section {
        padding: 16px;
        border-bottom: 1px solid #e5e5e5;
      }
      
      .route-list {
        flex: 1;
        overflow: hidden;
        
        .list-header {
          display: flex;
          justify-content: space-between;
          align-items: center;
          padding: 12px 16px;
          background: #f8f9fa;
          border-bottom: 1px solid #e5e5e5;
          font-weight: 600;
          color: #374151;
        }
        
        .list-content {
          flex: 1;
          overflow-y: auto;
          
          .route-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 12px 16px;
            cursor: pointer;
            border-bottom: 1px solid #f0f0f0;
            transition: all 0.2s;
            
            &:hover {
              background: #f8f9fa;
            }
            
            &.active {
              background: #e6f7ff;
              border-left: 3px solid #1890ff;
            }
            
            .route-info {
              flex: 1;
              
              .route-name {
                font-weight: 500;
                color: #1f2937;
                margin-bottom: 4px;
              }
              
              .route-meta {
                display: flex;
                gap: 8px;
                align-items: center;
              }
            }
            
            .route-actions {
              opacity: 0;
              transition: opacity 0.2s;
            }
            
            &:hover .route-actions {
              opacity: 1;
            }
          }
        }
      }
    }
    
    .right-panel {
      flex: 1;
      background: white;
      
      .route-detail {
        height: 100%;
        display: flex;
        flex-direction: column;
        
        .detail-header {
          display: flex;
          justify-content: space-between;
          align-items: center;
          padding: 20px;
          border-bottom: 1px solid #e5e5e5;
          
          h2 {
            margin: 0;
            color: #1f2937;
          }
        }
        
        .detail-content {
          flex: 1;
          padding: 20px;
          
          .info-grid {
            display: grid;
            grid-template-columns: repeat(2, 1fr);
            gap: 16px;
            margin-bottom: 24px;
            
            .info-item {
              display: flex;
              flex-direction: column;
              gap: 4px;
              
              label {
                font-weight: 500;
                color: #6b7280;
                font-size: 14px;
              }
              
              span {
                color: #1f2937;
                font-size: 14px;
              }
            }
          }
          
          .waypoints-table {
            margin-top: 16px;
          }
          
          .map-container {
            display: flex;
            align-items: center;
            justify-content: center;
            height: 400px;
            border: 2px dashed #d1d5db;
            border-radius: 8px;
            
            .map-placeholder {
              text-align: center;
              color: #6b7280;
              
              .arco-icon {
                font-size: 48px;
                margin-bottom: 16px;
              }
              
              p {
                margin: 8px 0;
                
                &.map-info {
                  font-size: 14px;
                  color: #9ca3af;
                }
              }
            }
          }
        }
      }
      
      .empty-state {
        height: 100%;
        display: flex;
        align-items: center;
        justify-content: center;
      }
    }
  }
}

:deep(.arco-tabs-content) {
  height: auto;
}

:deep(.arco-dropdown-option.danger) {
  color: #f56565;
}
</style>
