<template>
    <div>
        <a-button type="primary" class="tw-mb-2" @click="add">新增</a-button>
        <a-table :dataSource="components" :rowKey="getRowKey" :pagination="false">
            <a-table-column title="组件编码">
                <template #default="row">
                    <span v-if="row.componentId">{{ row.componentCode }}</span>
                    <a-input v-else v-model="row.componentCode" />
                </template>
            </a-table-column>
            <a-table-column title="组件名称">
                <template #default="row">
                    <span v-if="row.componentId">{{ row.componentName }}</span>
                    <a-input v-else v-model="row.componentName" />
                </template>
            </a-table-column>
            <a-table-column title="操作">
                <template #default="row">
                    <a @click="() => del(row)">删除</a>
                </template>
            </a-table-column>
        </a-table>
    </div>
</template>

<script>
import { getMenuComponentApi, addMenuComponentApi } from '@/api';

export default {
    props: ['row'],

    data: () => ({
        components: [],
    }),

    mounted() {
        this.getData();
    },

    methods: {
        async getData() {
            const { menuId } = this.row;
            this.components = await getMenuComponentApi(menuId);
        },
        add() {
            this.components.push({
                componentCode: '',
                componentName: '',
                __key__: this.components.length,
            });
        },
        del(row) {
            this.components = this.components.filter(r => r !== row);
        },
        getRowKey(row) {
            return row.__key__ ? row.__key__ : row.componentId;
        },
        submit() {
            const { menuId } = this.row;

            return addMenuComponentApi(
                menuId,
                this.components.map(i => {
                    delete i.__key__;
                    return i;
                }),
            );
        },
    },
};
</script>
