<template>
  <div class="header-container">
    <div class="header-title">{{ title }}</div>
    <el-form :model="formModel" ref="searchForm" label-width="auto" label-position="left" class="header-form" :inline="true">
      <el-form-item :label="item.label" :prop="item.fieldName" v-for="(item, index) in formData" :key="index">
        <!-- 输入框 -->
        <el-input v-if="item.type === 'input'" v-model="formModel[item.fieldName]"
          :placeholder="item.placeholder"></el-input>

        <!-- 下拉框 -->
        <el-select v-if="item.type === 'select'" v-model="formModel[item.fieldName]" :placeholder="item.placeholder">
          <el-option v-for="(option, index) in item.options" :key="index" :label="option.label"
            :value="option.value"></el-option>
        </el-select>

        <!-- 日期选择器 -->
        <el-date-picker v-if="item.type === 'date'" v-model="formModel[item.fieldName]" :placeholder="item.placeholder"
          type="date" format="yyyy-MM-dd"></el-date-picker>

        <!-- 自定义控件 -->
        <!-- 你可以根据需求继续添加不同类型的表单控件 -->
      </el-form-item>
      <el-form-item>
        <el-button type="primary" size="mini" @click="handleSubmit">搜索</el-button>
        <el-button size="mini" @click="handleReset">重置</el-button>
      </el-form-item>

    </el-form>
  </div>
</template>

<script>
export default {
  props: {
    title: String,
    formData: {
      type: Array,
      required: true,
      default: () => [],
    },
  },
  watch: {
    formData: {
      handler(newVal) {
        this.formData = newVal;
      },
      deep: true, // 深入监听
      immediate: true
    },
  },

  data () {
    return {
      formModel: {},
      formRules: {},  // 初始化表单规则
    };
  },
  mounted () {
    // 初始化表单模型和验证规则
    this.initializeForm();
  },
  methods: {
    // 初始化表单模型
    initializeForm () {
      this.formData.forEach((item) => {
        // 设置初始值
        this.$set(this.formModel, item.fieldName, item.value || "");

        // 设置表单验证规则
        this.$set(this.formRules, item.fieldName, {
          required: item.isRequired,
          message: `${item.label}是必填项`,
          trigger: "blur",
        });
      });
    },

    // 表单提交
    handleSubmit () {
      this.$refs.searchForm.validate((valid) => {
        if (valid) {
          // 这里可以做提交逻辑
          this.$emit("submit", this.formModel);
        } else {
          console.log("表单验证失败!");
        }
      });
    },

    // 表单重置
    handleReset () {
      this.$refs.searchForm.resetFields();
      this.$emit("submit", this.formModel);
    },
  },
};
</script>

<style scoped lang="scss">
.header-container {
  width: 100%;
  display: flex;
  align-items: center;
  line-height: 1;
}

.header-title {
  font-size: 20px;
  // width: 360px;
   white-space: nowrap; /* 禁止换行 */
   margin-right: 40px;
}

.btn-box {
  margin-left: 20px;
}
</style>
