<template>
<div style="width: 100%" v-if="!isFlexLayout">
    <el-row class="search-group" v-for="(group, x) in vnodeGroup" :key="x">
      <el-col :span="calcSpan" v-for="(vnode, y) in group" :key="y">
        <ht-vnode :vnode="vnode" :label-width="labelWidth" @enter-search="search" @field-loaded="handleFieldLoaded"
          @input-change="handleInputChange" />
      </el-col>
    </el-row>
    <el-row class="search-group">
      <div :style="{marginLeft: labelWidth + 'px'}">
        <el-button type="primary" size="small" @click="search">搜索</el-button>
        <el-button size="small" @click="reset">重置</el-button>
      </div>
    </el-row>
  </div>
  <div style="width: 100%" v-else class="flex-layout">
    <el-row class="flex-layout__search" v-for="(group, x) in vnodeGroup" :key="x">
      <div  v-for="(vnode, y) in group" :key="y" class="flex-layout__item">
        <ht-vnode :vnode="vnode" :label-width="labelWidth" @enter-search="search" @field-loaded="handleFieldLoaded"
          @input-change="handleInputChange" />
      </div>
    </el-row>
      <div >
        <el-button type="primary" size="small" @click="search">搜索</el-button>
        <el-button size="small" @click="reset">重置</el-button>
      </div>
  </div>
</template>
<script>
export default {
  name: "ht-table-search-panel",
  props: {
    divide: {
      type: Number,
      default: 4,
      validator: value => {
        return value > 0 && value < 5;
      }
    },
    labelWidth: {
      type: Number,
      default: 70
    },
    isFlexLayout:{
      type:Boolean,
      default:false
    }
  },
  data() {
    return {
      fieldVms: [],
      fieldArray: [],
      vnodeGroup: []
    };
  },
  computed: {
    calcSpan: {
      get() {
        return 24 / this.divide;
      }
    }
  },
  created() {
    const me = this;
    this.$slots.default.forEach((v, index) => {
      const groupId = Math.ceil((index + 1) / this.divide);
      let group = this.vnodeGroup[groupId - 1];
      if (!group) {
        group = [];
        this.vnodeGroup[groupId - 1] = group;
      }
      this.fieldArray.push({ ...v.componentOptions.propsData });
      group.push(v);
    });
    let this_ = this;
    console.log(this.$slots.default)
  },
  methods: {
    handleInputChange(obj, prop) {
      this.fieldArray = this.fieldArray.map((field, index) => {
        return field.prop == prop ? { ...field, ...obj } : field;
      });
    },
    handleFieldLoaded(ref) {
      // 搜索条件挂载完成后，添加其实例到数组中
      this.fieldVms.push(ref);
    },
    search() {
      this.$parent.$parent.$emit("advance-search", this.fieldArray);
    },
    reset() {
      this.fieldVms.forEach(vm => {
        vm.data = null;
      });
      this.$nextTick(() => {
        this.search();
      });
    }
  }
};
</script>
<style lang="scss" scoped>
.search-group {
  margin-bottom: 15px;
}
.flex-layout{
  display: flex;
  flex-wrap: wrap;
  &__search{
    display: flex;
    margin-bottom: 10px;
  }
  &__item{
    display: flex;
  }
}
</style>