<template>
  <div v-if="hasSelection" class="batch-edit-toolbar">
    <a-space size="small">
      <a-button 
        type="primary" 
        @click="showBatchEditModal = true"
      >
        批量编辑 ({{ selectedCount }})
      </a-button>
      
      <a-button 
        @click="clearSelection"
      >
        清除选择
      </a-button>
    </a-space>

    <!-- 批量编辑模态框 -->
    <BatchEditModal
      v-model:visible="showBatchEditModal"
      :selected-items="selectedItems"
      :editor="editor"
      @update="handleBatchUpdate"
    />
  </div>
</template>

<script setup lang="ts">
import type { MapPen } from '@api/map';
import BatchEditModal from '@common/modal/batch-edit-modal.vue';
import { computed, inject, type InjectionKey, ref, type ShallowRef } from 'vue';

import type { EditorService } from '../services/editor.service';

type Props = {
  token: InjectionKey<ShallowRef<EditorService>>;
};

const props = defineProps<Props>();
const editor = inject(props.token)!;

const showBatchEditModal = ref(false);

// 计算选中的元素
const selectedItems = computed(() => {
  if (!editor.value) return [];
  
  const selectedIds = editor.value.selected.value;
  return selectedIds
    .map(id => editor.value!.getPenById(id))
    .filter((pen): pen is MapPen => !!pen && (pen.name === 'point' || pen.name === 'line'));
});

const selectedCount = computed(() => selectedItems.value.length);

const hasSelection = computed(() => selectedCount.value > 0);

const clearSelection = () => {
  editor.value?.inactive();
};

const handleBatchUpdate = (updates: Array<{ id: string; updates: Partial<MapPen> }>) => {
  // 使用批量更新方法，确保所有点位同时更新
  editor.value?.batchUpdate(updates);
  showBatchEditModal.value = false;
};

defineOptions({
  name: 'BatchEditToolbar'
});
</script>

<style scoped lang="scss">
.batch-edit-toolbar {
  position: fixed;
  top: 80px;
  left: 50%;
  transform: translateX(-50%);
  z-index: 100;
  background: rgba(255, 255, 255, 0.95);
  padding: 12px 16px;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  backdrop-filter: blur(8px);
}
</style>
