<template>
  <div class="menus-page">
    <a-card class="mb-4">
      <template #title>菜单管理</template>
      <template #extra>
        <a-button v-permission="'menu:create'" type="primary" @click="handleAdd">新增菜单</a-button>
      </template>
    </a-card>
    <a-table :columns="columns" :data-source="dataSource" :loading="loading" row-key="id" :pagination="false"
      :default-expand-all-rows="true">
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'icon'">
          <component v-if="record.icon && getIconComponent(record.icon)" :is="getIconComponent(record.icon)!" />
          <span v-else class="text-gray-400">-</span>
        </template>
        <template v-if="column.key === 'action'">
          <a-space>
            <a-button v-permission="'menu:update'" type="link" size="small" @click="handleEdit(record)">
              编辑
            </a-button>
            <a-button v-permission.hide="'menu:delete'" type="link" size="small" danger @click="handleDelete(record)">
              删除
            </a-button>
          </a-space>
        </template>
      </template>
    </a-table>

    <!-- 新增/编辑菜单弹窗 -->
    <a-modal v-model:open="modalVisible" :title="modalTitle" :confirm-loading="submitLoading" @ok="handleSubmit"
      @cancel="handleCancel" width="600px" :loading="detailLoading">
      <a-form ref="formRef" :model="form" :rules="rules" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }">
        <a-form-item label="菜单名称" name="name">
          <a-input v-model:value="form.name" placeholder="请输入菜单名称" :maxlength="50" />
        </a-form-item>
        <a-form-item label="路由路径" name="path">
          <a-input v-model:value="form.path" placeholder="请输入路由路径（如：/system/users）" :maxlength="200" />
        </a-form-item>
        <a-form-item label="图标" name="icon">
          <a-input v-model:value="form.icon" placeholder="请输入图标名称（Ant Design Icons）" :maxlength="50" />
        </a-form-item>
        <a-form-item label="组件路径" name="component">
          <a-input v-model:value="form.component" placeholder="请输入组件路径（如：system/users/Index）" :maxlength="200" />
        </a-form-item>
        <a-form-item label="权限编码" name="permission">
          <a-input v-model:value="form.permission" placeholder="请输入权限编码（如：menu:read，留空则所有用户可见）" :maxlength="100" />
        </a-form-item>
        <a-form-item label="父菜单" name="parentId">
          <a-tree-select v-model:value="form.parentId" :tree-data="menuTreeOptions" placeholder="请选择父菜单（不选则为顶级菜单）"
            :allow-clear="true" tree-default-expand-all />
        </a-form-item>
        <a-form-item label="排序" name="sort">
          <a-input-number v-model:value="form.sort" :min="0" :max="9999" placeholder="请输入排序值" style="width: 100%" />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, nextTick, computed, h } from 'vue'
import { message, Modal } from 'ant-design-vue'
import type { TableColumnsType, FormInstance } from 'ant-design-vue'
import * as Icons from '@ant-design/icons-vue'
import { menusApi, type Menu, type CreateMenuForm, type UpdateMenuForm } from '@/api/menus'
import { useSimpleListRequest } from '@/composables/useSimpleListRequest'
import { useAuthStore } from '@/stores/auth'

// 图标映射函数：将字符串名称转换为图标组件
const getIconComponent = (iconName: string | null | undefined) => {
  if (!iconName) return null

  // 从 @ant-design/icons-vue 中获取对应的图标组件
  const IconComponent = (Icons as any)[iconName]
  if (IconComponent) {
    return () => h(IconComponent)
  }
  return null
}

const authStore = useAuthStore()

const submitLoading = ref(false)
const detailLoading = ref(false)
const modalVisible = ref(false)
const modalTitle = ref('新增菜单')
const formRef = ref<FormInstance>()
const editingId = ref<number | null>(null)

// 使用简单列表请求组合函数（非分页列表）
const {
  loading,
  dataSource,
  refresh: refreshList,
} = useSimpleListRequest<Menu>({
  requestFn: menusApi.getList,
  errorMessage: '获取菜单列表失败',
})

const form = reactive<CreateMenuForm>({
  name: '',
  path: '',
  icon: '',
  component: '',
  parentId: undefined,
  permission: '',
  sort: 0,
})

const rules = {
  name: [
    { required: true, message: '请输入菜单名称', trigger: 'blur' },
    { max: 50, message: '菜单名称不能超过50个字符', trigger: 'blur' },
  ],
  path: [
    { max: 200, message: '路由路径不能超过200个字符', trigger: 'blur' },
  ],
  icon: [
    { max: 50, message: '图标名称不能超过50个字符', trigger: 'blur' },
  ],
  component: [
    { max: 200, message: '组件路径不能超过200个字符', trigger: 'blur' },
  ],
  permission: [
    { max: 100, message: '权限编码不能超过100个字符', trigger: 'blur' },
  ],
  sort: [
    { type: 'number', min: 0, max: 9999, message: '排序值必须在0-9999之间', trigger: 'blur' },
  ],
}

const columns: TableColumnsType = [
  { title: 'ID', dataIndex: 'id', key: 'id', width: 110 },
  { title: '菜单名称', dataIndex: 'name', key: 'name' },
  { title: '路径', dataIndex: 'path', key: 'path' },
  { title: '图标', dataIndex: 'icon', key: 'icon', width: 100, align: 'center' },
  { title: '排序', dataIndex: 'sort', key: 'sort', width: 80 },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    key: 'createTime',
    align: 'center',
    width: 120,
    customRender: ({ text }) =>
      text ? new Date(text).toISOString().replace('T', ' ').substring(0, 19) : ''
  },
  {
    title: '编辑时间',
    dataIndex: 'modifyTime',
    key: 'modifyTime',
    align: 'center',
    width: 120,
    customRender: ({ text }) =>
      text ? new Date(text).toISOString().replace('T', ' ').substring(0, 19) : ''
  },
  { title: '修改人', dataIndex: 'modifier', key: 'modifier', width: 100 },
  { title: '操作', key: 'action', width: 150 },
]

// 构建菜单树选项（用于父菜单选择）
const menuTreeOptions = computed(() => {
  const buildOptions = (menus: Menu[], excludeId?: number): any[] => {
    return menus
      .filter((menu) => menu.id !== excludeId)
      .map((menu) => ({
        title: menu.name,
        value: menu.id,
        key: menu.id,
        children: menu.children ? buildOptions(menu.children, excludeId) : undefined,
      }))
  }
  return buildOptions(dataSource.value, editingId.value || undefined)
})

// 新增菜单
const handleAdd = () => {
  // 权限检查
  if (!authStore.hasPermission('menu:create')) {
    message.error('您没有创建菜单的权限')
    return
  }

  modalTitle.value = '新增菜单'
  editingId.value = null
  modalVisible.value = true
  nextTick(() => {
    formRef.value?.resetFields()
    form.name = ''
    form.path = ''
    form.icon = ''
    form.component = ''
    form.parentId = undefined
    form.permission = ''
    form.sort = 0
  })
}

// 编辑菜单
const handleEdit = async (record: Menu) => {
  modalTitle.value = '编辑菜单'
  editingId.value = record.id
  modalVisible.value = true
  detailLoading.value = true

  try {
    const detail = await menusApi.getDetail(record.id)
    form.name = detail.name
    form.path = detail.path || ''
    form.icon = detail.icon || ''
    form.component = detail.component || ''
    form.parentId = detail.parentId || undefined
    form.permission = detail.permission || ''
    form.sort = detail.sort || 0
  } catch (error) {
    message.error('获取菜单详情失败')
    modalVisible.value = false
  } finally {
    detailLoading.value = false
  }
}

// 删除菜单
const handleDelete = (record: Menu) => {
  Modal.confirm({
    title: '确认删除',
    content: `确定要删除菜单 "${record.name}" 吗？删除后其子菜单也会被删除，且无法恢复。`,
    okText: '确定',
    okType: 'danger',
    cancelText: '取消',
    onOk: async () => {
      try {
        await menusApi.delete(record.id)
        message.success('删除成功')
        refreshList()
      } catch (error: any) {
        const errorMessage = error?.response?.data?.message || '删除失败'
        message.error(errorMessage)
      }
    },
  })
}

// 提交表单
const handleSubmit = async () => {
  try {
    await formRef.value?.validate()
    submitLoading.value = true

    if (editingId.value) {
      // 编辑
      const updateData: UpdateMenuForm = {
        name: form.name,
        path: form.path || undefined,
        icon: form.icon || undefined,
        component: form.component || undefined,
        parentId: form.parentId || undefined,
        permission: form.permission || undefined,
        sort: form.sort || 0,
      }
      await menusApi.update(editingId.value, updateData)
      message.success('编辑成功')
    } else {
      // 新增
      const createData: CreateMenuForm = {
        name: form.name,
        path: form.path || undefined,
        icon: form.icon || undefined,
        component: form.component || undefined,
        parentId: form.parentId || undefined,
        permission: form.permission || undefined,
        sort: form.sort || 0,
      }
      await menusApi.create(createData)
      message.success('新增成功')
    }

    modalVisible.value = false
    refreshList()
  } catch (error: any) {
    if (error?.errorFields) {
      // 表单验证错误
      return
    }
    const errorMessage =
      error?.response?.data?.message ||
      (editingId.value ? '编辑失败' : '新增失败')
    message.error(errorMessage)
  } finally {
    submitLoading.value = false
  }
}

// 取消表单
const handleCancel = () => {
  modalVisible.value = false
  formRef.value?.resetFields()
}
</script>
