<template>
    <div>
        <span v-for="(btn, index) of basicBtns" :key="btn.label">
            <PopconfirmDelete
                :url="getDelUrl(btn.url, row)"
                v-if="btn.type === 'confirm'"
                :cb="btn.after"
                :title="btn.title"
                :onOk="() => btn.onOk && btn.onOk(row)"
                :label="btn.label"
            />
            <a v-else @click="() => btn.click(row)" v-bind="btn.option">{{ btn.label }}</a>
            <a-divider type="vertical" v-if="moreBtns.length || index !== basicBtns.length - 1" />
        </span>

        <template v-if="moreBtns.length">
            <a-popover>
                <template slot="content">
                    <a-space direction="vertical">
                        <span v-for="btn of moreBtns" :key="btn.label">
                            <PopconfirmDelete
                                :url="getDelUrl(btn.url, row)"
                                v-if="btn.type === 'confirm'"
                                :cb="btn.after"
                                :title="btn.title"
                                :onOk="() => btn.onOk && btn.onOk(row)"
                                :label="btn.label"
                            />
                            <a v-else @click="() => btn.click(row)" v-bind="btn.option">{{ btn.label }}</a>
                        </span>
                    </a-space>
                </template>
                <a>...</a>
            </a-popover>
        </template>
    </div>
</template>

<script>
import { isFunction } from '@/utils';
import PopconfirmDelete from '@/components/popconfirm_delete/index.vue';

export default {
    components: { PopconfirmDelete },

    props: {
        buttons: {
            type: Array,
            default: () => [],
        },
        row: Object,
    },
    watch: {
        row() {
            this.init();
        },
    },
    data() {
        return {
            buttonsArr: [],
        };
    },
    created() {
        this.init();
    },
    computed: {
        basicBtns() {
            return this.buttonsArr.length > 3 ? this.buttonsArr.slice(0, 3) : this.buttonsArr;
        },
        moreBtns() {
            return this.buttonsArr.length > 3 ? this.buttonsArr.slice(3) : [];
        },
    },
    methods: {
        getDelUrl(url, row) {
            if (isFunction(url)) return url(row);
            return url;
        },
        init() {
            this.buttons.map((i) => {
                i.__hidden__ = i.isHidden && i.isHidden(this.row);
            });
            this.buttonsArr = this.buttons.filter((i) => !i.__hidden__);
        },
    },
};
</script>
