<template>
  <div class="search">
    <div v-for="(item, index) in searchOptions" :key="index" class="search-item">
      <template v-if="item.type === 'input'">
        <span class="search-item-title">{{ item.title }}</span>
        <a-input v-model="form[item.field]" :placeholder="item.placeholder"></a-input>
      </template>
      <template v-if="item.type === 'select'">
        <span class="search-item-title">{{ item.title }}</span>
        <a-select :default-value="form[item.field]" @change="value => selectChange(value, item.field)">
          <a-select-option v-for="itemSelect in item.selectOptions" :key="itemSelect.value" :value="itemSelect.value">
            {{ itemSelect.label }}
          </a-select-option>
        </a-select>
      </template>
      <template v-if="item.type === 'datepicker'">
        <span class="search-item-title">{{ item.title }}</span>
        <a-range-picker
          :placeholder="['开始', '结束']"
          @change="(date, dateString) => rangeChange(date, dateString, item.field)"
        />
      </template>
    </div>
    <a-button type="primary" @click="search">搜索</a-button>
  </div>
</template>

<script>
export default {
  props: {
    searchOptions: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      form: {}
    }
  },
  created() {
    this.formInit()
  },
  methods: {
    formInit() {
      const obj = {}
      this.searchOptions.forEach(v => {
        obj[v.field] = v.defaultValue
      })
      this.form = obj
    },
    selectChange(value, field) {
      this.form[field] = value
    },
    rangeChange(date, dateString, field) {
      this.form[field] = dateString
    },
    search() {
      this.$emit('search', this.form)
    }
  }
}
</script>

<style lang="less" scoped>
.search {
  display: flex;
  flex-direction: row;
  padding: 20px 0;
  &-item {
    margin-right: 12px;
    &-title {
      margin-right: 8px;
    }
  }
}
</style>
