<template>
  <div class="manage-search">
    <div class="search-form">
      <el-form
        ref="formRef"
        :model="formData"
        :inline="inline"
        :label-width="labelWidth"
        :size="size"
        @submit.prevent="handleSearch"
      >
        <el-row :gutter="gutter">
          <el-col
            v-for="(item, index) in formItems"
            :key="item.prop || index"
            :span="item.span || defaultSpan"
          >
            <el-form-item
              style="width: 100%"
              :label="item.label"
              :prop="item.prop"
            >
              <!-- 输入框 -->
              <el-input
                v-if="item.type === 'input'"
                v-model="formData[item.prop]"
                :placeholder="item.placeholder || `请输入${item.label}`"
                :clearable="item.clearable"
                :disabled="item.disabled"
                :maxlength="item.maxlength"
                @keyup.enter="handleEnterSearch(item)"
                @clear="handleSearch"
              />

              <!-- 选择器 -->
              <el-select
                v-else-if="item.type === 'select'"
                v-model="formData[item.prop]"
                :placeholder="item.placeholder || `请选择${item.label}`"
                :clearable="item.clearable"
                :disabled="item.disabled"
                :multiple="item.multiple"
                :filterable="item.filterable"
                @clear="handleSearch"
              >
                <el-option
                  v-for="option in item.options"
                  :key="option.value"
                  :label="option.label"
                  :value="option.value"
                  :disabled="option.disabled"
                />
              </el-select>

              <!-- 字典选择器 -->
              <common-selector
                v-else-if="item.type === 'dict-select'"
                v-model="formData[item.prop]"
                :clearable="item.clearable"
                :dict-name="item.dictName"
                :label-key="item.labelKey || 'name'"
                :value-key="item.valueKey || 'key'"
                :placeholder="item.placeholder || `请选择${item.label}`"
                :disabled="item.disabled"
                :radio="item.radio"
              />

              <!-- 日期选择器 -->
              <el-date-picker
                v-else-if="item.type === 'date'"
                v-model="formData[item.prop]"
                :type="item.dateType || 'date'"
                :placeholder="item.placeholder || `请选择${item.label}`"
                :format="item.format"
                :value-format="item.valueFormat"
                :clearable="item.clearable"
                :disabled="item.disabled"
                :start-placeholder="item.startPlaceholder"
                :end-placeholder="item.endPlaceholder"
                @clear="handleSearch"
              />

              <!-- 日期范围选择器 -->
              <el-date-picker
                v-else-if="item.type === 'daterange'"
                v-model="formData[item.prop]"
                type="daterange"
                range-separator="至"
                :start-placeholder="item.startPlaceholder || '开始日期'"
                :end-placeholder="item.endPlaceholder || '结束日期'"
                :format="item.format"
                :value-format="item.valueFormat"
                :clearable="item.clearable"
                :disabled="item.disabled"
                @clear="handleSearch"
              />

              <!-- 单选框组 -->
              <el-radio-group
                v-else-if="item.type === 'radio'"
                v-model="formData[item.prop]"
                :disabled="item.disabled"
              >
                <el-radio
                  v-for="option in item.options"
                  :key="option.value"
                  :label="option.value"
                >
                  {{ option.label }}
                </el-radio>
              </el-radio-group>

              <!-- 复选框组 -->
              <el-checkbox-group
                v-else-if="item.type === 'checkbox'"
                v-model="formData[item.prop]"
                :disabled="item.disabled"
              >
                <el-checkbox
                  v-for="option in item.options"
                  :key="option.value"
                  :label="option.value"
                >
                  {{ option.label }}
                </el-checkbox>
              </el-checkbox-group>

              <!-- 数字输入框 -->
              <el-input-number
                v-else-if="item.type === 'number'"
                v-model="formData[item.prop]"
                :min="item.min"
                :max="item.max"
                :step="item.step || 1"
                :disabled="item.disabled"
                :controls="item.controls !== false"
                @keyup.enter="handleEnterSearch(item)"
              />

              <!-- 级联选择器 -->
              <el-cascader
                v-else-if="item.type === 'cascader'"
                v-model="formData[item.prop]"
                :options="item.options"
                :props="item.props || {}"
                :clearable="item.clearable"
                :disabled="item.disabled"
                :filterable="item.filterable"
                @clear="handleSearch"
              />

              <!-- 树选择器 -->
              <el-tree-select
                v-else-if="item.type === 'tree'"
                v-model="formData[item.prop]"
                :data="item.data"
                :props="item.props || {}"
                :clearable="item.clearable"
                :disabled="item.disabled"
                :filterable="item.filterable"
                :check-strictly="item.checkStrictly"
                @clear="handleSearch"
              />

              <!-- 自定义插槽 -->
              <slot
                v-else-if="item.type === 'slot'"
                :name="item.slotName || item.prop"
                :prop="item.prop"
                :item="item"
                :value="formData[item.prop]"
              />
            </el-form-item>
          </el-col>

          <!-- 操作按钮 -->
          <el-col :span="buttonSpan || 6">
            <el-form-item label=" ">
              <div class="search-form-buttons">
                <el-button type="primary" :icon="Search" @click="handleSearch">
                  {{ searchText || "搜索" }}
                </el-button>
                <el-button
                  type="primary"
                  plain
                  :icon="RefreshLeft"
                  @click="handleReset"
                >
                  {{ resetText || "重置" }}
                </el-button>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, watch, nextTick } from "vue";
import { Search, RefreshLeft } from "@element-plus/icons-vue";
import CommonSelector from "@/components/CommonSelector.vue";

const props = defineProps({
  items: {
    type: Array,
    default: () => [
      {
        type: "input",
        label: "项目名称",
        prop: "projectName",
        placeholder: "请输入项目名称",
        span: 6,
        clearable: true,
      },
      {
        type: "input",
        label: "项目编号",
        prop: "projectCode",
        placeholder: "请输入项目编号",
        span: 6,
        clearable: true,
      },
      {
        type: "input",
        label: "直属企业",
        prop: "zsqy",
        placeholder: "请输入直属企业",
        span: 6,
        clearable: true,
      },
      {
        type: "input",
        label: "管理主体",
        prop: "glzt",
        placeholder: "请输入管理主体",
        span: 6,
        clearable: true,
      },
      {
        type: "input",
        label: "联系人",
        prop: "lxr",
        placeholder: "请输入联系人",
        span: 6,
        clearable: true,
      },

      {
        type: "dict-select",
        label: "项目阶段",
        prop: "xmjd",
        dictName: "xmjd",
        placeholder: "请选择项目阶段",
        span: 6,
        clearable: true,
      },

      {
        type: "dict-select",
        label: "项目区域",
        prop: "xmqy",
        dictName: "xmqy",
        placeholder: "请选择项目区域",
        span: 6,
        clearable: true,
      },
    ],
  },
  inline: { type: Boolean, default: true },
  labelWidth: { type: String, default: "auto" },
  size: { type: String, default: "default" },
  gutter: { type: Number, default: 16 },
  defaultSpan: { type: Number, default: 6 },
  buttonSpan: { type: Number, default: 6 },
  searchText: { type: String, default: "搜索" },
  resetText: { type: String, default: "重置" },
  autoSearchOnReset: { type: Boolean, default: true },
  autoSearchOnClear: { type: Boolean, default: false },
});

const emit = defineEmits([
  "search",
  "reset",
  "field-change",
  "field-clear",
  "form-data-change",
]);

const formRef = ref();
const formData = reactive({});
const defaultFormData = ref({}); // 缓存初始值用于重置
const formItems = props.items;

// --- 工具函数 ---

// 1. 获取类型的默认空值
const getDefaultValue = (type) => {
  switch (type) {
    case "checkbox":
      return [];
    case "number":
      return null; // 数字通常用null表示空
    case "daterange":
      return [];
    default:
      return "";
  }
};

// 2. 核心过滤器：移除空值、空字符串、空数组
const filterEmptyValues = (data) => {
  const filteredData = {};
  Object.entries(data).forEach(([key, value]) => {
    // 只要不是空字符串、null、undefined 或 空数组，就保留
    if (
      value !== "" &&
      value !== null &&
      value !== undefined &&
      !(Array.isArray(value) && value.length === 0)
    ) {
      filteredData[key] = value;
    }
  });
  return filteredData;
};

// --- 核心逻辑 ---

// 初始化数据
const initFormData = (isReset = false) => {
  // 先清空
  Object.keys(formData).forEach((key) => delete formData[key]);

  formItems.forEach((item) => {
    if (item.prop) {
      let val;
      if (isReset) {
        // 重置模式：使用缓存的初始值
        val = defaultFormData.value[item.prop];
      } else {
        // 初始化模式：使用配置的默认值或类型默认值
        val =
          item.defaultValue !== undefined
            ? item.defaultValue
            : getDefaultValue(item.type);
        defaultFormData.value[item.prop] = val; // 缓存
      }
      formData[item.prop] = val;
    }
  });

  // 通知外部数据已更新（此时是原始数据，包含空值）
  emit("form-data-change", { ...formData });
};

// 唯一的搜索出口：负责过滤数据并发射事件
const handleSearch = () => {
  const result = filterEmptyValues(formData);
  emit("search", result);
};

// 重置逻辑：恢复数据 -> 触发搜索
const handleReset = () => {
  formRef.value?.clearValidate(); // 清除校验
  initFormData(true); // 恢复初始状态（空状态）
  emit("reset", { ...formData }); // 通知重置事件

  // 统一调用搜索，此时 handleSearch 会自动过滤掉刚恢复的空值
  if (props.autoSearchOnReset) {
    nextTick(() => handleSearch());
  }
};

// 回车搜索
const handleEnterSearch = (item) => {
  // 统一调用 handleSearch 进行过滤和提交
  handleSearch();
};

// --- 暴露给父组件的方法 ---
defineExpose({
  formRef,
  // 获取过滤后的数据（推荐用于外部调用）
  getFormData: () => filterEmptyValues(formData),
  // 获取原始数据（包含空值）
  getRawFormData: () => ({ ...formData }),
  // 外部触发重置
  resetFields: handleReset,
  // 外部触发搜索
  search: handleSearch,
  // 外部设置数据
  setFormData: (newData) => {
    Object.keys(newData).forEach((key) => {
      if (formData.hasOwnProperty(key)) {
        formData[key] = newData[key];
      }
    });
  },
});

// 组件挂载初始化
initFormData(false);
</script>
<style lang="less" scoped>
.search-form {
  :deep(.el-form-item) {
    margin-bottom: 16px;
  }

  :deep(.el-form-item__label) {
    font-weight: normal;
  }

  :deep(.el-input),
  :deep(.el-select),
  :deep(.el-date-editor),
  :deep(.el-cascader),
  :deep(.el-tree-select) {
    width: 100%;
    // 增强 el-select 宽度生效
    &.el-select {
      .el-select__wrapper {
        width: 100% !important;
      }
    }
  }

  .search-form-buttons {
    display: flex;
    gap: 8px;
  }

  :deep(.el-input-number) {
    width: 100%;
  }
}
</style>
