<template>
    <app-view class="system-menu">
        <app-table ref="tableRef" :data="dataList" v-model:columns="columns" row-key="resourcecode">
            <template #header>
                <el-button type="primary" icon="Plus" @click="openEditComponent">新增</el-button>
                <el-button type="primary" :icon="isRowExpansion ? 'FolderOpened' : 'Folder'" @click="tableExpandAll">
                    <span v-if="isRowExpansion">全部收起</span>
                    <span v-else>全部展开</span>
                </el-button>
            </template>
            <template #operate="{ row }">
                <el-button type="primary" icon="Edit" @click="openEditComponent(row)" link>编辑</el-button>
                <el-button type="danger" icon="Delete" link>删除</el-button>
            </template>
        </app-table>
        <component :is="componentMap.get(componentId)" v-bind="{ selectedRow }" @closed="closeComponent"
            v-if="componentId" />
    </app-view>
</template>

<script lang="ts" setup>
import { ref, defineAsyncComponent } from 'vue'
import { ElMessage } from 'element-plus'
import { useComponent } from '@/hooks/component'
import { useMenu } from '@/business/menu'
import AppTable from '@pc/components/base/table/index.vue'

const componentMap = new Map<string, unknown>([
    ['edit', defineAsyncComponent(() => import('./components/edit/index.vue'))]
])

const { dataList, columns, getMenuList } = useMenu()
const { componentId, openComponent, closeComponent } = useComponent(() => getMenuList())
const tableRef = ref()
const isRowExpansion = ref(false)
const selectedRow = ref<Ermcp.NewFuncmenuRsp>()

const openEditComponent = (row?: Ermcp.NewFuncmenuRsp) => {
    selectedRow.value = row
    openComponent('edit')
}

// 展开或收起表格
const tableExpandAll = () => {
    const table = tableRef.value.elTable
    isRowExpansion.value = !isRowExpansion.value
    const toggleRowExpansionAll = (data: Ermcp.NewFuncmenuRsp[]) => {
        data.forEach((item) => {
            table.toggleRowExpansion(item, isRowExpansion.value)
            if (item.children) {
                toggleRowExpansionAll(item.children)
            }
        })
    }
    toggleRowExpansionAll(dataList.value)
}

getMenuList().catch((err) => ElMessage.error(err))
</script>

<style lang="less">
@import './index.less';
</style>