<template>
    <component :is="config.layout.layoutMode"></component>
</template>

<script setup lang="ts">
import { reactive } from 'vue'
import { useConfig } from '/@/stores/config'
import { useNavTabs } from '/@/stores/navTabs'
import { useTerminal } from '/@/stores/terminal'
import { useSiteConfig } from '/@/stores/siteConfig'
import { useAdminInfo } from '/@/stores/adminInfo'
import { useRoute } from 'vue-router'
import Default from '/@/layouts/backend/container/default.vue'
import Classic from '/@/layouts/backend/container/classic.vue'
import Streamline from '/@/layouts/backend/container/streamline.vue'
import Double from '/@/layouts/backend/container/double.vue'
import { onMounted, onBeforeMount } from 'vue'
import { Session } from '/@/utils/storage'
import { index } from '/@/api/backend'
import { handleAdminRoute, getFirstRoute, routePush } from '/@/utils/router'
import router from '/@/router/index'
import { adminBaseRoutePath } from '/@/router/static/adminBase'
import { useEventListener } from '@vueuse/core'
import { BEFORE_RESIZE_LAYOUT } from '/@/stores/constant/cacheKey'
import { isEmpty } from 'lodash-es'
import { setNavTabsWidth } from '/@/utils/layout'
import { id } from 'element-plus/es/locales.mjs'
import { menuTree } from '/@/api/backend'

defineOptions({
    components: { Default, Classic, Streamline, Double },
})

const terminal = useTerminal()
const navTabs = useNavTabs()
const config = useConfig()
const route = useRoute()
const siteConfig = useSiteConfig()
const adminInfo = useAdminInfo()

const state = reactive({
    autoMenuCollapseLock: false,
})

onMounted(() => {
    if (!adminInfo.token) return router.push({ name: 'adminLogin' })

    init()
    setNavTabsWidth()
    useEventListener(window, 'resize', setNavTabsWidth)
})
onBeforeMount(() => {
    onAdaptiveLayout()
    useEventListener(window, 'resize', onAdaptiveLayout)
})

const menu = [
    {
        id: 1,
        pid: 0,
        type: 'menu',
        title: '控制台',
        name: 'dashboard',
        path: 'dashboard',
        icon: 'fa fa-dashboard',
        menu_type: 'tab',
        url: '',
        component: '\/src\/views\/backend\/dashboard.vue',
        keepalive: 'dashboard',
        extend: 'none',
        children: [
            {
                id: 94,
                pid: 1,
                type: 'button',
                title: '查看',
                name: 'dashboard\/index',
                path: '',
                icon: '',
                menu_type: null,
                url: '',
                component: '',
                keepalive: 0,
                extend: 'none',
            },
        ],
    },
    {
        id: 2,
        pid: 0,
        type: 'menu_dir',
        title: '权限管理',
        name: 'auth',
        path: 'auth',
        icon: 'fa fa-group',
        menu_type: null,
        url: '',
        component: '',
        keepalive: 0,
        extend: 'none',
        children: [
            {
                id: 816,
                pid: 108,
                type: 'menu',
                title: '菜单配置',
                name: 'auth\/menuManagement',
                path: 'auth\/menuManagement',
                icon: 'fa fa-group',
                menu_type: 'tab',
                url: '',
                component: '\/src\/views\/backend\/auth\/menuManagement\/index.vue',
                keepalive: 'auth\/menuManagement',
                extend: 'none',
                children: [],
            },
            {
                id: 777,
                pid: 201,
                type: 'menu',
                title: '用户管理',
                name: 'auth\/userManagement',
                path: 'auth\/userManagement',
                icon: 'fa fa-group',
                menu_type: 'tab',
                url: '',
                component: '\/src\/views\/backend\/auth\/userManagement\/index.vue',
                keepalive: 'auth\/userManagement',
                extend: 'none',
                children: [],
            },
            {
                id: 8,
                pid: 2,
                type: 'menu',
                title: '管理员管理',
                name: 'auth\/admin',
                path: 'auth\/admin',
                icon: 'el-icon-UserFilled',
                menu_type: 'tab',
                url: '',
                component: '\/src\/views\/backend\/auth\/admin\/index.vue',
                keepalive: 'auth\/admin',
                extend: 'none',
                children: [
                    {
                        id: 9,
                        pid: 8,
                        type: 'button',
                        title: '查看',
                        name: 'auth\/admin\/index',
                        path: '',
                        icon: '',
                        menu_type: null,
                        url: '',
                        component: '',
                        keepalive: 0,
                        extend: 'none',
                    },
                    {
                        id: 10,
                        pid: 8,
                        type: 'button',
                        title: '添加',
                        name: 'auth\/admin\/add',
                        path: '',
                        icon: '',
                        menu_type: null,
                        url: '',
                        component: '',
                        keepalive: 0,
                        extend: 'none',
                    },
                    {
                        id: 11,
                        pid: 8,
                        type: 'button',
                        title: '编辑',
                        name: 'auth\/admin\/edit',
                        path: '',
                        icon: '',
                        menu_type: null,
                        url: '',
                        component: '',
                        keepalive: 0,
                        extend: 'none',
                    },
                    {
                        id: 12,
                        pid: 8,
                        type: 'button',
                        title: '删除',
                        name: 'auth\/admin\/del',
                        path: '',
                        icon: '',
                        menu_type: null,
                        url: '',
                        component: '',
                        keepalive: 0,
                        extend: 'none',
                    },
                ],
            },
            {
                id: 13,
                pid: 2,
                type: 'menu',
                title: '菜单规则管理',
                name: 'auth\/rule',
                path: 'auth\/rule',
                icon: 'el-icon-Grid',
                menu_type: 'tab',
                url: '',
                component: '\/src\/views\/backend\/auth\/rule\/index.vue',
                keepalive: 'auth\/rule',
                extend: 'none',
                children: [
                    {
                        id: 14,
                        pid: 13,
                        type: 'button',
                        title: '查看',
                        name: 'auth\/rule\/index',
                        path: '',
                        icon: '',
                        menu_type: null,
                        url: '',
                        component: '',
                        keepalive: 0,
                        extend: 'none',
                    },
                    {
                        id: 15,
                        pid: 13,
                        type: 'button',
                        title: '添加',
                        name: 'auth\/rule\/add',
                        path: '',
                        icon: '',
                        menu_type: null,
                        url: '',
                        component: '',
                        keepalive: 0,
                        extend: 'none',
                    },
                    {
                        id: 16,
                        pid: 13,
                        type: 'button',
                        title: '编辑',
                        name: 'auth\/rule\/edit',
                        path: '',
                        icon: '',
                        menu_type: null,
                        url: '',
                        component: '',
                        keepalive: 0,
                        extend: 'none',
                    },
                    {
                        id: 17,
                        pid: 13,
                        type: 'button',
                        title: '删除',
                        name: 'auth\/rule\/del',
                        path: '',
                        icon: '',
                        menu_type: null,
                        url: '',
                        component: '',
                        keepalive: 0,
                        extend: 'none',
                    },
                    {
                        id: 18,
                        pid: 13,
                        type: 'button',
                        title: '快速排序',
                        name: 'auth\/rule\/sortable',
                        path: '',
                        icon: '',
                        menu_type: null,
                        url: '',
                        component: '',
                        keepalive: 0,
                        extend: 'none',
                    },
                ],
            },
            {
                id: 19,
                pid: 2,
                type: 'menu',
                title: '管理员日志管理',
                name: 'auth\/adminLog',
                path: 'auth\/adminLog',
                icon: 'el-icon-List',
                menu_type: 'tab',
                url: '',
                component: '\/src\/views\/backend\/auth\/adminLog\/index.vue',
                keepalive: 'auth\/adminLog',
                extend: 'none',
                children: [
                    {
                        id: 20,
                        pid: 19,
                        type: 'button',
                        title: '查看',
                        name: 'auth\/adminLog\/index',
                        path: '',
                        icon: '',
                        menu_type: null,
                        url: '',
                        component: '',
                        keepalive: 0,
                        extend: 'none',
                    },
                ],
            },
            {
                id: 99,
                pid: 98,
                type: 'menu',
                title: '角色管理',
                name: 'auth\/RoleManagement',
                path: 'auth\/RoleManagement',
                icon: 'fa fa-group',
                menu_type: 'tab',
                url: '',
                component: '\/src\/views\/backend\/RoleManagement\/RoleManagement.vue',
                keepalive: 'auth\/RoleManagement',
                extend: 'none',
                children: [],
            },
            {
                id: 97,
                pid: 96,
                type: 'menu',
                title: '机构管理',
                name: 'auth\/InstitutionalManagement',
                path: 'auth\/InstitutionalManagement',
                icon: 'fa fa-group',
                menu_type: 'tab',
                url: '',
                component: '\/src\/views\/backend\/InstitutionalManagement\/InstitutionalManagement.vue',
                keepalive: 'auth\/InstitutionalManagement',
                extend: 'none',
                children: [],
            },
        ],
    },
]

function transformNode(menu: any) {
    menu = menu.map((node: any) => {
        return {
            id: Number(node.id),
            pid: node.parentMenuId,
            type: node.children.length != 0 ? 'menu_dir' : 'menu',
            title: node.menuName,
            name: node.menuName,
            path: node.menuName,
            icon: node.menuIcon,
            menu_type: node.children.length != 0 ? null : 'tab',
            component: node.children.length != 0 ? '' : '/src/views/backend' + node.funParam,
            extend: 'none',
            children: node.children.map(transformNode),
        }
    })
    return menu
}
const init = () => {
    menuTree().then((res: any) => {
        console.log('🚀 ~ menusLoginTree ~ res:', res)
        const menu = transformNode(res.data.children)
        console.log('🚀 ~ menusLoginTree ~ menu:', menu)
        handleAdminRoute(menu)
        if (route.params.to) {
            const lastRoute = JSON.parse(route.params.to as string)
            if (lastRoute.path != adminBaseRoutePath) {
                let query = !isEmpty(lastRoute.query) ? lastRoute.query : {}
                routePush({ path: decodeURIComponent(lastRoute.path), query: query })
                return
            }
        }

        // 跳转到第一个菜单
        let firstRoute = getFirstRoute(navTabs.state.tabsViewRoutes)
        if (firstRoute) routePush(firstRoute.path)
    })
    // handleAdminRoute(menu)
    // if (route.params.to) {
    //     const lastRoute = JSON.parse(route.params.to as string)
    //     if (lastRoute.path != adminBaseRoutePath) {
    //         let query = !isEmpty(lastRoute.query) ? lastRoute.query : {}
    //         routePush({ path: lastRoute.path, query: query })
    //         return
    //     }
    // }

    // // 跳转到第一个菜单
    // let firstRoute = getFirstRoute(navTabs.state.tabsViewRoutes)
    // if (firstRoute) routePush(firstRoute.path)

    /**
     * 后台初始化请求，获取站点配置，动态路由等信息
     */
    // index().then((res) => {
    // siteConfig.dataFill(res.data.siteConfig)
    // terminal.changePort(res.data.terminal.installServicePort)
    // terminal.changePackageManager(res.data.terminal.npmPackageManager)
    // siteConfig.setInitialize(true)

    // if (!isEmpty(res.data.adminInfo)) {
    //     adminInfo.dataFill(res.data.adminInfo)
    //     siteConfig.setUserInitialize(true)
    // }

    // if (res.data) {

    // 预跳转到上次路径

    // }
    // })
}

const onAdaptiveLayout = () => {
    let defaultBeforeResizeLayout = {
        layoutMode: config.layout.layoutMode,
        menuCollapse: config.layout.menuCollapse,
    }
    let beforeResizeLayout = Session.get(BEFORE_RESIZE_LAYOUT)
    if (!beforeResizeLayout) Session.set(BEFORE_RESIZE_LAYOUT, defaultBeforeResizeLayout)

    const clientWidth = document.body.clientWidth
    if (clientWidth < 1024) {
        /**
         * 锁定窗口改变自动调整 menuCollapse
         * 避免已是小窗且打开了菜单栏时，意外的自动关闭菜单栏
         */
        if (!state.autoMenuCollapseLock) {
            state.autoMenuCollapseLock = true
            config.setLayout('menuCollapse', true)
        }
        config.setLayout('shrink', true)
        config.setLayoutMode('Classic')
    } else {
        state.autoMenuCollapseLock = false
        let beforeResizeLayoutTemp = beforeResizeLayout || defaultBeforeResizeLayout

        config.setLayout('menuCollapse', beforeResizeLayoutTemp.menuCollapse)
        config.setLayout('shrink', false)
        config.setLayoutMode(beforeResizeLayoutTemp.layoutMode)
    }
}
</script>
