<template>
    <div class="m-search">
        <el-form ref="searchForm" v-model="values" inline @submit.native.prevent>
            <SearchItem v-for="(item,index) in config" v-bind="item" v-model="values[item.prop]" :key="index" />
            <slot name="footer">
                <el-button icon="el-icon-plus" type="primary" size="small" @click="submit">搜索</el-button>
                <el-button icon="el-icon-refresh-right" type="default" size="small" @click="reset">重置</el-button>
            </slot>
        </el-form>

    </div>
</template>

<script>
import SearchItem from './form-item.vue'
export default {
    name: "McSearch",
    inheritAttrs: false,
    components: {
        SearchItem
    },
    props: {
        value: null,
        config: {
            type: Array,
            require: true,
            default: () => []
        },
        onSubmit: Function,
        onInput: Function
    },
    computed: {
        values: {
            get() {
                return this.value || {}
            },
            set(val) {
                this.onInput && this.onInput(val)
                this.$emit('input', val)
            }
        }
    },
    watch: {
        config: {
            handler: 'initValues',
            immediate: true,
            deep: true
        }
    },
    methods: {
        initValues() {
            this.values = this.config.reduce((values, item) => {
                values[item.prop] = item.value
                return values
            }, {})
        },
        submit() {
            const values = this.values;
            this.onSubmit && this.onSubmit(values)
            this.$emit('submit', values)
        },
        reset() {
            this.$emit('reset')
            this.$refs.searchForm.resetFields()
            this.initValues()
            this.submit()
        }
    },
}
</script>

<style lang="less" scoped>
.m-search{
   .el-button{
    margin-top: 4px;
   }
}
</style>