<template>
  <div class="search-bar">
    <div class="search-row">
      <el-input v-model="form.keyword" :placeholder="placeholder" clearable style="width: 200px">
        <template #prefix>
          <el-icon><Search /></el-icon>
        </template>
      </el-input>
      <el-date-picker
        v-if="showDateRange"
        v-model="form.dateRange"
        type="daterange"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        value-format="YYYY-MM-DD"
        style="width: 220px"
      />
    </div>
    <div class="search-row" v-if="filters.length > 0 || $slots.extra">
      <div class="filter-item" v-for="filter in filters" :key="filter.field">
        <span class="label">{{ filter.label }}</span>
        <el-select v-model="form[filter.field]" placeholder="请选择" clearable style="width: 100px">
          <el-option v-for="opt in filter.options" :key="opt.value" :label="opt.label" :value="opt.value" />
        </el-select>
      </div>
      <slot name="extra"></slot>
      <div class="btn-group">
        <slot name="buttons"></slot>
        <el-button type="danger" @click="handleSearch">搜索</el-button>
        <el-button @click="handleReset">重置</el-button>
      </div>
    </div>
    <div class="search-row btn-only" v-else>
      <slot name="buttons"></slot>
      <el-button type="danger" @click="handleSearch">搜索</el-button>
      <el-button @click="handleReset">重置</el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { Search } from '@element-plus/icons-vue'

export interface FilterOption {
  label: string
  value: string
}

export interface FilterConfig {
  field: string
  label: string
  options: FilterOption[]
}

const props = withDefaults(defineProps<{
  form: Record<string, any>
  filters?: FilterConfig[]
  showDateRange?: boolean
  placeholder?: string
}>(), {
  filters: () => [],
  showDateRange: true,
  placeholder: '搜索'
})

const emit = defineEmits<{
  search: []
  reset: []
}>()

const handleSearch = () => {
  emit('search')
}

const handleReset = () => {
  // 重置表单
  Object.keys(props.form).forEach(key => {
    if (key === 'dateRange') {
      props.form[key] = []
    } else {
      props.form[key] = ''
    }
  })
  emit('reset')
}
</script>

<style scoped lang="scss">
.search-bar {
  margin-bottom: 20px;
  
  .search-row {
    display: flex;
    align-items: center;
    gap: 16px;
    margin-bottom: 12px;
    
    &:last-child {
      margin-bottom: 0;
    }
    
    &.btn-only {
      margin-top: 0;
    }
  }
  
  .filter-item {
    display: flex;
    align-items: center;
    gap: 8px;
    
    .label {
      color: #666;
      font-size: 14px;
    }
  }
  
  .btn-group {
    margin-left: auto;
    display: flex;
    gap: 10px;
  }
}
</style>
