<template>
  <div class="map-toolbar" :style="toolbarStyle">
    <!-- 内置工具或自定义工具 -->
    <template v-if="preset !== 'custom' || tools.length > 0">
      <!-- 预设或自定义工具模式 -->
      <div v-for="(tool, index) in visibleTools" :key="tool.key" class="toolbar-item-wrapper">
        <!-- 按钮类型 -->
        <div v-if="tool.type === 'btn'" class="toolbar-item">
          <el-tooltip
            :content="getToolTooltip(tool)"
            :placement="vertical ? 'right' : 'bottom'"
          >
            <el-button
              :size="buttonSize"
              :type="tool.buttonType || 'default'"
              circle
              :disabled="tool.disabled || isToolDisabled(tool.key)"
              :class="[
                'toolbar-btn',
                {
                  'primary-btn': tool.buttonType === 'primary',
                  'active': selectedKey === tool.key,
                  'has-custom-icon': tool.customIcon
                }
              ]"
              @click="handleToolClick(tool)"
            >
              <!-- Element Plus 图标 -->
              <template v-if="!tool.customIcon && tool.icon">
                <el-icon>
                  <component :is="getIconComponent(tool.icon)" />
                </el-icon>
              </template>

              <!-- 自定义图标 -->
              <template v-else-if="tool.customIcon">
                <!-- 选择工具图标 -->
                <svg v-if="tool.customIcon === 'select'" viewBox="0 0 24 24" class="custom-icon">
                  <g transform="scale(0.024)">
                    <path d="M439.04 141.6192c17.5104 2.5088 29.6448 18.7392 27.136 36.1984l-12.2368 85.504a32 32 0 0 1-63.3344-9.0112l12.2368-85.504a32 32 0 0 1 36.1984-27.136zM783.36 163.84h-194.56a30.72 30.72 0 0 0 0 61.44h194.56q10.24 0 10.24 10.24v204.8a30.72 30.72 0 1 0 61.44 0v-204.8q0-29.696-20.992-50.688-20.992-20.992-50.688-20.992zM326.7072 252.672a32 32 0 0 1-50.5856 39.2192L221.184 220.9792a32 32 0 0 1 50.5856-39.2192L326.656 252.672z m-72.3456 95.232a32 32 0 0 1-9.0624 63.3856L159.744 399.0528a32 32 0 0 1 9.0624-63.3344l85.504 12.2368z m607.6416 217.856L422.8096 372.5312c-19.0464-8.2432-36.608 2.56-29.3888 24.32l157.184 472.7808c5.7344 17.5616 16.896 18.5344 24.9856 2.1504q40.192-83.2 75.9296-138.3424a10.0352 10.0352 0 0 1 16.0768-0.9728l98.9184 114.5344a26.7264 26.7264 0 0 0 38.912 2.2528l26.6752-25.4464a30.208 30.208 0 0 0 1.536-40.96l-99.6864-115.456a10.0864 10.0864 0 0 1 2.5088-15.36q52.48-30.6176 125.5424-60.8256c16.384-6.7584 16.384-18.2272 0-25.4464zM235.52 870.4H409.6a30.72 30.72 0 0 0 0-61.44H235.52q-10.24 0-10.24-10.24v-276.48a30.72 30.72 0 0 0-61.44 0v276.48q0 29.696 20.992 50.688 20.992 20.992 50.688 20.992z"
                          fill="currentColor"/>
                  </g>
                </svg>

                <!-- 绘制点图标 -->
                <svg v-else-if="tool.customIcon === 'point'" viewBox="0 0 24 24" class="custom-icon">
                  <circle cx="12" cy="12" r="4" fill="currentColor"/>
                  <circle cx="12" cy="12" r="8" fill="none" stroke="currentColor" stroke-width="1.5" stroke-dasharray="2,2" opacity="0.6"/>
                </svg>

                <!-- 绘制线图标 -->
                <svg v-else-if="tool.customIcon === 'line'" viewBox="0 0 24 24" class="custom-icon">
                  <path d="M4 20L20 4" stroke="currentColor" stroke-width="2" stroke-linecap="round"/>
                  <circle cx="4" cy="20" r="2" fill="currentColor"/>
                  <circle cx="20" cy="4" r="2" fill="currentColor"/>
                </svg>

                <!-- 绘制曲线图标 -->
                <svg v-else-if="tool.customIcon === 'curve'" viewBox="0 0 24 24" class="custom-icon">
                  <path d="M3 20C3 20 7 4 12 12C17 20 21 4 21 4" stroke="currentColor" stroke-width="2" stroke-linecap="round" fill="none"/>
                  <circle cx="3" cy="20" r="2" fill="currentColor"/>
                  <circle cx="21" cy="4" r="2" fill="currentColor"/>
                </svg>

                <!-- 绘制区域图标 -->
                <svg v-else-if="tool.customIcon === 'polygon'" viewBox="0 0 24 24" class="custom-icon">
                  <path d="M12 2L22 8.5L18 20H6L2 8.5L12 2Z" stroke="currentColor" stroke-width="1.5" fill="none"/>
                  <circle cx="12" cy="2" r="1.5" fill="currentColor"/>
                  <circle cx="22" cy="8.5" r="1.5" fill="currentColor"/>
                  <circle cx="18" cy="20" r="1.5" fill="currentColor"/>
                  <circle cx="6" cy="20" r="1.5" fill="currentColor"/>
                  <circle cx="2" cy="8.5" r="1.5" fill="currentColor"/>
                </svg>
              </template>
            </el-button>
          </el-tooltip>
        </div>
        <!-- 分隔线类型 -->
        <div
          v-else-if="tool.type === 'divider'"
          class="toolbar-divider"
          aria-hidden="true"
        ></div>
      </div>
    </template>

    <template v-else>
      <!-- 默认内置工具模式（兼容原有标定页） -->
      <el-tooltip content="放大" :placement="vertical ? 'right' : 'bottom'">
        <el-button
          :size="buttonSize"
          circle
          @click="zoomIn"
          class="toolbar-btn"
        >
          <el-icon><Plus /></el-icon>
        </el-button>
      </el-tooltip>

      <el-tooltip content="缩小" :placement="vertical ? 'right' : 'bottom'">
        <el-button
          :size="buttonSize"
          circle
          @click="zoomOut"
          class="toolbar-btn"
        >
          <el-icon><Minus /></el-icon>
        </el-button>
      </el-tooltip>

      <el-tooltip content="居中到机器人" :placement="vertical ? 'right' : 'bottom'">
        <el-button
          :size="buttonSize"
          circle
          @click="centerToRobot"
          :disabled="!hasRobotPosition"
          class="toolbar-btn"
        >
          <el-icon><LocationFilled /></el-icon>
        </el-button>
      </el-tooltip>

      <el-tooltip :content="isFullscreen ? '退出全屏' : '全屏'" :placement="vertical ? 'right' : 'bottom'">
        <el-button
          :size="buttonSize"
          circle
          @click="toggleFullscreen"
          class="toolbar-btn"
        >
          <el-icon><FullScreen /></el-icon>
        </el-button>
      </el-tooltip>

      <!-- 分割线 -->
      <div class="toolbar-divider"></div>

      <!-- 主要操作按钮 -->
      <el-tooltip content="添加标定点" :placement="vertical ? 'right' : 'bottom'">
        <el-button
          type="primary"
          :size="buttonSize"
          circle
          @click="addCalibrationPoint"
          class="toolbar-btn primary-btn"
          :disabled="!canAddCalibration"
        >
          <el-icon><CirclePlusFilled /></el-icon>
        </el-button>
      </el-tooltip>
    </template>
  </div>
</template>

<script setup>
import { computed } from 'vue'
import { ElMessageBox, ElIcon } from 'element-plus'
import {
  Plus,
  Minus,
  LocationFilled,
  FullScreen,
  CirclePlusFilled,
  Refresh,
  SwitchButton,
  Position,
  Aim,
  Check
} from '@element-plus/icons-vue'

const props = defineProps({
  // 预设配置
  preset: {
    type: String,
    default: 'custom',
    validator: value => ['custom', 'calibration', 'nav', 'edit'].includes(value)
  },
  // 自定义工具配置
  tools: {
    type: Array,
    default: () => []
  },
  // 布局方向
  vertical: {
    type: Boolean,
    default: true
  },
  // 按钮尺寸
  size: {
    type: String,
    default: 'md',
    validator: value => ['sm', 'md', 'lg'].includes(value)
  },
  // 当前选中的工具
  selectedKey: {
    type: String,
    default: ''
  },
  // 禁用的工具列表
  disabledKeys: {
    type: Array,
    default: () => []
  },
  // 位置偏移
  offset: {
    type: Object,
    default: () => ({ top: '16px', left: '16px' })
  },

  // === 兼容原标定页的props ===
  canAddCalibration: {
    type: Boolean,
    default: true
  },
  hasRobotPosition: {
    type: Boolean,
    default: false
  },
  isFullscreen: {
    type: Boolean,
    default: false
  },
  showAdvanced: {
    type: Boolean,
    default: false
  },
  // 连接状态
  isConnected: {
    type: Boolean,
    default: true
  },
  // 系统忙碌状态
  isBusy: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits([
  'click',
  'zoom-in',
  'zoom-out',
  'center-robot',
  'center-to-robot',
  'toggle-fullscreen',
  'add-calibration-point',
  'mode-change',
  'save',
  'reset-view',
  'toggle-measure-tool',
  'confirm-init',
  'confirm-reboot',
  'confirm-stop'
])

// 图标映射表
const iconMap = {
  'el-icon-plus': Plus,
  'el-icon-minus': Minus,
  'el-icon-location': LocationFilled,
  'el-icon-full-screen': FullScreen,
  'el-icon-aim': Aim,
  'el-icon-circle-plus': CirclePlusFilled,
  'el-icon-refresh': Refresh,
  'el-icon-switch-button': SwitchButton,
  'el-icon-position': Position,
  'el-icon-check': Check
}

// 获取图标组件
function getIconComponent(iconName) {
  return iconMap[iconName] || iconName
}

// 当前使用的工具配置
const currentTools = computed(() => {
  if (props.preset === 'custom' && props.tools.length > 0) {
    return props.tools
  }
  return getPresetTools()
})

// 可见的工具列表
const visibleTools = computed(() => {
  return currentTools.value.filter(tool => tool.visible !== false)
})

// 按钮尺寸映射
const buttonSize = computed(() => {
  const sizeMap = {
    'sm': 'small',
    'md': 'small',
    'lg': 'default'
  }
  return sizeMap[props.size] || 'small'
})

// 工具栏样式
const toolbarStyle = computed(() => {
  return {
    top: props.offset.top,
    left: props.offset.left,
    right: props.offset.right,
    bottom: props.offset.bottom,
    flexDirection: props.vertical ? 'column' : 'row'
  }
})

// 获取预设工具配置
function getPresetTools() {
  const presets = {
    calibration: [
      { key: 'zoom-in', type: 'btn', icon: 'el-icon-plus', tooltip: '放大' },
      { key: 'zoom-out', type: 'btn', icon: 'el-icon-minus', tooltip: '缩小' },
      { key: 'center-robot', type: 'btn', icon: 'el-icon-location', tooltip: '居中到机器人' },
      { key: 'toggle-fullscreen', type: 'btn', icon: props.isFullscreen ? 'el-icon-aim' : 'el-icon-full-screen', tooltip: props.isFullscreen ? '退出全屏' : '进入全屏' },
      { key: 'divider-1', type: 'divider' },
      { key: 'add-calibration', type: 'btn', icon: 'el-icon-circle-plus', tooltip: '添加标定点', buttonType: 'primary' }
    ],
    nav: [
      { key: 'zoom-in', type: 'btn', icon: 'el-icon-plus', tooltip: '放大' },
      { key: 'zoom-out', type: 'btn', icon: 'el-icon-minus', tooltip: '缩小' },
      { key: 'center-robot', type: 'btn', icon: 'el-icon-location', tooltip: '居中到机器人' },
      { key: 'toggle-fullscreen', type: 'btn', icon: props.isFullscreen ? 'el-icon-aim' : 'el-icon-full-screen', tooltip: props.isFullscreen ? '退出全屏' : '进入全屏' },
      { key: 'divider-1', type: 'divider' },
      { key: 'init-pose', type: 'btn', icon: 'el-icon-position', tooltip: '初始化' },
      { key: 'reboot', type: 'btn', icon: 'el-icon-refresh', tooltip: '重启' },
      { key: 'emergency-stop', type: 'btn', icon: 'el-icon-switch-button', tooltip: '结束/急停' }
    ],
    edit: [
      { key: 'zoom-in', type: 'btn', icon: 'el-icon-plus', tooltip: '放大' },
      { key: 'zoom-out', type: 'btn', icon: 'el-icon-minus', tooltip: '缩小' },
      { key: 'center-robot', type: 'btn', icon: 'el-icon-location', tooltip: '居中到机器人' },
      { key: 'toggle-fullscreen', type: 'btn', icon: props.isFullscreen ? 'el-icon-aim' : 'el-icon-full-screen', tooltip: props.isFullscreen ? '退出全屏' : '进入全屏' },
      { key: 'divider-1', type: 'divider' },
      { key: 'select-mode', type: 'btn', customIcon: 'select', tooltip: '元素选择' },
      { key: 'draw-point', type: 'btn', customIcon: 'point', tooltip: '绘制点' },
      { key: 'draw-line', type: 'btn', customIcon: 'line', tooltip: '绘制线' },
      { key: 'draw-curve', type: 'btn', customIcon: 'curve', tooltip: '绘制曲线' },
      { key: 'draw-polygon', type: 'btn', customIcon: 'polygon', tooltip: '绘制区域' },
      { key: 'divider-2', type: 'divider' },
      { key: 'save-map', type: 'btn', icon: 'el-icon-check', tooltip: '保存', buttonType: 'primary' }
    ]
  }
  return presets[props.preset] || []
}

// 获取工具的tooltip
function getToolTooltip(tool) {
  return tool.tooltip || tool.key
}

// 处理需要确认的操作
async function handleConfirmAction(actionKey) {
  const confirmMessages = {
    'init-pose': '确定要进行位姿初始化吗？',
    'reboot': '确定要重启系统吗？',
    'emergency-stop': '确定要急停/结束当前操作吗？'
  }

  const message = confirmMessages[actionKey]
  if (!message) return

  try {
    await ElMessageBox.confirm(message, '确认操作', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    const eventMap = {
      'init-pose': 'confirm-init',
      'reboot': 'confirm-reboot',
      'emergency-stop': 'confirm-stop'
    }
    emit(eventMap[actionKey])
  } catch {
    // 用户取消操作
  }
}

// 统一工具点击处理
function handleToolClick(tool) {
  // 需要二次确认的操作
  if (['init-pose', 'reboot', 'emergency-stop'].includes(tool.key)) {
    handleConfirmAction(tool.key)
    return
  }

  // 发送统一点击事件
  emit('click', { key: tool.key, tool })

  // 兼容特定工具的专用事件
  if (tool.key === 'zoom-in') {
    emit('zoom-in')
  } else if (tool.key === 'zoom-out') {
    emit('zoom-out')
  } else if (tool.key === 'center-robot') {
    emit('center-robot')
  } else if (tool.key === 'toggle-fullscreen') {
    emit('toggle-fullscreen')
  } else if (tool.key === 'add-calibration') {
    emit('add-calibration-point')
  } else if (tool.key === 'select-mode') {
    emit('mode-change', 'select')
  } else if (tool.key === 'draw-point') {
    emit('mode-change', 'draw-point')
  } else if (tool.key === 'draw-line') {
    emit('mode-change', 'draw-line')
  } else if (tool.key === 'draw-curve') {
    emit('mode-change', 'draw-curve')
  } else if (tool.key === 'draw-polygon') {
    emit('mode-change', 'draw-polygon')
  } else if (tool.key === 'save-map') {
    emit('save')
  }
}

// 检查工具是否禁用
function isToolDisabled(key) {
  if (props.disabledKeys.includes(key)) {
    return true
  }
  return false
}

// === 兼容原标定页的方法 ===
function zoomIn() {
  emit('zoom-in')
  emit('click', { key: 'zoom-in' })
}

function zoomOut() {
  emit('zoom-out')
  emit('click', { key: 'zoom-out' })
}

function centerToRobot() {
  if (!props.hasRobotPosition) {
    return
  }
  emit('center-to-robot')
  emit('click', { key: 'center-to-robot' })
}

function toggleFullscreen() {
  emit('toggle-fullscreen')
  emit('click', { key: 'toggle-fullscreen' })
}

function addCalibrationPoint() {
  emit('add-calibration-point')
  emit('click', { key: 'add-calibration-point' })
}

function resetView() {
  emit('reset-view')
  emit('click', { key: 'reset-view' })
}

function toggleMeasureTool() {
  emit('toggle-measure-tool')
  emit('click', { key: 'toggle-measure-tool' })
}
</script>

<style>
@import './_map-shared.css';

/* 工具栏容器 */
.map-toolbar {
  position: relative;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 6px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
  padding: 8px;
  pointer-events: auto;
  width: auto;
  z-index: 1;
  animation: toolbarSlideIn 0.3s ease-out;
}

/* 工具项包装器 */
.toolbar-item-wrapper {
  display: contents;
}

/* 工具项 */
.toolbar-item {
  display: flex;
  flex-direction: inherit;
  align-items: center;
  gap: inherit;
}

/* 工具栏按钮 */
.toolbar-btn {
  width: var(--toolbar-btn-size);
  height: var(--toolbar-btn-size);
  min-width: var(--toolbar-btn-size);
  min-height: var(--toolbar-btn-size);
  padding: 0;
  margin: 0;
  border: 1px solid #dcdfe6;
  background-color: #fff;
  color: #606266;
  transition: all 0.2s ease;
}

.toolbar-btn:hover {
  background-color: #f5f7fa;
  border-color: #c0c4cc;
  color: #409eff;
}

.toolbar-btn:active {
  background-color: #e6f7ff;
  border-color: #409eff;
  color: #409eff;
  transform: scale(0.98);
}

.toolbar-btn.primary-btn {
  background-color: #409eff;
  color: #fff;
  border-color: #409eff;
}

.toolbar-btn.primary-btn:hover {
  background-color: #66b1ff;
  border-color: #66b1ff;
}

.toolbar-btn.primary-btn:active {
  background-color: #3a8ee6;
  border-color: #3a8ee6;
  transform: scale(0.98);
}

.toolbar-btn.active {
  background: #409eff;
  color: #fff;
  border-color: #409eff;
}

.toolbar-btn:disabled {
  color: #c0c4cc;
  background-color: #fff;
  border-color: #ebeef5;
  cursor: not-allowed;
}

/* 深度选择器 - Element Plus 图标 */
.toolbar-btn :deep(.el-icon) {
  font-size: 16px !important;
  line-height: 1 !important;
}

.toolbar-btn :deep(i) {
  font-size: var(--font-size-base) !important;
  line-height: 1 !important;
}

/* 分隔线 */
.toolbar-divider {
  width: 100%;
  height: 1px;
  margin: 10px 0;
  background: rgba(0, 0, 0, 0.08);
  flex-shrink: 0;
}

/* 自定义图标样式 */
.custom-icon {
  width: 16px;
  height: 16px;
  display: block;
  color: currentColor;
  flex-shrink: 0;
}

.toolbar-btn:hover .custom-icon,
.toolbar-btn.active .custom-icon {
  color: currentColor;
}

/* 包含自定义图标的按钮 */
.toolbar-btn.has-custom-icon :deep(.el-button) {
  display: flex !important;
  align-items: center !important;
  justify-content: center !important;
  padding: 0 !important;
}

.toolbar-btn.has-custom-icon :deep(.el-button > span) {
  display: flex !important;
  align-items: center !important;
  justify-content: center !important;
  width: 100% !important;
  height: 100% !important;
}

/* 暗色主题适配 */
html.dark .map-toolbar {
  background: rgba(31, 41, 55, 0.9);
  border-color: var(--color-border-tertiary);
}

html.dark .toolbar-btn {
  background: var(--color-bg-tertiary);
  border-color: var(--color-border-tertiary);
  color: var(--color-text-secondary);
}

html.dark .toolbar-btn:hover {
  background: var(--color-bg-quaternary);
  border-color: var(--color-border-secondary);
  color: var(--color-primary);
}

html.dark .toolbar-divider {
  background: var(--color-border-tertiary);
}

/* 响应式适配 */
@media (max-width: 768px) {
  .toolbar-btn {
    width: var(--toolbar-btn-size-sm) !important;
    height: var(--toolbar-btn-size-sm) !important;
    min-width: var(--toolbar-btn-size-sm) !important;
    min-height: var(--toolbar-btn-size-sm) !important;
  }

  .toolbar-btn :deep(.el-icon) {
    font-size: var(--font-size-sm);
  }
}

/* 动画效果 */
@keyframes toolbarSlideIn {
  from {
    opacity: 0;
    transform: translateX(-20px);
  }
  to {
    opacity: 1;
    transform: translateX(0);
  }
}
</style>
