<template>
  <div 
    v-if="visible" 
    class="bottom-inspector is-editing"
    :style="{ height: currentHeight }"
    @keyup.esc="handleEscKey"
    tabindex="-1"
  >
    <!-- 顶部居中拖拽条 -->
    <div class="drag-section">
      <div 
        class="drag-handle" 
        @mousedown="startResize"
        @dblclick="resetHeight"
      ></div>
    </div>
    
    <!-- 头部标题栏 -->
    <div class="inspector-header">
      <div class="header-left">
        <div class="title">当前元素参数</div>
        <div v-if="elementData" class="element-info">
          <el-tag size="mini" :type="getElementTypeTag(elementData.type)">
            {{ getElementTypeName(elementData.type) }}
          </el-tag>
          <span class="element-id">{{ elementData.id }}</span>
          <span v-if="elementData.name" class="element-name">{{ elementData.name }}</span>
        </div>
      </div>
      <div class="header-right">
        <!-- 快速操作 -->
        <div class="quick-actions">
          <el-tooltip content="定位到元素" placement="top">
            <el-button 
              size="mini" 
              type="text" 
              icon="el-icon-location"
              @click="locateElement"
            />
          </el-tooltip>
        </div>
        <!-- 操作按钮 -->
        <div class="action-buttons">
          <el-button 
            size="mini"
            @click="handleCancel"
          >
            取消
          </el-button>
          <el-button 
            size="mini" 
            type="primary"
            :loading="saving"
            @click="handleSave"
          >
            保存
          </el-button>
        </div>
      </div>
    </div>

    <!-- 内容区域 -->
    <div class="bottom-inspector__body" ref="contentRef">
      <!-- 骨架屏 -->
      <div v-if="loading" class="skeleton-content">
        <div class="skeleton-section">
          <div class="skeleton-title"></div>
          <div class="skeleton-field"></div>
          <div class="skeleton-field"></div>
          <div class="skeleton-field"></div>
        </div>
        <div class="skeleton-section">
          <div class="skeleton-title"></div>
          <div class="skeleton-field"></div>
          <div class="skeleton-field"></div>
        </div>
      </div>

      <!-- 表单内容：左右两列布局 -->
      <div v-else-if="elementData" class="inspector-sections">
        <!-- 基础参数卡片 -->
        <section class="inspector-card inspector-card--basic">
          <div class="card-header">
            <div class="section-header">
              <span class="section-title">基础参数</span>
            </div>
          </div>
          <div class="card-body">
            <el-form 
              ref="basicFormRef"
              :model="formData"
              :rules="formRules"
              label-width="100px"
              size="small"
              class="inspector-form"
            >
              <el-form-item label="元素ID" prop="id">
                <el-input 
                  v-model="formData.id" 
                  readonly
                  size="small"
                />
              </el-form-item>
              <el-form-item label="元素名称" prop="name">
                <el-input 
                  v-model="formData.name" 
                  placeholder="请输入元素名称"
                  size="small"
                />
              </el-form-item>
              
              <!-- 坐标信息 -->
              <template v-if="hasCoordinates">
                <el-form-item label="X坐标(m)" prop="x">
                  <el-input-number
                    v-model="formData.x"
                    :precision="3"
                    :step="coordinateStep"
                    controls-position="right"
                    size="small"
                  />
                </el-form-item>
                <el-form-item label="Y坐标(m)" prop="y">
                  <el-input-number
                    v-model="formData.y"
                    :precision="3"
                    :step="coordinateStep"
                    controls-position="right"
                    size="small"
                  />
                </el-form-item>
                <el-form-item v-if="formData.z !== undefined" label="Z坐标(m)" prop="z">
                  <el-input-number
                    v-model="formData.z"
                    :precision="3"
                    :step="coordinateStep"
                    controls-position="right"
                    size="small"
                  />
                </el-form-item>
              </template>

              <!-- 线段/曲线基础参数 -->
              <template v-if="elementData.type === 'LineString'">
                <el-form-item label="起点ID" prop="startid">
                  <el-input 
                    v-model="formData.startid" 
                    :readonly="true"
                    size="small"
                  />
                </el-form-item>
                <el-form-item label="终点ID" prop="endid">
                  <el-input 
                    v-model="formData.endid" 
                    :readonly="true"
                    size="small"
                  />
                </el-form-item>
                <el-form-item label="方向控制" prop="directList">
                  <div class="direction-controls">
                    <el-checkbox
                      v-model="formData.directList[0]"
                      size="small"
                    >
                      起点→终点(前行)
                    </el-checkbox>
                    <el-checkbox
                      v-model="formData.directList[1]"
                      size="small"
                    >
                      起点→终点(倒行)
                    </el-checkbox>
                    <el-checkbox
                      v-model="formData.directList[2]"
                      size="small"
                    >
                      终点→起点(前行)
                    </el-checkbox>
                    <el-checkbox
                      v-model="formData.directList[3]"
                      size="small"
                    >
                      终点→起点(倒行)
                    </el-checkbox>
                  </div>
                </el-form-item>
                <el-form-item label="最大限速(m/s)" prop="maxspeed">
                  <el-input-number
                    v-model="formData.maxspeed"
                    :min="0"
                    :max="20"
                    :precision="1"
                    :step="0.5"
                    controls-position="right"
                    size="small"
                  />
                </el-form-item>
                <el-form-item label="最小限速(m/s)" prop="minspeed">
                  <el-input-number
                    v-model="formData.minspeed"
                    :min="0"
                    :precision="1"
                    :step="0.5"
                    controls-position="right"
                    size="small"
                  />
                </el-form-item>
                <el-form-item label="车道宽度(m)" prop="lanewidth">
                  <el-input-number
                    v-model="formData.lanewidth"
                    :min="0.1"
                    :precision="2"
                    :step="0.1"
                    controls-position="right"
                    size="small"
                  />
                </el-form-item>
                <el-form-item label="左车道数" prop="leftlanenum">
                  <el-input-number
                    v-model="formData.leftlanenum"
                    :min="0"
                    controls-position="right"
                    size="small"
                  />
                </el-form-item>
                <el-form-item label="右车道数" prop="rightlanenum">
                  <el-input-number
                    v-model="formData.rightlanenum"
                    :min="0"
                    controls-position="right"
                    size="small"
                  />
                </el-form-item>
              </template>
            </el-form>
          </div>
        </section>

        <!-- 高级参数卡片 -->
        <section class="inspector-card inspector-card--advanced">
          <div class="card-header">
            <div class="section-header">
              <span class="section-title">高级参数</span>
            </div>
          </div>
          <div class="card-body">
            <el-form 
              ref="advancedFormRef"
              :model="formData"
              :rules="formRules"
              label-width="100px"
              size="small"
              class="inspector-form"
            >
              <!-- 点位参数 -->
              <template v-if="elementData.type === 'Point'">
                <el-form-item label="航偏角(rad)" prop="yaw">
                  <el-input-number
                    v-model="formData.yaw"
                    :precision="3"
                    :step="0.1"
                    controls-position="right"
                    size="small"
                  />
                </el-form-item>
                <el-form-item label="航偏角使能" prop="isyawfix">
                  <el-switch
                    v-model="formData.isyawfix"
                    size="small"
                  />
                </el-form-item>
              </template>

              <!-- 线段/曲线高级参数 -->
              <template v-else-if="elementData.type === 'LineString'">
                <el-form-item label="避障方式" prop="obstype">
                  <el-select
                    v-model="formData.obstype"
                    size="small"
                  >
                    <el-option label="停车等待" :value="0" />
                    <el-option label="车道绕障" :value="1" />
                    <el-option label="路网绕障" :value="2" />
                  </el-select>
                </el-form-item>
                <el-form-item label="正向前移(m)" prop="s2eforward">
                  <el-input-number
                    v-model="formData.s2eforward"
                    :precision="2"
                    :step="0.1"
                    controls-position="right"
                    size="small"
                  />
                </el-form-item>
                <el-form-item label="逆向前移(m)" prop="e2sforward">
                  <el-input-number
                    v-model="formData.e2sforward"
                    :precision="2"
                    :step="0.1"
                    controls-position="right"
                    size="small"
                  />
                </el-form-item>
              </template>

              <!-- 多边形参数 -->
              <template v-else-if="elementData.type === 'Polygon'">
                <el-form-item label="区域类型" prop="type">
                  <el-select
                    v-model="formData.type"
                    placeholder="请选择区域类型"
                    size="small"
                  >
                    <el-option label="隔离区域" :value="0" />
                    <el-option label="装饰区域" :value="1" />
                    <el-option label="禁行区域" :value="2" />
                    <el-option label="会车管制区" :value="3" />
                    <el-option label="道闸管控区" :value="4" />
                    <el-option label="GPS定位区" :value="11" />
                    <el-option label="动态禁行区" :value="22" />
                  </el-select>
                </el-form-item>
                <el-form-item label="填充颜色" prop="color">
                  <el-color-picker
                    v-model="formData.color"
                    size="small"
                  />
                </el-form-item>
                <el-form-item label="透明度" prop="transparent">
                  <el-slider
                    v-model="formData.transparent"
                    :min="0"
                    :max="255"
                    :step="5"
                    size="small"
                  />
                </el-form-item>
              </template>
            </el-form>
          </div>
        </section>
      </div>

      <!-- 空状态 -->
      <div v-else class="empty-state">
        <i class="el-icon-info"></i>
        <p>请选择一个元素查看其参数信息</p>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'BottomInspector',
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    mode: {
      type: String,
      default: 'view'
    },
    data: {
      type: Object,
      default: null
    },
    loading: {
      type: Boolean,
      default: false
    }
  },
  emits: ['edit', 'save', 'cancel', 'close', 'height-change', 'locate'],
  data() {
    return {
      currentHeight: '20vh',
      minHeight: 180,
      maxHeight: '50vh',
      isResizing: false,
      startY: 0,
      startHeight: 0,
      
      formData: {},
      originalData: {},
      
      formRules: {
        x: [
          { required: true, message: '请输入X坐标', trigger: 'change' }
        ],
        y: [
          { required: true, message: '请输入Y坐标', trigger: 'change' }
        ]
      },
      
      coordinateStep: 0.1,
      
      saving: false,
      
      hasUnsavedChanges: false
    }
  },
  computed: {
    elementData() {
      return this.data
    },
    hasCoordinates() {
      if (!this.elementData) return false
      return this.elementData.type === 'Point' || 
             this.elementData.position || 
             (this.elementData.x !== undefined && this.elementData.y !== undefined)
    }
  },
  watch: {
    visible(newVal) {
      if (newVal) {
        this.$nextTick(() => {
          this.$el?.focus()
        })
      }
    },
    data: {
      handler(newData) {
        if (newData) {
          this.initFormData()
        }
      },
      immediate: true,
      deep: true
    },
    mode(newMode) {
      if (newMode === 'edit') {
        this.createSnapshot()
      }
    },
    formData: {
      handler() {
        if (this.mode === 'edit') {
          this.checkUnsavedChanges()
        }
      },
      deep: true
    }
  },
  mounted() {
    document.addEventListener('mousemove', this.handleMouseMove)
    document.addEventListener('mouseup', this.handleMouseUp)
  },
  beforeDestroy() {
    document.removeEventListener('mousemove', this.handleMouseMove)
    document.removeEventListener('mouseup', this.handleMouseUp)
  },
  methods: {
    startResize(event) {
      this.isResizing = true
      this.startY = event.clientY
      const currentPx = this.$el.offsetHeight
      this.startHeight = currentPx
      event.preventDefault()
    },
    
    handleMouseMove(event) {
      if (!this.isResizing) return
      
      const deltaY = this.startY - event.clientY
      let next = this.startHeight + deltaY
      const max = Math.round(window.innerHeight * 0.5)
      const min = 180
      next = Math.max(min, Math.min(max, next))
      
      this.currentHeight = `${next}px`
    },
    
    handleMouseUp() {
      if (this.isResizing) {
        this.isResizing = false
        this.$emit('height-change', this.currentHeight)
      }
    },
    
    resetHeight() {
      this.currentHeight = '20vh'
      this.$emit('height-change', this.currentHeight)
    },
    
    initFormData() {
      if (!this.elementData) {
        this.formData = {}
        return
      }
      
      const data = { ...this.elementData }
      
      if (data.position && Array.isArray(data.position)) {
        data.x = data.position[0]
        data.y = data.position[1]
        data.z = data.position[2] || 0
      }
      
      if (data.direct !== undefined && data.type === 'LineString') {
        const value = data.direct - 100 || 0
        const binary = value.toString(2).padStart(4, '0')
        data.directList = [
          binary[0] === '1',
          binary[1] === '1', 
          binary[2] === '1',
          binary[3] === '1'
        ]
      }
      
      if (this.elementData.type === 'Polygon') {
        if (data.type === undefined || data.type === 'Polygon') {
          data.type = 1
        }
      }
      
      this.formData = { ...data }
      this.hasUnsavedChanges = false
    },
    
    createSnapshot() {
      this.originalData = JSON.parse(JSON.stringify(this.formData))
    },
    
    restoreSnapshot() {
      if (this.originalData) {
        this.formData = JSON.parse(JSON.stringify(this.originalData))
        this.hasUnsavedChanges = false
      }
    },
    
    checkUnsavedChanges() {
      if (!this.originalData) return
      
      this.hasUnsavedChanges = JSON.stringify(this.formData) !== JSON.stringify(this.originalData)
    },
    
    handleSave() {
      const basicFormValid = this.$refs.basicFormRef ? this.$refs.basicFormRef.validate() : Promise.resolve(true)
      const advancedFormValid = this.$refs.advancedFormRef ? this.$refs.advancedFormRef.validate() : Promise.resolve(true)
      
      Promise.all([basicFormValid, advancedFormValid]).then((results) => {
        const allValid = results.every(valid => valid === true)
        
        if (allValid) {
          this.saving = true
          
          const saveData = { ...this.formData }
          
          if (saveData.directList && this.elementData.type === 'LineString') {
            const binaryString = saveData.directList.map(bit => (bit ? '1' : '0')).join('')
            const value = parseInt(binaryString, 2)
            saveData.direct = value + 100
            delete saveData.directList
          }
          
          if (saveData.x !== undefined && saveData.y !== undefined) {
            saveData.position = [saveData.x, saveData.y, saveData.z || 0]
          }
          
          this.$emit('save', saveData)
          
          this.saving = false
          this.hasUnsavedChanges = false
        } else {
          this.$message.error('请检查表单数据')
        }
      }).catch(() => {
        this.$message.error('表单验证失败')
      })
    },
    
    handleCancel() {
      if (this.hasUnsavedChanges) {
        this.$confirm('是否放弃未保存的更改？', '确认', {
          confirmButtonText: '放弃更改',
          cancelButtonText: '继续编辑',
          type: 'warning'
        }).then(() => {
          this.restoreSnapshot()
          this.$emit('cancel')
        })
      } else {
        this.$emit('cancel')
      }
    },
    
    handleClose() {
      if (this.mode === 'edit' && this.hasUnsavedChanges) {
        this.$confirm('当前有未保存的更改，是否放弃？', '确认关闭', {
          confirmButtonText: '放弃更改',
          cancelButtonText: '继续编辑',
          type: 'warning'
        }).then(() => {
          this.$emit('close')
        })
      } else {
        this.$emit('close')
      }
    },
    
    handleEscKey() {
      if (!this.hasUnsavedChanges) {
        this.handleClose()
      }
    },
    
    locateElement() {
      this.$emit('locate', this.elementData)
      this.$message.success(`已定位到元素 ${this.elementData.id}`)
    },
    
    getElementTypeTag(type) {
      const typeMap = {
        'Point': 'success',
        'LineString': 'primary', 
        'Polygon': 'warning'
      }
      return typeMap[type] || 'info'
    },
    
    getElementTypeName(type) {
      const typeMap = {
        'Point': '点',
        'LineString': '线',
        'Polygon': '面'
      }
      return typeMap[type] || '未知'
    }
  }
}
</script>

<style lang="scss" scoped>
.bottom-inspector {
  position: absolute;
  left: var(--left-safe);
  width: calc(100% - var(--left-safe) - var(--right-safe));
  bottom: 0;
  
  min-height: 280px;
  height: 20vh;
  max-height: 50vh;
  background: #fff;
  border-radius: 12px 12px 0 0;
  box-shadow: 0 8px 28px rgba(0,0,0,0.12);
  display: flex;
  flex-direction: column;
  box-sizing: border-box;
  
  z-index: 9;
  pointer-events: auto;
  overflow: hidden;

  &:focus {
    outline: none;
  }
  
  &.is-editing {
    border-top-color: #409eff;
    box-shadow: 0 8px 32px rgba(64, 158, 255, 0.2);
  }
}

.drag-section {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 8px 0;
  background: #fff;
  flex-shrink: 0;
  
  .drag-handle {
    width: 56px;
    height: 4px;
    border-radius: 2px;
    background: rgba(0,0,0,.18);
    cursor: ns-resize;
    transition: background-color 0.2s ease;
    
    &:hover {
      background: rgba(0,0,0,.28);
    }
  }
}

.inspector-header {
  flex: 0 0 auto;
  height: 44px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 16px;
  border-bottom: 1px solid #e4e7ed;
  background: #fafbfc;
  box-sizing: border-box;
  
  .header-left {
    display: flex;
    align-items: center;
    flex: 1;
    
    .title {
      font-size: 16px;
      font-weight: 600;
      color: #303133;
      margin-right: 16px;
    }
    
    .element-info {
      display: flex;
      align-items: center;
      gap: 8px;
      color: #606266;
      font-size: 14px;
      
      .element-id {
        font-family: 'Monaco', 'Menlo', monospace;
        background: #f0f2f5;
        padding: 2px 6px;
        border-radius: 4px;
        font-size: 12px;
      }
      
      .element-name {
        color: #909399;
      }
    }
  }
  
  .header-right {
    display: flex;
    align-items: center;
    gap: 8px;
  }
  
  .quick-actions {
    display: flex;
    align-items: center;
    gap: 4px;
    margin-right: 8px;
    padding-right: 8px;
    border-right: 1px solid #e4e7ed;
  }
  
  .action-buttons {
    display: flex;
    align-items: center;
    gap: 8px;
  }
}

.bottom-inspector__body {
  flex: 1 1 auto;
  overflow-y: auto;
  padding: 12px 16px;
  box-sizing: border-box;
}

.inspector-sections {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 16px;
  align-items: start;
}

.inspector-card {
  background: #fff;
  border: 1px solid #eef0f3;
  border-radius: 10px;
  overflow: hidden;
}

.inspector-card .card-header {
  position: sticky; 
  top: 0;
  background: #f8fafc; 
  z-index: 1;
  padding: 10px 12px; 
  border-bottom: 1px solid #eef0f3;
}

.inspector-card .card-body {
  padding: 12px;
}

.inspector-card :deep(.el-form),
.inspector-card :deep(.el-form-item),
.inspector-card :deep(.el-input),
.inspector-card :deep(.el-input__inner) { 
  width: 100%; 
}

.bottom-inspector .el-form,
.bottom-inspector .el-form-item,
.bottom-inspector .el-input,
.bottom-inspector .el-input__inner {
  width: 100%;
  max-width: 100%;
}

.inspector-form {
  ::v-deep .el-form-item {
    margin-bottom: 12px;
    
    &:last-child {
      margin-bottom: 0;
    }
    
    .el-form-item__label {
      font-size: 13px;
      line-height: 1.4;
      padding-bottom: 4px;
    }
    
    .el-form-item__content {
      line-height: 1.6;
    }
  }
  
  .direction-controls {
    display: flex;
    flex-direction: column;
    gap: 8px;
    
    .el-checkbox {
      margin-right: 0;
    }
  }
}

.skeleton-content {
  .skeleton-section {
    margin-bottom: 24px;
    
    .skeleton-title {
      height: 16px;
      background: linear-gradient(90deg, #f0f2f5 25%, #e6e8eb 50%, #f0f2f5 75%);
      background-size: 200% 100%;
      animation: skeleton-loading 1.5s infinite;
      border-radius: 4px;
      margin-bottom: 16px;
      width: 120px;
    }
    
    .skeleton-field {
      height: 32px;
      background: linear-gradient(90deg, #f0f2f5 25%, #e6e8eb 50%, #f0f2f5 75%);
      background-size: 200% 100%;
      animation: skeleton-loading 1.5s infinite;
      border-radius: 4px;
      margin-bottom: 12px;
      
      &:nth-child(2) { animation-delay: 0.1s; }
      &:nth-child(3) { animation-delay: 0.2s; }
      &:nth-child(4) { animation-delay: 0.3s; }
    }
  }
}

@keyframes skeleton-loading {
  0% {
    background-position: 200% 0;
  }
  100% {
    background-position: -200% 0;
  }
}

.empty-state {
  text-align: center;
  padding: 40px 20px;
  color: #909399;
  
  i {
    font-size: 48px;
    margin-bottom: 16px;
    display: block;
    color: #c0c4cc;
  }
  
  p {
    font-size: 14px;
    margin: 0;
  }
}

@media (max-width: 992px) {
  .bottom-inspector {
    left: 12px;
    width: calc(100% - 24px);
    
    .inspector-header {
      .header-left .title {
        font-size: 14px;
        margin-right: 12px;
      }
      
      .element-info {
        display: none;
      }
      
      .quick-actions {
        display: none;
      }
    }
    
    .bottom-inspector__body {
      padding: 12px;
    }
    
    .inspector-sections {
      grid-template-columns: 1fr;
      gap: 12px;
    }
    
    .inspector-card .card-body {
      padding: 10px;
    }
    
    .inspector-form {
      ::v-deep .el-form-item .el-form-item__label {
        font-size: 12px;
      }
    }
  }
}
</style>
