<script setup>
  import { ref, watch } from 'vue';
  //组件的属性
  let props = defineProps({
    form: {
      //表单参数详情
      type: Object,
      default: () => ({})
    },
    columns: {
      type: Array,
      default: () => []
    },
    marginBottom: {
      type: String,
      default: '10px'
    }
  });
  const emit = defineEmits(['update:form']);

  let model = ref({});
  watch(
    () => props.form,
    (val) => {
      model.value = val;
    },
    { deep: true }
  );

  watch(
    () => model.value,
    (val) => {
      let data = Object.assign(props.form, val);
      emit('update:form', data);
    },
    { deep: true }
  );

  //tag上 placeholder的显示
  const getPlaceholder = (row) => {
    if (row.placeholder) return row.placeholder;
    if (typeof row.tag == 'object') return;
    return row.label;
  };
  //插槽函数
  const slotFunction = (val) => {
    return typeof val == 'function' ? val() : val;
  };

  let formRef = ref(null);

  defineExpose({
    form: props.model
  });
</script>

<style lang="scss">
  .search-form {
    ::v-deep .el-date-editor.el-input, .el-date-editor.el-input__wrapper {
      width: 100%;
    }
  }
</style>

<template>
  <el-form
    ref="formRef"
    v-bind="$attrs"
    :labelWidth="0"
    :model="model"
    class="search-form"
  >
    <el-row :gutter="12" justify="start">
      <el-col
        v-for="element in columns"
        :span="element.span || 6"
        :key="element.prop"
      >
        <el-form-item
          class="custom-class"
          :class="element.customClass"
          :prop="element.prop"
          v-bind="element.formItemAttrs"
          :style="{ marginBottom: marginBottom }"
        >
          <template v-if="element.type == 'slot'">
            <slot
              :name="element.prop"
              :data="model"
              :item="element.tagAttrs"
            ></slot>
          </template>
          <component
            v-else
            :is="element.tag"
            v-bind="element.tagAttrs"
            v-model="model[element.prop]"
            :placeholder="getPlaceholder(element)"
          >
            <template v-for="(val, key, i) in element.tagSlots" :key="i" #[key]>
              {{ slotFunction(val) }}
            </template>
          </component>
        </el-form-item>
      </el-col>
      <slot></slot>
    </el-row>
  </el-form>
</template>
