<template>
    <my-table
        url="/api/v1/menus"
        :addBtn="addBtn"
        :formatData="formatData"
        rowKey="menuId"
        noPage
        ref="table"
    >
        <template #drawer>
            <AddCom v-if="addCom" :row="currentClickRow" ref="addCom" />
            <Form ref="addForm" v-else />
        </template>

        <a-table-column :title="$t('menu.name')" data-index="menuName" />
        <a-table-column :title="$t('menu.type')" data-index="menuTypeName" />
        <a-table-column
            :title="$t('menu.order')"
            data-index="viewIndex"
            :sorter="sorter"
            sortOrder="ascend"
        />
        <a-table-column :title="$t('menu.icon')" data-index="menuIcon" />
        <a-table-column title="URL" data-index="menuUrl" />
        <a-table-column :title="$t('table.operation')">
            <template #default="row">
                <my-ac-btn :row="row" :buttons="buttons" />
            </template>
        </a-table-column>
    </my-table>
</template>

<script>
import { convertListToTree } from '@/utils';
import Form from './form.vue';
import AddCom from './add_com.vue';

export default {
    data: (vm) => ({
        addCom: false,
        currentClickRow: null,
        addBtn: {
            text: vm.$t('table.add'),
            onOk() {
                return vm.addCom ? vm.$refs['addCom']?.submit() : vm.$refs['addForm']?.submit();
            },
            onCancel() {
                vm.addCom = false;
                vm.currentClickRow = null;
            },
        },
        sortOrder: 'ascend',
        buttons: [
            {
                label: vm.$t('menu.addComponent'),
                option: {
                    style: 'color: #ff4d4f',
                },
                click(row) {
                    vm.show();
                    vm.addCom = true;
                    vm.currentClickRow = row;
                },
                isHidden: (row) => row.menuType !== 'MENU',
            },
            { label: vm.$t('table.edit'), click: vm.edit },
            { type: 'confirm', url: (row) => `/api/v1/menus/${row.menuId}`, after: vm.refreshTable },
        ],
    }),

    components: { Form, AddCom },

    methods: {
        formatData: convertListToTree,
        refreshTable() {
            this.$refs['table'].getData();
        },
        sorter(pre, next) {
            return pre.viewIndex - next.viewIndex;
        },
        edit(data) {
            this.$refs['table']?.show({ type: 1 });
            this.$nextTick(() => {
                this.$refs['addForm'].setEdit({ ...data });
            });
        },
        show() {
            this.$refs['table'].show({ title: this.$t('menu.menuComponent') });
        },
    },
};
</script>
