<template>
  <div class="sa-search-simple">
    <div class="search-form">
      <el-form ref="formRef" :model="formData" inline @submit.prevent="handleSearch">
        <!-- 始终显示的搜索项 -->
        <div class="search-form-main">
          <template v-for="(field, key, index) in searchFields" :key="key">
            <el-form-item v-if="isExpanded || index < 3" :prop="key" :label="field.label">
              <!-- 输入框类型 -->
              <el-input
                v-if="field.type === 'input'"
                v-model="formData[key]"
                :placeholder="field.placeholder || ''"
                clearable
                :style="{ width: field.width ? field.width + 'px' : '200px' }"
              />

              <!-- 下拉选择类型 -->
              <el-select
                v-else-if="field.type === 'select'"
                v-model="formData[key]"
                :placeholder="field.placeholder || field.label"
                clearable
                :style="{ width: field.width ? field.width + 'px' : '200px' }"
              >
                <el-option
                  v-for="option in field.options"
                  :key="option.value"
                  :label="option.label"
                  :value="option.value"
                />
              </el-select>

              <!-- 级联选择类型 -->
              <el-cascader
                v-else-if="field.type === 'cascader'"
                v-model="formData[key]"
                :options="field.options"
                :props="field.props"
                :placeholder="field.placeholder || field.label"
                clearable
                :style="{ width: field.width ? field.width + 'px' : '300px' }"
              />

              <!-- 日期范围类型 -->
              <el-date-picker
                v-else-if="field.type === 'daterange'"
                v-model="formData[key]"
                type="datetimerange"
                value-format="YYYY-MM-DD HH:mm:ss"
                format="YYYY-MM-DD HH:mm:ss"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                :editable="false"
                :style="{ width: field.width ? field.width + 'px' : '350px' }"
              />
            </el-form-item>
          </template>

          <!-- 自定义插槽内容 -->
          <slot name="custom" :data="formData"></slot>

          <!-- 操作按钮 -->
          <el-form-item>
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="handleReset">重置</el-button>
            <el-button v-if="hasMoreThanThree" type="text" @click="toggleExpand">
              {{ isExpanded ? '收起' : '展开' }}
              <el-icon class="expand-toggle-icon" :class="{ 'is-expanded': isExpanded }">
                <ArrowDown />
              </el-icon>
            </el-button>
          </el-form-item>
        </div>

        <!-- 折叠的高级搜索项 -->
        <el-collapse-transition>
          <div v-show="isExpanded && hasMoreThanThree" class="search-form-advanced">
            <template v-for="(field, key, index) in searchFields" :key="'advanced-' + key">
              <el-form-item v-if="index >= 3" :prop="key" :label="field.label">
                <!-- 输入框类型 -->
                <el-input
                  v-if="field.type === 'input'"
                  v-model="formData[key]"
                  :placeholder="field.placeholder || ''"
                  clearable
                  :style="{ width: field.width ? field.width + 'px' : '200px' }"
                />

                <!-- 下拉选择类型 -->
                <el-select
                  v-else-if="field.type === 'select'"
                  v-model="formData[key]"
                  :placeholder="field.placeholder || field.label"
                  clearable
                  :style="{ width: field.width ? field.width + 'px' : '200px' }"
                >
                  <el-option
                    v-for="option in field.options"
                    :key="option.value"
                    :label="option.label"
                    :value="option.value"
                  />
                </el-select>

                <!-- 级联选择类型 -->
                <el-cascader
                  v-else-if="field.type === 'cascader'"
                  v-model="formData[key]"
                  :options="field.options"
                  :props="field.props"
                  :placeholder="field.placeholder || field.label"
                  clearable
                  :style="{ width: field.width ? field.width + 'px' : '300px' }"
                />

                <!-- 日期范围类型 -->
                <el-date-picker
                  v-else-if="field.type === 'daterange'"
                  v-model="formData[key]"
                  type="datetimerange"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  format="YYYY-MM-DD HH:mm:ss"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  :editable="false"
                  :style="{ width: field.width ? field.width + 'px' : '350px' }"
                />
              </el-form-item>
            </template>
          </div>
        </el-collapse-transition>
      </el-form>
    </div>
  </div>
</template>

<script>
  import { ref, computed, reactive, watch } from 'vue';
  import { ArrowDown } from '@element-plus/icons-vue';

  export default {
    name: 'SaSearchSimple',
    components: {
      ArrowDown,
    },
  };
</script>

<script setup>
  const props = defineProps({
    searchFields: {
      type: Object,
      default: () => ({}),
    },
    defaultValues: {
      type: Object,
      default: () => ({}),
    },
  });

  const emit = defineEmits(['search', 'reset']);

  const formRef = ref();
  const isExpanded = ref(false);

  // 表单数据
  const formData = reactive({});

  // 计算是否有超过3个搜索条件
  const hasMoreThanThree = computed(() => {
    return Object.keys(props.searchFields).length > 3;
  });

  // 展开收起切换
  const toggleExpand = () => {
    isExpanded.value = !isExpanded.value;
  };

  // 搜索处理
  const handleSearch = () => {
    // 过滤掉空值
    const searchData = {};
    Object.keys(formData).forEach((key) => {
      const value = formData[key];
      if (value !== '' && value !== null && value !== undefined) {
        // 如果是数组且不为空
        if (Array.isArray(value) && value.length > 0) {
          searchData[key] = value;
        }
        // 如果是对象且有有效值
        else if (typeof value === 'object' && value !== null) {
          if (value.min || value.max) {
            searchData[key] = value;
          }
        }
        // 其他非空值
        else if (value) {
          searchData[key] = value;
        }
      }
    });

    emit('search', searchData);
  };

  // 重置处理
  const handleReset = () => {
    // 重置表单数据
    Object.keys(formData).forEach((key) => {
      if (props.defaultValues[key] !== undefined) {
        formData[key] = props.defaultValues[key];
      } else {
        formData[key] = '';
      }
    });

    emit('reset');
  };

  // 初始化表单数据
  const initFormData = () => {
    Object.keys(props.searchFields).forEach((key) => {
      if (props.defaultValues[key] !== undefined) {
        formData[key] = props.defaultValues[key];
      } else {
        formData[key] = '';
      }
    });
  };

  // 监听搜索字段变化
  watch(
    () => props.searchFields,
    () => {
      initFormData();
    },
    { immediate: true },
  );

  // 监听默认值变化
  watch(
    () => props.defaultValues,
    () => {
      initFormData();
    },
    { deep: true },
  );
</script>

<style lang="scss" scoped>
  .sa-search-simple {
    width: 100%;

    .search-form {
      margin-top: 30px;
      background-color: #fff;
      border-radius: 4px;

      :deep(.el-form-item) {
        margin-bottom: 16px;
        margin-right: 16px;
      }

      .search-form-main {
        display: flex;
        flex-wrap: wrap;
        align-items: flex-end;
        margin-bottom: 0;
      }

      .search-form-advanced {
        display: flex;
        flex-wrap: wrap;
        align-items: flex-end;
        padding-top: 16px;
      }

      .expand-toggle-btn {
        margin-left: 8px;
        transition: all 0.3s ease;

        .expand-toggle-icon {
          margin-left: 4px;
          transition: transform 0.3s cubic-bezier(0.25, 0.8, 0.25, 1);

          &.is-expanded {
            transform: rotate(180deg);
          }
        }

        &:hover {
          color: #66b1ff;
          transform: translateY(-1px);
        }

        &:active {
          transform: translateY(0);
        }
      }
    }
  }

  // 响应式设计
  @media (max-width: 768px) {
    .sa-search-simple {
      .search-form {
        padding: 12px;

        :deep(.el-form-item) {
          margin-bottom: 12px;
          margin-right: 12px;
        }

        .search-form-main,
        .search-form-advanced {
          flex-direction: column;
          align-items: stretch;

          :deep(.el-form-item) {
            margin-right: 0;
          }
        }
      }
    }
  }

  @media (max-width: 480px) {
    .sa-search-simple {
      .search-form {
        padding: 8px;

        :deep(.el-form-item) {
          margin-bottom: 8px;
          margin-right: 8px;
        }
      }
    }
  }
</style>
