<template>
  <div class="menu-management">
    <Breadcrumb />

    <el-card class="table-card" shadow="never">
      <div class="table-toolbar">
        <div class="toolbar-left">
          <el-button
            v-permission="'sys:menu:add'"
            type="primary"
            :icon="CirclePlus"
            size="large"
            class="is-solid"
            @click="handleAdd()"
            >新增菜单</el-button
          >
          <el-button type="primary" :icon="Sort" size="large" class="is-solid" @click="toggleExpand"
            >展开/折叠</el-button
          >
        </div>
        <div class="toolbar-right">
          <el-input
            v-model="searchKeyword"
            :prefix-icon="Search"
            size="large"
            placeholder="菜单名称"
            style="width: 240px"
            clearable
          />
          <el-button
            :icon="Search"
            type="primary"
            class="is-solid"
            size="large"
            @click="handleSearch"
            >搜索</el-button
          >
          <el-button
            :icon="Refresh"
            type="primary"
            class="is-solid"
            size="large"
            @click="handleReset"
            >重置</el-button
          >
        </div>
      </div>

      <el-table
        ref="tableRef"
        :data="filteredMenuData"
        row-key="id"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
        border
        :default-expand-all="isExpandAll"
      >
        <el-table-column prop="name" label="菜单名称" min-width="180" />
        <el-table-column prop="type" label="类型" width="80" align="center">
          <template #default="{ row }">
            <el-tag v-if="row.type === 0" type="warning">目录</el-tag>
            <el-tag v-else-if="row.type === 1">菜单</el-tag>
            <el-tag v-else-if="row.type === 2" type="info">按钮</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="icon" label="图标" width="80" align="center">
          <template #default="{ row }">
            <el-icon v-if="row.icon" :size="16">
              <component :is="row.icon" />
            </el-icon>
          </template>
        </el-table-column>
        <el-table-column prop="permission" label="权限标识" min-width="150" />
        <el-table-column prop="sort" label="排序" width="80" align="center" />
        <el-table-column prop="status" label="状态" width="80" align="center">
          <template #default="{ row }">
            <el-tag :type="row.status === '正常' ? 'success' : 'danger'">{{ row.status }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" min-width="200" fixed="right" align="center">
          <template #default="{ row }">
            <template v-if="row.type !== 2">
              <el-button v-permission="'sys:menu:add'" type="primary" link @click="handleAdd(row)"
                >新增</el-button
              >
            </template>
            <el-button v-permission="'sys:menu:edit'" type="primary" link @click="handleEdit(row)"
              >编辑</el-button
            >
            <el-button
              v-permission="'sys:menu:delete'"
              type="danger"
              link
              @click="handleDelete(row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="600px" destroy-on-close>
      <el-form ref="formRef" :model="formData" :rules="formRules" label-width="100px">
        <el-form-item label="上级菜单">
          <el-input :model-value="parentMenuName" disabled />
        </el-form-item>

        <el-form-item label="菜单类型" prop="type">
          <el-radio-group v-model="formData.type" :disabled="isEdit" @change="handleTypeChange">
            <el-radio :value="0">目录</el-radio>
            <el-radio :value="1">菜单</el-radio>
            <el-radio :value="2">按钮</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="菜单名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入菜单名称" />
        </el-form-item>

        <template v-if="formData.type !== 2">
          <el-form-item label="图标" prop="icon">
            <el-input v-model="formData.icon" placeholder="请输入图标名称" />
          </el-form-item>
        </template>

        <template v-if="formData.type === 1">
          <el-form-item label="路由路径" prop="path">
            <el-input v-model="formData.path" placeholder="请输入路由路径" />
          </el-form-item>
          <el-form-item label="组件路径" prop="component">
            <el-input v-model="formData.component" placeholder="请输入组件路径" />
          </el-form-item>
        </template>

        <template v-if="formData.type === 2">
          <el-form-item label="权限标识" prop="permission">
            <el-input v-model="formData.permission" placeholder="请输入权限标识，如 sys:user:add" />
          </el-form-item>
        </template>

        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="formData.sort" :min="0" :max="999" controls-position="right" />
        </el-form-item>

        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="formData.status">
            <el-radio value="正常">正常</el-radio>
            <el-radio value="停用">停用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" class="is-gradient" @click="handleSubmit">确定</el-button>
          <el-button @click="dialogVisible = false">取消</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
  import type { FormInstance, FormRules } from 'element-plus'
  import { CirclePlus, Search, Refresh, Sort } from '@element-plus/icons-vue'

  // ==================== 类型定义 ====================

  interface MenuItem {
    id: number
    name: string
    type: number // 0=目录 1=菜单 2=按钮
    icon: string
    path: string
    component: string
    permission: string
    sort: number
    status: string
    children: MenuItem[]
  }

  // ==================== 表格数据 ====================

  const tableRef = ref<InstanceType<(typeof import('element-plus'))['ElTable']>>()
  const searchKeyword = ref('')
  const isExpandAll = ref(true)

  const menuData = ref<MenuItem[]>([
    {
      id: 1,
      name: '首页',
      type: 1,
      icon: 'HomeFilled',
      path: '/dashboard',
      component: 'dashboard/index',
      permission: '',
      sort: 0,
      status: '正常',
      children: [],
    },
    {
      id: 200,
      name: 'SDK管理',
      type: 1,
      icon: 'Box',
      path: '/sdk',
      component: 'sdk/index',
      permission: '',
      sort: 5,
      status: '正常',
      children: [
        {
          id: 201,
          name: '管理详情',
          type: 1,
          icon: 'Box',
          path: 'detail',
          component: 'sdk/detail',
          permission: '',
          sort: 1,
          status: '正常',
          children: [],
        },
      ],
    },
    {
      id: 100,
      name: '系统管理',
      type: 0,
      icon: 'Setting',
      path: '/system',
      component: '',
      permission: '',
      sort: 10,
      status: '正常',
      children: [
        {
          id: 101,
          name: '用户管理',
          type: 1,
          icon: 'User',
          path: 'user',
          component: 'system/user/index',
          permission: '',
          sort: 1,
          status: '正常',
          children: [
            {
              id: 1011,
              name: '新增用户',
              type: 2,
              icon: '',
              path: '',
              component: '',
              permission: 'sys:user:add',
              sort: 1,
              status: '正常',
              children: [],
            },
            {
              id: 1012,
              name: '编辑用户',
              type: 2,
              icon: '',
              path: '',
              component: '',
              permission: 'sys:user:edit',
              sort: 2,
              status: '正常',
              children: [],
            },
            {
              id: 1013,
              name: '删除用户',
              type: 2,
              icon: '',
              path: '',
              component: '',
              permission: 'sys:user:delete',
              sort: 3,
              status: '正常',
              children: [],
            },
          ],
        },
        {
          id: 102,
          name: '角色管理',
          type: 1,
          icon: 'UserFilled',
          path: 'role',
          component: 'system/role/index',
          permission: '',
          sort: 2,
          status: '正常',
          children: [
            {
              id: 1021,
              name: '新增角色',
              type: 2,
              icon: '',
              path: '',
              component: '',
              permission: 'sys:role:add',
              sort: 1,
              status: '正常',
              children: [],
            },
            {
              id: 1022,
              name: '编辑角色',
              type: 2,
              icon: '',
              path: '',
              component: '',
              permission: 'sys:role:edit',
              sort: 2,
              status: '正常',
              children: [],
            },
            {
              id: 1023,
              name: '删除角色',
              type: 2,
              icon: '',
              path: '',
              component: '',
              permission: 'sys:role:delete',
              sort: 3,
              status: '正常',
              children: [],
            },
            {
              id: 1024,
              name: '分配权限',
              type: 2,
              icon: '',
              path: '',
              component: '',
              permission: 'sys:role:assign',
              sort: 4,
              status: '正常',
              children: [],
            },
          ],
        },
        {
          id: 103,
          name: '菜单管理',
          type: 1,
          icon: 'Menu',
          path: 'menu',
          component: 'system/menu/index',
          permission: '',
          sort: 3,
          status: '正常',
          children: [
            {
              id: 1031,
              name: '新增菜单',
              type: 2,
              icon: '',
              path: '',
              component: '',
              permission: 'sys:menu:add',
              sort: 1,
              status: '正常',
              children: [],
            },
            {
              id: 1032,
              name: '编辑菜单',
              type: 2,
              icon: '',
              path: '',
              component: '',
              permission: 'sys:menu:edit',
              sort: 2,
              status: '正常',
              children: [],
            },
            {
              id: 1033,
              name: '删除菜单',
              type: 2,
              icon: '',
              path: '',
              component: '',
              permission: 'sys:menu:delete',
              sort: 3,
              status: '正常',
              children: [],
            },
          ],
        },
      ],
    },
    {
      id: 300,
      name: '内容管理',
      type: 0,
      icon: 'Document',
      path: '/content',
      component: '',
      permission: '',
      sort: 20,
      status: '正常',
      children: [
        {
          id: 301,
          name: '文章管理',
          type: 1,
          icon: 'Document',
          path: 'article',
          component: 'content/article/index',
          permission: '',
          sort: 1,
          status: '正常',
          children: [],
        },
      ],
    },
  ])

  // 搜索过滤（递归）
  const filteredMenuData = computed(() => {
    if (!searchKeyword.value) return menuData.value

    const keyword = searchKeyword.value.toLowerCase()

    function filterTree(items: MenuItem[]): MenuItem[] {
      return items
        .map((item) => ({ ...item, children: filterTree(item.children) }))
        .filter((item) => {
          const nameMatch = item.name.toLowerCase().includes(keyword)
          return nameMatch || item.children.length > 0
        })
    }

    return filterTree(menuData.value)
  })

  // ==================== 展开/折叠 ====================

  function toggleExpand() {
    isExpandAll.value = !isExpandAll.value
    // 重新渲染表格以应用展开/折叠
    const data = menuData.value
    menuData.value = []
    nextTick(() => {
      menuData.value = data
    })
  }

  // ==================== 搜索/重置 ====================

  function handleSearch() {
    // filteredMenuData is computed, searchKeyword triggers it
  }

  function handleReset() {
    searchKeyword.value = ''
  }

  // ==================== 对话框逻辑 ====================

  const dialogVisible = ref(false)
  const isEdit = ref(false)
  const currentRow = ref<MenuItem | null>(null)
  const formRef = ref<FormInstance>()

  const dialogTitle = computed(() => (isEdit.value ? '编辑菜单' : '新增菜单'))

  const parentMenuName = computed(() => {
    if (!currentRow.value) return '主目录'
    return currentRow.value.name
  })

  function getInitialFormData(): {
    parentId: number
    type: number
    name: string
    icon: string
    path: string
    component: string
    permission: string
    sort: number
    status: string
  } {
    return {
      parentId: 0,
      type: 0,
      name: '',
      icon: '',
      path: '',
      component: '',
      permission: '',
      sort: 0,
      status: '正常',
    }
  }

  const formData = reactive(getInitialFormData())

  const formRules = computed<FormRules>(() => ({
    type: [{ required: true, message: '请选择菜单类型', trigger: 'change' }],
    name: [{ required: true, message: '请输入菜单名称', trigger: 'blur' }],
    path:
      formData.type === 1 ? [{ required: true, message: '请输入路由路径', trigger: 'blur' }] : [],
    component:
      formData.type === 1 ? [{ required: true, message: '请输入组件路径', trigger: 'blur' }] : [],
    permission:
      formData.type === 2 ? [{ required: true, message: '请输入权限标识', trigger: 'blur' }] : [],
  }))

  function handleTypeChange() {
    // 清除切换类型后不相关的字段
    if (formData.type === 0) {
      formData.path = ''
      formData.component = ''
      formData.permission = ''
    } else if (formData.type === 1) {
      formData.permission = ''
    } else {
      formData.icon = ''
      formData.path = ''
      formData.component = ''
    }
  }

  function handleAdd(row?: MenuItem) {
    isEdit.value = false
    currentRow.value = row ?? null
    Object.assign(formData, getInitialFormData())
    if (row) {
      formData.parentId = row.id
      // 子级类型默认比父级深一层
      if (row.type === 0) formData.type = 1
      else if (row.type === 1) formData.type = 2
    }
    dialogVisible.value = true
  }

  function handleEdit(row: MenuItem) {
    isEdit.value = true
    currentRow.value = null
    Object.assign(formData, getInitialFormData())
    formData.type = row.type
    formData.name = row.name
    formData.icon = row.icon
    formData.path = row.path
    formData.component = row.component
    formData.permission = row.permission
    formData.sort = row.sort
    formData.status = row.status
    dialogVisible.value = true
  }

  function handleDelete(row: MenuItem) {
    ElMessageBox.confirm(`确认要删除菜单「${row.name}」吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
      .then(() => {
        // 从树中递归移除
        removeNode(menuData.value, row.id)
        ElMessage.success('删除成功')
      })
      .catch(() => {})
  }

  function removeNode(nodes: MenuItem[], id: number): boolean {
    const idx = nodes.findIndex((n) => n.id === id)
    if (idx !== -1) {
      nodes.splice(idx, 1)
      return true
    }
    for (const node of nodes) {
      if (removeNode(node.children, id)) return true
    }
    return false
  }

  async function handleSubmit() {
    if (!formRef.value) return
    await formRef.value.validate((valid) => {
      if (valid) {
        if (isEdit.value) {
          ElMessage.success('编辑成功（模拟）')
        } else {
          ElMessage.success('新增成功（模拟）')
        }
        dialogVisible.value = false
      }
    })
  }
</script>

<style lang="scss" scoped>
  .menu-management {
    .table-card {
      margin-top: 10px;
    }

    .table-toolbar {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 16px;
    }

    .toolbar-left,
    .toolbar-right {
      display: flex;
      align-items: center;
      gap: 8px;
    }
  }
</style>
