<template>
  <div v-if="buttons.length" class="dynamic-table-toolbar" :style="toolbarStyle">
    <el-space :size="8">
      <el-button
        v-for="(btn, idx) in buttons"
        :key="btn.key || idx"
        :type="btn.type"
        :icon="btn.icon"
        :loading="btn.loading"
        :disabled="btn.disabled || (btn.needsSelection && !selectedKeys.length)"
        @click="handleClick(btn)"
      >
        {{ btn.text }}
      </el-button>
    </el-space>
  </div>
</template>

<script setup>
import { computed } from 'vue'
import { ElMessage } from 'element-plus'

const props = defineProps({
  /**
   * 按钮列表
   */
  buttons: {
    type: Array,
    default: () => []
  },
  /**
   * 已选中的行 key 数组
   */
  selectedKeys: {
    type: Array,
    default: () => []
  },
  /**
   * 数据源（传递给按钮 onClick）
   */
  dataSource: {
    type: Array,
    default: () => []
  },
  /**
   * 工具栏对齐方式
   */
  align: {
    type: String,
    default: 'left',
    validator: (v) => ['left', 'center', 'right'].includes(v)
  }
})

const toolbarStyle = computed(() => ({
  justifyContent: props.align === 'left' ? 'flex-start'
    : props.align === 'right' ? 'flex-end'
    : 'center'
}))

const handleClick = (button) => {
  // 检查是否需要选中数据
  if (button.needsSelection && !props.selectedKeys.length) {
    ElMessage.warning(button.selectionMessage || '请选择要操作的数据')
    return
  }

  // 调用按钮的 onClick 回调
  button.onClick?.(props.selectedKeys, props.dataSource)
}
</script>

<style scoped>
.dynamic-table-toolbar {
  display: flex;
  margin-bottom: 16px;
}
</style>
