<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="名称" data-index="menuName" />
        <a-table-column title="类型" data-index="menuTypeName" />
        <a-table-column title="显示排序" data-index="viewIndex" :sorter="sorter" sortOrder="ascend" />
        <a-table-column title="显示图标" data-index="menuIcon" />
        <a-table-column title="模块URL" data-index="menuUrl" />
        <a-table-column title="操作">
            <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: '新建',
            onOk() {
                return vm.addCom ? vm.$refs['addCom']?.submit() : vm.$refs['addForm']?.submit();
            },
            onCancel() {
                vm.addCom = false;
                vm.currentClickRow = null;
            },
        },
        sortOrder: 'ascend',
        buttons: [
            {
                label: '新增组件',
                option: {
                    style: 'color: #ff4d4f',
                },
                click(row) {
                    vm.show();
                    vm.addCom = true;
                    vm.currentClickRow = row;
                },
                isHidden: row => row.menuType !== 'MENU',
            },
            { label: '编辑', 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: '菜单组件' });
        },
    },
};
</script>
