<template>
  <div class="page-wrapper">
    <el-card shadow="never">
      <template #header>
        <div class="card-header-title">
          <el-icon><Menu /></el-icon>
          <span>菜单管理</span>
        </div>
      </template>
      <div class="menu-toolbar">
        <span class="toolbar-label">选择系统</span>
        <el-select v-model="currentSystemId" placeholder="请选择系统" style="width: 240px" @change="fetchMenuTree">
          <el-option v-for="sys in systemList" :key="sys.systemId" :label="sys.systemName" :value="sys.systemId" />
        </el-select>
        <el-button type="primary" @click="openForm(null)" :disabled="!currentSystemId">
          <el-icon><Plus /></el-icon>新增菜单
        </el-button>
        <el-button @click="toggleExpand">
          <el-icon><Expand /></el-icon>
          {{ isExpandAll ? '折叠全部' : '展开全部' }}
        </el-button>
      </div>
    </el-card>

    <el-card shadow="never">
      <el-table ref="tableRef" :data="menuTreeData" border row-key="id"
        :tree-props="{ children: 'children' }" :default-expand-all="true" v-loading="loading" style="width:100%">
        <el-table-column prop="menuName" label="菜单名称" width="200" />
        <el-table-column prop="icon" label="图标" width="80" align="center">
          <template #default="{ row }">
            <img v-if="row.icon && (row.icon.startsWith('http') || row.icon.startsWith('/zgapi'))" :src="row.icon" style="width:18px;height:18px;object-fit:contain" />
            <el-icon v-else-if="row.icon" :size="18"><component :is="getIconComponent(row.icon)" /></el-icon>
            <span v-else style="color:var(--text-muted)">-</span>
          </template>
        </el-table-column>
        <el-table-column prop="path" label="路由路径" width="180" show-overflow-tooltip />
        <el-table-column prop="component" label="组件" width="180" show-overflow-tooltip />
        <el-table-column prop="menuType" label="类型" width="80" align="center">
          <template #default="{ row }">
            <el-tag :type="row.menuType === 1 ? '' : row.menuType === 2 ? 'success' : 'warning'" effect="dark" size="small">
              {{ menuTypeMap[row.menuType] ?? '未知' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="permission" label="权限标识" width="160" show-overflow-tooltip />
        <el-table-column prop="sortOrder" label="排序" width="80" align="center" />
        <el-table-column prop="status" label="状态" width="80" align="center">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'danger'" effect="dark" size="small">
              {{ row.status === 1 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="280" align="center" class-name="ops-col">
          <template #default="{ row }">
            <div class="actions">
              <el-button type="primary" size="small" plain @click="openForm(row)">新增子级</el-button>
              <el-button type="primary" size="small" plain @click="openForm(null, row)">编辑</el-button>
              <el-button type="danger" size="small" plain @click="handleDelete(row)">删除</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 表单弹窗 -->
    <el-dialog v-model="dlg.visible" :title="dlg.title" width="600px" :close-on-click-modal="false" @closed="resetForm">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="90px">
        <el-form-item label="上级菜单" v-if="!dlg.isEdit">
          <el-tree-select v-model="form.parentId" :data="parentTree" :props="{ value:'id', label:'menuName', children:'children' }"
            node-key="id" placeholder="留空为顶级菜单" clearable check-strictly style="width:100%" />
        </el-form-item>
        <el-form-item label="菜单名称" prop="menuName">
          <el-input v-model="form.menuName" placeholder="请输入菜单名称" />
        </el-form-item>
        <el-form-item label="菜单类型" prop="menuType">
          <el-radio-group v-model="form.menuType">
            <el-radio-button :value="1">目录</el-radio-button>
            <el-radio-button :value="2">菜单</el-radio-button>
            <el-radio-button :value="3">按钮</el-radio-button>
          </el-radio-group>
        </el-form-item>

        <template v-if="form.menuType === 3">
          <el-form-item label="权限标识" prop="permission">
            <el-input v-model="form.permission" placeholder="如: system:user:add" />
          </el-form-item>
        </template>
        <template v-else>
          <el-form-item label="路由路径" :prop="form.menuType === 2 ? 'menuPath' : undefined">
            <el-input v-model="form.menuPath" placeholder="请输入路由路径" />
          </el-form-item>
          <el-form-item label="组件路径" v-if="form.menuType === 2">
            <el-input v-model="form.component" placeholder="请输入组件路径" />
          </el-form-item>
          <el-form-item label="图标">
            <IconPicker v-model="form.icon" />
          </el-form-item>
        </template>

        <el-form-item label="排序" prop="sortOrder">
          <el-input-number v-model="form.sortOrder" :min="0" :max="9999" />
        </el-form-item>
        <el-form-item label="状态">
          <el-switch v-model="form.status" :active-value="1" :inactive-value="0" active-text="启用" inactive-text="禁用" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dlg.visible = false">取消</el-button>
        <el-button type="primary" :loading="dlg.loading" @click="submitForm">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Expand, Menu } from '@element-plus/icons-vue'
import { getIconComponent } from '@/utils/icons'
import type { FormInstance, FormRules } from 'element-plus'
import request from '@/utils/request'
import IconPicker from '@/components/IconPicker.vue'

const menuTypeMap: Record<number, string> = { 1: '目录', 2: '菜单', 3: '按钮' }

interface MenuItem {
  id?: string; parentId: string | null; menuName: string; menuPath: string; path?: string
  component: string; icon: string; menuType: number; permission: string
  sortOrder: number; status: number; children?: MenuItem[]
}

// 系统列表
const systemList = ref<any[]>([])
const currentSystemId = ref<string>()
const menuTreeData = ref<MenuItem[]>([])
const loading = ref(false)
const isExpandAll = ref(true)
const tableRef = ref()
const parentTree = ref<any[]>([])

onMounted(async () => {
  try {
    const res = await request.get('/zgapi/v1/auth/system/list')
    systemList.value = res.data ?? []
    // 默认选 gateway 系统
    const gw = systemList.value.find((s: any) => s.systemCode === 'gateway')
    if (gw) { currentSystemId.value = gw.systemId; await fetchMenuTree() }
  } catch { /* ignore */ }
})

async function fetchMenuTree() {
  if (!currentSystemId.value) { menuTreeData.value = []; return }
  loading.value = true
  try {
    const res = await request.get('/zgapi/v1/admin/menu/tree', { params: { systemId: currentSystemId.value } })
    menuTreeData.value = res.data ?? []
    parentTree.value = res.data ?? []
  } catch { menuTreeData.value = [] } finally { loading.value = false }
}

function toggleExpand() {
  isExpandAll.value = !isExpandAll.value
  const t = tableRef.value; if (!t) return
  const toggle = (rows: any[]) => rows.forEach(r => { t.toggleRowExpansion(r, isExpandAll.value); if (r.children?.length) toggle(r.children) })
  toggle(menuTreeData.value)
}

// 表单弹窗
const dlg = reactive({ visible: false, title: '', isEdit: false, loading: false })
const formRef = ref<FormInstance>()
const editId = ref<string>()
const form = reactive({ parentId: null as string | null, menuName: '', menuPath: '', component: '', icon: '', menuType: 2, permission: '', sortOrder: 0, status: 1 })

const rules = computed<FormRules>(() => ({
  menuName: [{ required: true, message: '请输入菜单名称', trigger: 'blur' }],
  permission: form.menuType === 3 ? [{ required: true, message: '请输入权限标识', trigger: 'blur' }] : [],
  menuPath: form.menuType === 2 ? [{ required: true, message: '请输入路由路径', trigger: 'blur' }] : [],
}))

function resetForm() {
  Object.assign(form, { parentId: null, menuName: '', menuPath: '', component: '', icon: '', menuType: 2, permission: '', sortOrder: 0, status: 1 })
  editId.value = undefined
  // 清除校验状态，避免弹窗立即显示错误
  setTimeout(() => formRef.value?.clearValidate(), 0)
}

function openForm(parent: MenuItem | null, edit?: MenuItem) {
  resetForm()
  dlg.visible = true
  if (edit) {
    // 编辑模式
    dlg.title = '编辑菜单'
    dlg.isEdit = true
    editId.value = edit.id
    Object.assign(form, {
      menuName: edit.menuName, menuType: edit.menuType, menuPath: edit.path || '',
      component: edit.component || '', icon: edit.icon || '',
      permission: edit.permission || '', sortOrder: edit.sortOrder, status: edit.status,
    })
  } else {
    dlg.title = parent ? '新增子菜单' : '新增菜单'
    dlg.isEdit = false
    if (parent) form.parentId = parent.id || null
  }
}

async function submitForm() {
  const valid = await formRef.value?.validate().catch(() => false)
  if (!valid) return
  dlg.loading = true
  try {
    const payload: any = { ...form, systemId: currentSystemId.value }
    if (editId.value) {
      await request.put('/zgapi/v1/admin/menu', { ...payload, id: editId.value })
      ElMessage.success('编辑成功')
    } else {
      await request.post('/zgapi/v1/admin/menu', payload)
      ElMessage.success('新增成功')
    }
    dlg.visible = false
    fetchMenuTree()
  } catch { /* ignore */ } finally { dlg.loading = false }
}

function handleDelete(row: MenuItem) {
  ElMessageBox.confirm(`确认删除菜单"${row.menuName}"吗？`, '删除确认', { type: 'warning' }).then(async () => {
    try { await request.delete(`/zgapi/v1/admin/menu/${row.id}`); ElMessage.success('删除成功'); fetchMenuTree() } catch { /* ignore */ }
  }).catch(() => {})
}
</script>

<style scoped>
.page-wrapper { display:flex; flex-direction:column; gap:16px; }
.card-header-title { display:flex; align-items:center; gap:8px; font-weight:600; font-size:14px; color:var(--text-primary); }
.menu-toolbar { display:flex; align-items:center; gap:12px; flex-wrap:wrap; }
.toolbar-label { font-size:14px; font-weight:500; color:var(--text-secondary); }
.actions { display:flex; gap:8px; flex-wrap:wrap; justify-content:center; }

@media (max-width: 768px) {
  .page-wrapper { gap: 10px; }
  .page-toolbar { flex-direction: column; gap: 10px; }
  .page-toolbar .el-select { width: 100% !important; }
  .menu-toolbar { flex-direction: column; align-items: stretch; }
}
</style>
