<template>
  <!-- 巡检路径编辑组件 -->
  <el-dialog
    id="path-editor-root"
    v-model="dialogVisible"
    :title="isEdit ? '编辑巡检路径' : '新增巡检路径'"
    width="90%"
    max-width="1200px"
    destroy-on-close
    @closed="handleClose"
  >
    <!-- 表单容器 -->
    <el-form
      ref="pathFormRef"
      :model="pathForm"
      label-width="100px"
      :rules="formRules"
    >
      <!-- 基本信息区域 -->
      <div class="mb-6">
        <h3 class="text-lg font-medium text-blue-300 mb-4">基本信息</h3>
        <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
          <el-form-item label="路径名称" prop="name">
            <el-input
              v-model="pathForm.name"
              placeholder="请输入路径名称"
              maxlength="50"
              show-word-limit
            />
          </el-form-item>
        </div>
        <el-form-item label="路径说明" prop="description">
          <el-input
            v-model="pathForm.description"
            type="textarea"
            rows="3"
            placeholder="请输入路径说明"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>
      </div>
      
      <!-- 地图展示区域 -->
       <!--建立 一个全局变量用于存放用户点击的设备名称列表，同步到编辑框的点位设备列表中-->
      <div class="mb-6">
        <h3 class="text-lg font-medium text-blue-300 mb-4">路径地图</h3>
        <div class="border border-blue-400 rounded-lg overflow-hidden relative">
          <!-- 地图容器，设置固定高度 -->
          <div class="path-map-container">
            <EditMap el-id="etsfs"/>
          </div>
          <!-- 地图操作提示 -->
          <div class="map-tip">
            <el-tooltip content="地图已加载，选择路径点后将显示路径连线" placement="top">
              <el-button size="small" type="primary" plain>
                <el-icon><HelpFilled /></el-icon> 地图使用提示
              </el-button>
            </el-tooltip>
          </div>
        </div>
      </div>
      
      <!-- 路径点表格区域 -->
      <div>
        <div class="flex justify-between items-center mb-4">
          <h3 class="text-lg font-medium text-blue-300">路径点配置</h3>
          <el-button type="primary" @click="handleAddPathPoint" icon="Plus">新增路径点</el-button>
        </div>
        
        <el-table
          v-loading="loading"
          :data="pathForm.points"
          style="width: 100%"
          @sort-change="handleSortChange"
        >
          <el-table-column prop="index" label="序号" width="80" align="center" sortable="custom" />
          <el-table-column prop="deviceName" label="路径点设备" min-width="200" align="center">
              <template #default="scope">
                <el-select
                  v-model="scope.row.deviceName"
                  placeholder="请输入设备名称"
                  style="width: 100%"
                  @change="(value) => handleDeviceSelect(value, scope.row)"
                >
                  <el-option
                    v-for="device in deviceList"
                    :key="device.value"
                    :label="device.label"
                    :value="device.value"
                  />
                </el-select>
              </template>
            </el-table-column>
            <el-table-column prop="modelId" label="地图模型ID" min-width="150" align="center" />
          <el-table-column label="操作" width="120" align="center">
            <template #default="scope">
              <div class="flex gap-2 justify-center">
                <el-button
                  size="small"
                  @click="handleMoveUp(scope.row, scope.$index)"
                  :disabled="scope.$index === 0"
                  icon="ArrowUp"
                >上移</el-button>
                <el-button
                  size="small"
                  @click="handleMoveDown(scope.row, scope.$index)"
                  :disabled="scope.$index === pathForm.points.length - 1"
                  icon="ArrowDown"
                >下移</el-button>
                <el-button
                  size="small"
                  type="danger"
                  @click="handleDeletePoint(scope.$index)"
                  icon="Delete"
                >删除</el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-form>
    
    <!-- 对话框底部按钮 -->
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSave">保存</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
  /**
   * 巡检路径编辑组件
   * 用于新增和编辑巡检路径信息，包含地图展示和路径点配置
   */
// 导入inject用于从Map组件获取map实例
import { ref, reactive, computed, onMounted, watch, inject } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import EditMap from '../EditMap.vue' // 导入地图组件
import { useDeviceStore } from '@/stores/device' // 导入设备store
import { usePathStore } from '@/stores/pathStore' // 导入路径store
import { useNavi } from '@/hooks/useNavi' // 导入导航hook

// Props定义
const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  pathData: {
    type: Object,
    default: null
  }
})

// Emits定义
const emit = defineEmits(['update:visible', 'save'])

// 响应式数据
const dialogVisible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value)
})

const pathFormRef = ref()
const loading = ref(false)

// 表单数据
const pathForm = reactive({
  id: '',
  name: '',
  description: '',
  points: []
})

// 表单验证规则
const formRules = reactive({
  name: [
    { required: true, message: '请输入路径名称', trigger: 'blur' },
    { min: 2, max: 50, message: '路径名称长度应在2-50个字符之间', trigger: 'blur' }
  ],
  description: [
    { max: 200, message: '路径说明长度不能超过200个字符', trigger: 'blur' }
  ]
})

// 获取设备store实例
const deviceStore = useDeviceStore()
// 获取路径store实例
const pathStore = usePathStore()

// 使用computed从store获取设备列表选项
const deviceList = computed(() => {
  return deviceStore.getSelectOptions()
})

// 计算属性
const isEdit = computed(() => !!props.pathData)

/**
 * 重置表单
 */
const resetForm = () => {
  pathForm.id = ''
  pathForm.name = ''
  pathForm.description = ''
  pathForm.points = []
  
  if (pathFormRef.value) {
    pathFormRef.value.resetFields()
  }
}

// 监听对话框可见性变化
watch(() => props.visible, (isVisible) => {
  if (isVisible) {
    // 对话框打开时，清空pathStore中的pathPoints数组
    pathStore.clearPathPoints()
    
    // 判断是否为编辑状态
    if (isEdit.value && pathForm.points.length > 0) {
      // 编辑状态：将pathForm.points同步到pathStore的pathPoints数组
      const pathPointsData = pathForm.points.map(point => ({
        modelId: point.modelId,
        deviceName: point.deviceName
      }))
      // 直接设置pathStore的pathPoints数组
      pathStore.pathPoints = pathPointsData
    }
    // 新增状态：保持pathStore中的pathPoints数组为空（已通过clearPathPoints实现）
  }
}, { immediate: true })

// 监听pathStore中pathPoints数组的变更，实现从全局到局部的同步
watch(() => pathStore.pathPoints, (newPathPoints) => {
  if (newPathPoints && newPathPoints.length > 0) {
    // 确保不重复同步（避免循环更新）
    const currentModelIds = pathForm.points.map(p => p.modelId)
    const newModelIds = newPathPoints.map(p => p.modelId)
    
    // 检查是否有变化需要同步
    const hasChanges = currentModelIds.length !== newModelIds.length ||
                      !currentModelIds.every((id, index) => id === newModelIds[index])
    
    if (hasChanges) {
      // 将全局pathPoints同步到表单的pathPoints中
      const synchronizedPoints = newPathPoints.map((point, index) => ({
        id: `${Date.now()}-${index}`, // 生成新的唯一ID
        index: index + 1, // 序号从1开始
        modelId: point.modelId,
        deviceName: point.deviceName
      }))
      
      pathForm.points = synchronizedPoints
    }
  }
}, { deep: true })

// 监听props变化
watch(() => props.pathData, (newVal) => {
  if (newVal) {
    // 编辑模式：填充表单数据
    pathForm.id = newVal.id || ''
    pathForm.name = newVal.name || ''
    pathForm.description = newVal.description || ''
    pathForm.points = newVal.points ? JSON.parse(JSON.stringify(newVal.points)) : []
    
    // 如果对话框已经可见且是编辑状态，同步到pathStore
    if (props.visible) {
      const pathPointsData = pathForm.points.map(point => ({
        modelId: point.modelId,
        deviceName: point.deviceName
      }))
      pathStore.pathPoints = pathPointsData
    }
  } else {
    // 新增模式：重置表单
    resetForm()
  }
}, { immediate: true })

/**
 * 处理对话框关闭
 */
const handleClose = () => {
  resetForm()
}

/**
 * 新增路径点
 */
const handleAddPathPoint = () => {
  const newIndex = pathForm.points.length + 1
  pathForm.points.push({
    id: `${Date.now()}-${Math.random().toString(36).substr(2, 9)}`,
    index: newIndex,
    deviceName: '',
    modelId: ''
  })
  
  // 更新序号
  updatePointIndexes()
}

/**
 * 删除路径点
 */
const handleDeletePoint = (index) => {
  ElMessageBox.confirm(
    '确定要删除这个路径点吗？',
    '确认删除',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    pathForm.points.splice(index, 1)
    updatePointIndexes()
    ElMessage.success('路径点删除成功')
  }).catch(() => {
    // 用户取消删除
  })
}

/**
 * 上移路径点
 */
const handleMoveUp = (row, index) => {
  if (index > 0) {
    // 交换位置
    const temp = pathForm.points[index]
    pathForm.points[index] = pathForm.points[index - 1]
    pathForm.points[index - 1] = temp
    
    // 更新序号
    updatePointIndexes()
  }
}

/**
 * 下移路径点
 */
const handleMoveDown = (row, index) => {
  if (index < pathForm.points.length - 1) {
    // 交换位置
    const temp = pathForm.points[index]
    pathForm.points[index] = pathForm.points[index + 1]
    pathForm.points[index + 1] = temp
    
    // 更新序号
    updatePointIndexes()
  }
}

/**
 * 处理设备选择变化
 */
const handleDeviceSelect = (value, row) => {
  // 查找对应的modelId
  const selectedDevice = deviceList.value.find(device => device.value === value)
  if (selectedDevice) {
    row.modelId = selectedDevice.value // 设备的value已经是modelId
  }
}

/**
 * 更新路径点序号
 */
const updatePointIndexes = () => {
  pathForm.points.forEach((point, index) => {
    point.index = index + 1
  })
}

/**
 * 处理排序变化
 */
const handleSortChange = ({ column, prop, order }) => {
  if (prop === 'index') {
    // 按序号排序
    pathForm.points.sort((a, b) => {
      return order === 'ascending' ? a.index - b.index : b.index - a.index
    })
    
    // 更新序号
    updatePointIndexes()
  }
}

/**
 * 验证路径点
 */
const validatePoints = () => {
  // 检查是否有空设备名称
  for (let i = 0; i < pathForm.points.length; i++) {
    const point = pathForm.points[i]
    if (!point.deviceName || point.deviceName.trim() === '') {
      ElMessage.warning(`请为第${point.index}个路径点选择设备`)
      return false
    }
  }
  return true
}

/**
 * 处理保存
 */
const handleSave = async () => {
  // 验证表单
  if (!pathFormRef.value) {
    return
  }
  
  try {
    await pathFormRef.value.validate()
    
    // 验证路径点
    if (!validatePoints()) {
      return
    }
    
    loading.value = true
    
    // 准备保存数据
    const saveData = {
      ...pathForm,
      pointCount: pathForm.points.length,
      updateTime: new Date().toLocaleString('zh-CN')
    }
    
    if (!isEdit.value) {
      saveData.createTime = saveData.updateTime
    }
    
    // 模拟API调用延迟
    await new Promise(resolve => setTimeout(resolve, 500))
    
    // 将路径点信息添加到导航系统
    console.log(map.value)
    console.log(pathForm.points)
    if (map.value && pathForm.points.length > 0) {
      // 先清空现有路径
      //stopNavi()
      // 按顺序添加所有路径点的modelId到导航系统
      pathForm.points.forEach(point => {
        if (point.modelId) {
          addPathId(point.modelId)
        }
      })
      // 如果路径点数量足够，可以自动启动导航
      if (pathForm.points.length >= 2) {
        // 这里可以根据需要决定是否自动启动导航
        // startNavi()
      }
    }
    
    // 触发保存事件
    emit('save', saveData)
    
    ElMessage.success('保存成功')
    dialogVisible.value = false
  } catch (error) {
    console.error('保存失败:', error)
    ElMessage.error('保存失败，请重试')
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
/**
 * 巡检路径编辑组件样式
 */
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

/* 标题样式 */
.text-lg {
  font-size: 18px;
}

.font-medium {
  font-weight: 500;
}

.text-blue-300 {
  color: #91d5ff;
}

.text-blue-200 {
  color: #b6dfff;
}

/* 间距样式 */
.mb-4 {
  margin-bottom: 16px;
}

.mb-6 {
  margin-bottom: 24px;
}

/* 网格布局 */
.grid {
  display: grid;
}

.grid-cols-1 {
  grid-template-columns: 1fr;
}

.md\:grid-cols-2 {
  grid-template-columns: 1fr 1fr;
}

.gap-4 {
  gap: 16px;
}

/* 地图容器样式 */
.path-map-container {
  height: 400px;
  width: 100%;
  position: relative;
  overflow: hidden;
}

/* 确保Map组件在容器内正确显示 */
:deep(.path-map-container .wrapper) {
  width: 100% !important;
  height: 100% !important;
  position: relative;
}

:deep(.path-map-container #mapContainer) {
  width: 100% !important;
  height: 100% !important;
  position: relative;
}

/* 地图提示样式 */
.map-tip {
  position: absolute;
  top: 10px;
  right: 10px;
  z-index: 10;
}

/* 表单样式 */
:deep(.el-form) {
  background: transparent !important;
}

:deep(.el-form-item__label) {
  color: #68c9ff !important;
  font-weight: 500;
}

/* 输入框样式 */
:deep(.el-input__wrapper) {
  background: rgba(255, 255, 255, 0.05) !important;
  border-color: #68c9ff !important;
}

:deep(.el-input__inner) {
  color: #b6dfff !important;
  background: transparent !important;
}

/* 表格样式 */
:deep(.el-table) {
  background: rgba(12, 43, 77, 0.7) !important;
  border: 1px solid #68c9ff;
  backdrop-filter: blur(5px);
}

:deep(.el-table__header-wrapper th) {
  background: rgba(20, 60, 110, 0.8) !important;
  color: #68c9ff !important;
  border-bottom: 1px solid #68c9ff !important;
}

:deep(.el-table__body-wrapper tr) {
  background: transparent !important;
}

:deep(.el-table__body-wrapper tr:nth-child(even)) {
  background: rgba(20, 60, 110, 0.3) !important;
}

:deep(.el-table__body-wrapper tr:hover) {
  background: rgba(104, 201, 255, 0.2) !important;
}

:deep(.el-table__body-wrapper td) {
  color: #b6dfff !important;
  border-bottom: 1px solid rgba(104, 201, 255, 0.3) !important;
}
</style>