<template>
    <a-button v-if="buttonType == 'submit'" v-debounce="onClick" :type="type" :disabled="disabled" v-bind="$attrs">
        <slot></slot>
    </a-button>
    <a-button v-else :type="type" v-bind="$attrs" v-on="$listeners">
        <slot></slot>
    </a-button>
</template>

<script>
import { debounce } from 'throttle-debounce'
import { on, off } from '@/utils/dom'
let fn = null
let defaultTime = 300
export default {
    name: 'ProButton',
    props: {
        buttonType: {
            type: String,
            default: () => ''
        },
        type: {//原生按钮组件type属性，直接透传给el-button点击按钮可能会导致页面刷新，原因未知
            type: String,
            default: () => ''
        },
    },
    data () {
        return {
            disabled: false
        };
    },
    methods: {
        onClick (e) {
            const _this = this;
            _this.disabled = true;
            let payload = {
                event: e,
                setDisabled: _this.setDisabled
            }
            this.$emit('click', payload)
        },
        /**
         * 设置按钮置灰
         * @param {*} disabled
         */
        setDisabled (disabled) {
            this.disabled = disabled
        }
    },
    directives: {
        debounce: {
            bind (el, { value, arg, modifiers }) {
                fn = debounce(arg || defaultTime, value)
                on(el, 'click', fn)
            },

            unbind: function (el) {
                if (fn) {
                    off(el, 'click', fn)
                }
            }
        }
    }
}
</script>
