<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">
          <!-- 始终显示的前3个搜索项 -->
          <template v-for="(field, key, index) in searchFields" :key="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"
                :default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]"
                :style="{ width: field.width ? field.width + 'px' : '350px' }" />
            </el-form-item>
          </template>

          <!-- 展开时显示的额外搜索项 -->
          <template v-if="isExpanded" v-for="(field, key, index) in searchFields" :key="'expanded-' + 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"
                :default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]"
                :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">{{ t('common.search') }}</el-button>
            <el-button @click="handleReset">{{ t('common.reset') }}</el-button>
            <el-button v-if="hasMoreThanThree" type="text" @click="toggleExpand">
              {{ isExpanded ? t('common.collapse') : t('common.expand') }}
              <el-icon class="expand-toggle-icon" :class="{ 'is-expanded': isExpanded }">
                <ArrowDown />
              </el-icon>
            </el-button>
          </el-form-item>
        </div>
      </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>
import { useI18n } from 'vue-i18n';

const { t } = useI18n();

const props = defineProps({
  searchFields: {
    type: Object,
    default: () => ({}),
  },
  defaultValues: {
    type: Object,
    default: () => ({}),
  },
  // 支持 v-model 双向绑定
  modelValue: {
    type: Object,
    default: () => ({}),
  },
  // 默认是否展开
  defaultExpand: {
    type: Boolean,
    default: false,
  },
});

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

const formRef = ref();
const isExpanded = ref(props.defaultExpand);
const isInitialized = 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;
      }
    }
  });

  // 触发搜索事件（modelValue 已经通过 watch 自动更新了）
  emit('search', searchData);
};

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

  // 触发重置事件（modelValue 会通过 watch 自动更新）
  emit('reset');
};



// 初始化表单数据
const initFormData = () => {
  isInitialized.value = false;
  Object.keys(props.searchFields).forEach((key) => {
    if (props.defaultValues[key] !== undefined) {
      formData[key] = props.defaultValues[key];
    } else {
      formData[key] = '';
    }
  });
  // 初始化完成后，设置标志
  setTimeout(() => {
    isInitialized.value = true;
  }, 0);
};

// 监听表单数据变化，实时更新 modelValue
watch(
  formData,
  () => {
    // 只在初始化完成后才触发更新
    if (!isInitialized.value) return;

    // 过滤掉空值，实时更新父组件
    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('update:modelValue', searchData);
  },
  { deep: true },
);

// 监听 modelValue 变化，支持外部更新
watch(
  () => props.modelValue,
  (newValue) => {
    if (newValue && typeof newValue === 'object') {
      Object.keys(formData).forEach((key) => {
        if (newValue[key] !== undefined) {
          formData[key] = newValue[key];
        }
      });
    }
  },
  { deep: true },
);

// 监听搜索字段变化
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: 20px;
    background-color: var(--sa-card-background);
    border-radius: 4px;

    :deep(.el-form-item) {
      margin-bottom: 16px;
      margin-right: 16px;
      min-width: fit-content; // 确保表单项不会被过度压缩
    }

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

    .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 {
        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>
