<template>
  <SKMenuManagement
    :items="menuItems"
    :loading="loading"
    :permission-options="permissionOptions"
    :status-options="statusOptions"
    @edit="onEdit"
  />
</template>

<script setup lang="ts">
import type { MenuItem } from '@/components/SKMenuManagement.vue'
import { ref } from 'vue'
import SKMenuManagement from '@/components/SKMenuManagement.vue'

const loading = ref(false)
const statusOptions = [
  { title: '已啟用', value: 1 },
  { title: '已禁用', value: 0 },
]
const permissionOptions = ['管理員', '一級主管', '二級主管', '使用者']
const menuItems = ref([
  {
    id: 1,
    title: '工作台',
    permission: '使用者',
    path: '/workspace',
    component: '/dashboard/workspace/index',
    status: 1,
    children: [],
  },
  {
    id: 2,
    title: '系統管理',

    permission: '管理員',
    path: '/system',
    component: 'LAYOUT',
    status: 1,
    isNew: true,
    children: [
      {
        id: 21,
        title: '菜單管理',

        permission: '管理員',
        path: '/system/menu',
        component: '/system/menu/list',
        status: 1,
        children: [
          {
            id: 211,
            title: '新增',
            permission: '管理員',
            status: 1,
          },
          {
            id: 212,
            title: '修改',
            permission: '管理員',
            status: 1,
          },
          {
            id: 213,
            title: '刪除',
            permission: '管理員',
            status: 1,
          },
        ],
      },
      {
        id: 22,
        title: '部門管理',
        permission: '一級主管',
        path: '/system/dept',
        component: '/system/dept/list',
        status: 1,
        children: [],
      },
    ],
  },
  {
    id: 3,
    title: '項目',
    permission: '二級主管',
    path: '/vben-admin',
    component: 'LAYOUT',
    status: 1,
    children: [
      {
        id: 31,
        title: '文檔',
        permission: '使用者',
        path: '/vben-admin/document',
        component: 'https://doc.vben.pro',
        status: 1,
      },
      {
        id: 32,
        title: 'Ant Design Vue 版本',
        permission: '使用者',
        path: '/vben-admin/antdv',
        component: 'https://ant.vben.pro',
        status: 0,
      },
    ],
  },
  {
    id: 4,
    title: '關於',
    permission: '使用者',
    path: '/about',
    component: '_core/about/index',
    status: 1,
    children: [],
  },
])

function updateTreeItemById (items: MenuItem[], updated: MenuItem): boolean {
  for (let i = 0; i < items.length; i += 1) {
    const current = items[i]
    if (!current) continue

    if (current.id === updated.id) {
      items[i] = {
        ...current,
        status: updated.status,
        permission: updated.permission,
      }
      return true
    }

    if (current.children && current.children.length > 0) {
      const found = updateTreeItemById(current.children, updated)
      if (found) return true
    }
  }
  return false
}

function onEdit (item: MenuItem) {
  updateTreeItemById(menuItems.value, item)
}
</script>
