<template>
  <div class="search-section">
    <div class="search-grid-container">
      <slot />
      <div 
        v-for="i in getPlaceHolderCount()" 
        :key="`placeholder-${i}`"
        class="placeholder-item"
      ></div>
      <div class="search-btn-group">
        <el-button type="primary" icon="Search" @click="handleSearch">
          查询
        </el-button>
        <el-button type="info" icon="Refresh" @click="handleReset">
          重置
        </el-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, defineEmits, onMounted, nextTick } from 'vue'
import { Search, Refresh } from '@element-plus/icons-vue'

const emit = defineEmits(['search', 'reset'])
const conditionCount = ref(0)

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

const handleReset = () => {
  emit('reset')
}

onMounted(async () => {
  await nextTick()
  calcConditionCount()
})

const calcConditionCount = () => {
  const items = document.querySelectorAll('.search-grid-container .search-item')
  conditionCount.value = items ? items.length : 0
}

const getPlaceHolderCount = () => {
  const currentRowRemain = 4 - (conditionCount.value % 4)
  return currentRowRemain === 0 ? 3 : currentRowRemain - 1
}
</script>

<style scoped>
.search-section {
  width: 100%;
  margin-bottom: 16px;
  flex-shrink: 0;
  padding-bottom: 12px;
  border-bottom: 1px solid #e5e7eb;
  box-sizing: border-box;
}

.search-grid-container {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 15px;
  width: 100%;
  box-sizing: border-box;
  align-items: stretch;
}

.search-grid-container :deep(.search-item) {
  margin-bottom: 0 !important;
  width: 100%;
  box-sizing: border-box;
  display: flex;
  align-items: center; 
}

.search-grid-container :deep(.search-input),
.search-grid-container :deep(.search-select) {
  width: 100%;
  box-sizing: border-box;
}

.placeholder-item {
  width: 100%;
  height: 1px;
  visibility: hidden;
}

.search-btn-group {
  display: flex;
  gap: 8px;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
  box-sizing: border-box;
}

@media (max-width: 768px) {
  .search-grid-container {
    grid-template-columns: 1fr !important;
    gap: 10px;
  }
  .placeholder-item {
    display: none;
  }
  .search-btn-group {
    justify-content: center;
    padding: 8px 0;
  }
}
</style>