<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { menuApi } from '@/api/system.js'

// ─── State ────────────────────────────────────────────────────────────────────

const treeData = ref([])
const loading = ref(false)
const dialogVisible = ref(false)
const dialogTitle = ref('新增菜单')
const submitLoading = ref(false)
const isEdit = ref(false)
const formRef = ref(null)

// ─── Form ─────────────────────────────────────────────────────────────────────

const form = reactive({
  id: null,
  parent_id: null,
  title: '',
  name: '',
  icon: '',
  path: '',
  component: '',
  type: 1,   // 1=目录 2=菜单 3=按钮
  sort: 0,
  visible: 1,
  status: 1,
  redirect: ''
})

const formRules = {
  title: [{ required: true, message: '请输入菜单名称', trigger: 'blur' }],
  path: [
    {
      validator: (rule, value, callback) => {
        if (form.type !== 3 && !value) {
          callback(new Error('请输入路由路径'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

const menuTypeOptions = [
  { label: '目录', value: 1 },
  { label: '菜单', value: 2 },
  { label: '按钮', value: 3 }
]

const commonIcons = [
  'House', 'User', 'Setting', 'DataLine', 'Grid', 'Money',
  'DocumentCopy', 'List', 'Calendar', 'Bell', 'Lock', 'Tools',
  'Odometer', 'ChatDotRound', 'Collection', 'Management'
]

// ─── Methods ──────────────────────────────────────────────────────────────────

async function fetchTree() {
  loading.value = true
  try {
    const res = await menuApi.getList({ per_page: 500 })
    const flat = res.data?.list || res.data?.data || []
    treeData.value = buildTree(flat)
  } catch {
    //
  } finally {
    loading.value = false
  }
}

function buildTree(nodes, parentId = null) {
  return nodes
    .filter(n => (n.parent_id ?? null) === parentId)
    .sort((a, b) => (a.sort ?? 0) - (b.sort ?? 0))
    .map(n => ({ ...n, children: buildTree(nodes, n.id) }))
}

function menuTypeTag(type) {
  const map = { 1: '', 2: 'success', 3: 'info' }
  return map[type] || ''
}

function menuTypeLabel(type) {
  const map = { 1: '目录', 2: '菜单', 3: '按钮' }
  return map[type] || '-'
}

function handleAdd(parentRow) {
  isEdit.value = false
  dialogTitle.value = parentRow ? `在「${parentRow.title}」下新增菜单` : '新增顶级菜单'
  Object.assign(form, {
    id: null,
    parent_id: parentRow?.id || null,
    title: '', name: '', icon: '', path: '',
    component: '', type: parentRow ? 2 : 1,
    sort: 0, visible: 1, status: 1, redirect: ''
  })
  dialogVisible.value = true
}

async function handleEdit(row) {
  isEdit.value = true
  dialogTitle.value = `编辑菜单 - ${row.title}`
  Object.assign(form, {
    id: row.id,
    parent_id: row.parent_id,
    title: row.title,
    name: row.name || '',
    icon: row.icon || '',
    path: row.path || '',
    component: row.component || '',
    type: row.type,
    sort: row.sort || 0,
    visible: row.visible,
    status: row.status,
    redirect: row.redirect || ''
  })
  dialogVisible.value = true
}

async function handleSubmit() {
  if (!formRef.value) return
  await formRef.value.validate(async (valid) => {
    if (!valid) return
    submitLoading.value = true
    try {
      if (isEdit.value) {
        await menuApi.update(form.id, form)
        ElMessage.success('菜单更新成功')
      } else {
        await menuApi.create(form)
        ElMessage.success('菜单创建成功')
      }
      dialogVisible.value = false
      fetchTree()
    } catch {
      //
    } finally {
      submitLoading.value = false
    }
  })
}

async function handleDelete(row) {
  await ElMessageBox.confirm(
    `确定删除菜单「${row.title}」吗？若有子菜单将一并删除。`,
    '删除确认',
    {
      confirmButtonText: '确定删除',
      cancelButtonText: '取消',
      type: 'warning',
      confirmButtonClass: 'el-button--danger'
    }
  )
  await menuApi.delete(row.id)
  ElMessage.success('删除成功')
  fetchTree()
}

onMounted(() => {
  fetchTree()
})
</script>

<template>
  <div class="p-6 space-y-4">
    <div class="bg-white rounded-2xl border border-gray-100 shadow-sm">
      <div class="flex items-center justify-between px-5 py-4 border-b border-gray-50">
        <div class="flex items-center gap-3">
          <el-button :icon="'Refresh'" @click="fetchTree">刷新</el-button>
        </div>
        <el-button type="primary" :icon="'Plus'" @click="handleAdd(null)">新增顶级菜单</el-button>
      </div>
      <div class="px-2">
        <el-table
          v-loading="loading"
          :data="treeData"
          row-key="id"
          :tree-props="{ children: 'children', hasChildren: 'has_children' }"
          default-expand-all
          style="width: 100%"
        >
          <el-table-column prop="title" label="菜单名称" min-width="180">
            <template #default="{ row }">
              <span style="display: flex; align-items: center; gap: 6px">
                <el-icon v-if="row.icon" size="14">
                  <component :is="row.icon" />
                </el-icon>
                {{ row.title }}
              </span>
            </template>
          </el-table-column>
          <el-table-column label="类型" width="80" align="center">
            <template #default="{ row }">
              <el-tag :type="menuTypeTag(row.type)" size="small">
                {{ menuTypeLabel(row.type) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="path" label="路由路径" min-width="180" show-overflow-tooltip />
          <el-table-column prop="component" label="组件路径" min-width="200" show-overflow-tooltip />
          <el-table-column prop="sort" label="排序" width="70" align="center" />
          <el-table-column label="显示" width="80" align="center">
            <template #default="{ row }">
              <el-tag :type="row.visible === 1 ? 'success' : 'info'" size="small">
                {{ row.visible === 1 ? '显示' : '隐藏' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="状态" width="80" align="center">
            <template #default="{ row }">
              <el-tag :type="row.status === 1 ? 'success' : 'danger'" size="small">
                {{ row.status === 1 ? '正常' : '停用' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200" fixed="right" align="center">
            <template #default="{ row }">
              <el-button
                v-if="row.type !== 3"
                size="small"
                type="success"
                text
                @click="handleAdd(row)"
              >
                新增子项
              </el-button>
              <el-button size="small" type="primary" text @click="handleEdit(row)">编辑</el-button>
              <el-button size="small" type="danger" text @click="handleDelete(row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <!-- Dialog -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="600px" destroy-on-close>
      <el-form ref="formRef" :model="form" :rules="formRules" label-width="100px">
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="菜单类型" prop="type">
              <el-radio-group v-model="form.type">
                <el-radio-button
                  v-for="opt in menuTypeOptions"
                  :key="opt.value"
                  :value="opt.value"
                >
                  {{ opt.label }}
                </el-radio-button>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="菜单名称" prop="title">
              <el-input v-model="form.title" placeholder="菜单显示名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="图标" prop="icon">
              <el-select v-model="form.icon" placeholder="选择图标" clearable style="width: 100%">
                <el-option
                  v-for="icon in commonIcons"
                  :key="icon"
                  :label="icon"
                  :value="icon"
                >
                  <span style="display: flex; align-items: center; gap: 8px">
                    <el-icon><component :is="icon" /></el-icon>
                    {{ icon }}
                  </span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col v-if="form.type !== 3" :span="12">
            <el-form-item label="路由路径" prop="path">
              <el-input v-model="form.path" placeholder="如: /system/users" />
            </el-form-item>
          </el-col>
          <el-col v-if="form.type === 2" :span="12">
            <el-form-item label="组件路径" prop="component">
              <el-input v-model="form.component" placeholder="如: system/users/index" />
            </el-form-item>
          </el-col>
          <el-col v-if="form.type === 1" :span="12">
            <el-form-item label="重定向" prop="redirect">
              <el-input v-model="form.redirect" placeholder="目录默认跳转路径（选填）" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="路由名称" prop="name">
              <el-input v-model="form.name" placeholder="唯一路由名（选填）" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="排序" prop="sort">
              <el-input-number v-model="form.sort" :min="0" :max="9999" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否显示" prop="visible">
              <el-radio-group v-model="form.visible">
                <el-radio :value="1">显示</el-radio>
                <el-radio :value="0">隐藏</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-radio-group v-model="form.status">
                <el-radio :value="1">正常</el-radio>
                <el-radio :value="0">停用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="submitLoading" @click="handleSubmit">
          {{ isEdit ? '保存修改' : '确认创建' }}
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>
