<template>
    <app-view>
        <app-table ref="tableRef" :data="dataList" v-model:columns="columns" row-key="resourceCode">
            <template #headerLeft>
                <div>
                    <el-button icon="Plus" @click="showComponent('edit')">新增</el-button>
                </div>
                <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 size="small" icon="Edit" circle @click="showComponent('edit', row)" />
                <el-button size="small" icon="Delete" circle @click="showComponent('delete', row)" />
            </template>
        </app-table>
        <component ref="componentRef" v-bind="{ record }" :is="componentMap.get(componentId)" @closed="closeComponent"
            v-if="componentId" />
    </app-view>
</template>

<script lang="ts" setup>
import { shallowRef, defineAsyncComponent } from 'vue'
import { useComponent } from '@/hooks/component'
import { useRequest } from '@/hooks/request'
import { getAllMenus } from '@/services/api/user'
import AppTable from '@pc/components/base/table/index.vue'

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

const record = shallowRef<Model.MenusRsp>()
const tableRef = shallowRef()
const isRowExpansion = shallowRef(false)

const { componentRef, componentId, openComponent, closeComponent } = useComponent(() => run())

const { dataList, run } = useRequest(getAllMenus)

const columns = shallowRef([
    { field: 'title', label: '菜单', align: 'left' },
    { field: 'resourceCode', label: '代码', },
    { field: 'url', label: '路由', },
    { field: 'icon', label: '图标', },
    { field: 'operate', label: 'common.operate', fixed: 'right' }
])

const showComponent = (componentName: string, row?: Model.MenusRsp) => {
    record.value = row
    openComponent(componentName)
}

// 展开或收起表格
const tableExpandAll = () => {
    const table = tableRef.value.elTable
    isRowExpansion.value = !isRowExpansion.value

    const toggleRowExpansionAll = (data: Model.MenusRsp[]) => {
        data.forEach((item) => {
            table.toggleRowExpansion(item, isRowExpansion.value)
            if (item.children) {
                toggleRowExpansionAll(item.children)
            }
        })
    }

    toggleRowExpansionAll(dataList.value)
}
</script>