<template>
  <div class="layer-panel-container" :style="{ width: (layerGroups.length * 60 + 24 + Math.max(0, layerGroups.length - 1) * 8) + 'px' }">
    <span class="category-section">
      <span class="layer-horizontal-grid">
        <!-- 使用新的横向 LayerItem 子组件 -->
        <layer-item-horizontal
          v-for="layer in layerGroups"
          :key="layer.id"
          :device-layer="layer"
          :getDynamicIcon="getDynamicIcon"
          :handleSvgError="handleSvgError"
          @click="handleLayerClick"
        />
      </span>
    </span>
  </div>
</template>

<script>
import LayerItemHorizontal from '@vue2-client/base-client/components/common/AfMap/components/DeviceLayerPanel/LayerItemHorizontal.vue'
export default {
  name: 'LayerPanelHorizontal',
  components: {
    LayerItemHorizontal
  },
  props: {
    layerData: {
      type: Object,
      required: true
    },
    getDynamicIcon: {
      type: Function,
      required: true
    },
    handleSvgError: {
      type: Function,
      required: true
    }
  },
  computed: {
    layerGroups () {
      // 使用 flatMap 提取出所有的 groups 并扁平化
      const allGroups = this.layerData.flatMap(item => item.groups)

      // 使用 Map 根据 id 去重，保留后面的数据（如果遇到相同id）
      const map = new Map()
      allGroups.forEach(item => {
        map.set(item.id, item)
      })

      // 转回数组返回
      return Array.from(map.values())
    }
  },
  methods: {
    handleLayerClick (layer) {
      this.$emit('select', layer)
    },
  }
}
</script>

<style scoped>
.layer-panel-container {
  width: 100%;
  max-height: 60vh;
  overflow-y: auto;
  padding: 12px;
}

.category-section {
  margin-bottom: 24px;
}

/* 横向网格布局 */
.layer-horizontal-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(60px, 1fr));
  gap: 8px;
}

/* 响应式调整 */
@media (min-width: 768px) {
  .layer-horizontal-grid {
    grid-template-columns: repeat(auto-fill, minmax(60px, 1fr));
    gap: 8px;
  }
}

@media (min-width: 1024px) {
  .layer-horizontal-grid {
    grid-template-columns: repeat(auto-fill, minmax(60px, 1fr));
  }
}
</style>
