<template>
  <el-form ref="queryForm" :inline="true" :model="queryParams" label-width="90px" size="small">
    <el-form-item
      v-for="item in queryOptions"
      :key="item.value"
      :label="item.label"
      :prop="item.prop"
    >
      <template v-if="item.type === 'input'">
        <el-input
            v-model="queryParams[item.prop]"
            clearable
            :placeholder="`请输入${item.label}`"
            @keyup.enter.native="handleQuery"
        />
      </template>
      <template v-else-if="item.type === 'select'">
        <el-select v-model="queryParams[item.prop]" clearable :placeholder="`请选择${item.label}`">
          <el-option
              v-for="dict in item.dicts"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          />
        </el-select>
      </template>
      <template v-else-if="item.type === 'daterange'">
        <el-date-picker
            v-model="queryParams[item.prop]"
            end-placeholder="结束日期"
            range-separator="-"
            start-placeholder="开始日期"
            style="width: 240px"
            type="daterange"
            value-format="yyyy-MM-dd"
        />
      </template>
    </el-form-item>
    <el-form-item>
      <el-button icon="el-icon-search" size="mini" type="primary" @click="handleQuery">搜索</el-button>
      <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
export default {
  props: {
    defaultValue: {
      type: Object,
      default: () => {}
    },
    queryOptions: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      queryParams: {}
    }
  },
  created() {
    this.initValue();
  },
  watch: {
    defaultValue: {
      handler(val) {
        Object.keys(val).forEach(key => {
          if (val[key]) {
            this.$set(this.queryParams, key, val[key]);
          }
        });
      },
      deep: true,
      immediate: true
    }
  },
  methods: {
    initValue() {
      this.queryOptions.forEach(item => {
        if (item.prop && this.queryParams[item.prop] === void 0) {
          this.$set(this.queryParams, item.prop, void 0)
        }
      })
    },
    handleQuery() {
      this.$emit('query', this.queryParams)
    },
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery();
    }
  }
}
</script>

<style lang="scss" scoped>

</style>