<template>
  <div class="page-container">
    <ProTable
      ref="tableRef"
      :columns="columns"
      :request="fetchTableData"
      :toolbar="toolbarConfig"
      :search="false"
      row-key="id"
      :default-expand-all-rows="true"
    >
      <template #toolbar-actions>
        <a-button type="primary" @click="handleCreate(null)">
          <PlusOutlined /> 新增菜单
        </a-button>
      </template>

      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'menu_type'">
          <a-tag :color="record.menu_type === 'M' ? 'blue' : record.menu_type === 'C' ? 'green' : 'orange'">
            {{ record.menu_type === 'M' ? '目录' : record.menu_type === 'C' ? '菜单' : '按钮' }}
          </a-tag>
        </template>
        <template v-else-if="column.key === 'status'">
          <a-tag :color="record.status === '0' ? 'green' : 'default'">
            {{ record.status === '0' ? '正常' : '停用' }}
          </a-tag>
        </template>
        <template v-else-if="column.key === 'action'">
          <a-space :size="4">
            <a-button type="link" size="small" @click="handleCreate(record)">新增</a-button>
            <a-button type="link" size="small" @click="handleEdit(record)">编辑</a-button>
            <a-popconfirm title="确认删除该菜单？" @confirm="handleDelete(record)">
              <a-button type="link" danger size="small">删除</a-button>
            </a-popconfirm>
          </a-space>
        </template>
      </template>
    </ProTable>

    <a-modal
      v-model:open="modalVisible"
      :title="editingId ? '编辑菜单' : '新增菜单'"
      :confirm-loading="submitting"
      width="640px"
      @ok="handleSubmit"
      @cancel="handleCancel"
    >
      <ProForm
        ref="formRef"
        :form-items="formItems"
        :initial-values="formData"
        :grid="{ cols: 1, gutter: 16 }"
        :layout="{ layout: 'vertical' }"
      />
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import type { ProFormItem, ProTableColumn, ProTableToolbar } from "@/types/pro";

import { PlusOutlined } from "@antdv-next/icons";
import { message } from "antdv-next";
import { computed, onMounted, ref } from "vue";

import { getMenuTree, saveMenu, deleteMenu } from "@/api/menu";
import ProForm from "@/components/Pro/ProForm/index.vue";
import ProTable from "@/components/Pro/ProTable/index.vue";

const tableRef = ref<{ refresh: () => void } | null>(null);
const formRef = ref<{ validate: () => Promise<boolean>; getFieldsValue: () => Record<string, unknown> } | null>(null);

const modalVisible = ref(false);
const submitting = ref(false);
const editingId = ref<string | null>(null);
const parentId = ref<string | null>(null);
const parentPerms = ref<string | null>(null);

const actionLabelMap: Record<string, string> = {
  list: "查看", add: "新增", edit: "编辑", delete: "删除",
  export: "导出", import: "导入", assign: "分配", audit: "审核",
  upload: "上传", download: "下载",
};

function getPermsPrefix(): string {
  if (parentPerms.value) {
    return parentPerms.value.replace(/:list$|:view$|:manage$/, "");
  }
  return "";
}

function getActionOptions(values: Record<string, unknown>) {
  const prefix = getPermsPrefix();
  if (!prefix) return [];
  const current = values.perms as string;
  const options = Object.entries(actionLabelMap).map(([key, label]) => ({
    label: `${label}  (${prefix}:${key})`,
    value: `${prefix}:${key}`,
  }));
  if (current && !options.find((o) => o.value === current)) {
    options.unshift({ label: current, value: current });
  }
  return options;
}

const toolbarConfig = computed<ProTableToolbar>(() => ({
  title: "菜单管理",
  subTitle: "",
  actions: ["refresh", "density", "columnSetting"],
}));

const formData = ref<Record<string, unknown>>({});
const menuSelectTree = ref<any[]>([]);

function transformToSelectTree(items: any[]): any[] {
  return items.map((item) => ({
    id: item.id,
    menu_name: item.menu_name,
    children: item.children ? transformToSelectTree(item.children) : undefined,
  }));
}

onMounted(async () => {
  const res: any = await getMenuTree();
  if (res.code === 1) {
    menuSelectTree.value = transformToSelectTree(res.data || []);
  }
});

const columns: ProTableColumn[] = [
  { title: "菜单名称", dataIndex: "menu_name", key: "menu_name", width: 200 },
  { title: "图标", dataIndex: "icon", key: "icon", width: 80 },
  { title: "排序", dataIndex: "order_num", key: "order_num", width: 80 },
  { title: "权限标识", dataIndex: "perms", key: "perms", width: 180, ellipsis: true },
  { title: "组件路径", dataIndex: "component", key: "component", width: 150, ellipsis: true },
  { title: "类型", dataIndex: "menu_type", key: "menu_type", width: 80 },
  { title: "状态", dataIndex: "status", key: "status", width: 80 },
  { title: "操作", dataIndex: "action", key: "action", width: 160, fixed: "right" },
];

const formItems = computed<ProFormItem[]>(() => [
  { label: "上级菜单", name: "parent_id", type: "treeSelect",
    options: menuSelectTree.value,
    props: { fieldNames: { label: 'menu_name', value: 'id', children: 'children' }, treeDefaultExpandAll: true, allowClear: true, placeholder: "无（顶级菜单）" } },
  { label: "菜单名称", name: "menu_name", type: "input", rules: [{ required: true, message: "请输入菜单名称" }] },
  { label: "菜单类型", name: "menu_type", type: "select", initialValue: "M", rules: [{ required: true }],
    fieldProps: { options: [{ label: "目录", value: "M" }, { label: "菜单", value: "C" }, { label: "按钮", value: "F" }] } },
  { label: "路由地址", name: "path", type: "input" },
  { label: "组件路径", name: "component", type: "input" },
  { label: "权限标识", name: "perms", type: "input",
    hidden: (values: Record<string, unknown>) => values.menu_type !== 'C',
    placeholder: "例如: system:user:list",
    tooltip: "菜单权限标识，格式: 模块:页面:list" },
  { label: "权限标识", name: "perms", type: "select",
    hidden: (values: Record<string, unknown>) => values.menu_type !== 'F',
    placeholder: "请选择操作类型",
    options: getActionOptions,
    props: { allowClear: true, showSearch: true } },
  { label: "图标", name: "icon", type: "input" },
  { label: "排序", name: "order_num", type: "number", initialValue: 0 },
  { label: "状态", name: "status", type: "select", initialValue: "0",
    fieldProps: { options: [{ label: "正常", value: "0" }, { label: "停用", value: "1" }] } },
]);

async function fetchTableData() {
  const res: any = await getMenuTree();
  if (res.code === 1) {
    return { data: res.data || [], total: (res.data || []).length, success: true };
  }
  return { data: [], total: 0, success: false };
}

function handleCreate(parent: any) {
  editingId.value = null;
  parentId.value = parent?.id || null;
  parentPerms.value = parent?.perms || null;
  formData.value = { parent_id: parent?.id || undefined, menu_type: parent ? "C" : "M", status: "0", order_num: 0 };
  modalVisible.value = true;
}

function handleEdit(record: any) {
  editingId.value = record.id;
  parentId.value = record.parent_id || null;
  parentPerms.value = null; // for editing, we don't auto-generate — keep existing perms
  formData.value = { ...record };
  modalVisible.value = true;
}

async function handleSubmit() {
  const valid = await formRef.value?.validate();
  if (!valid) return;
  submitting.value = true;
  try {
    const values = formRef.value?.getFieldsValue() || {};
    // Auto-generate perms for C-type menus from path
    if (values.menu_type === 'C' && !values.perms && values.path) {
      values.perms = (values.path as string).replace(/^\//, '').replace(/\//g, ':') + ':list';
    }
    await saveMenu({ ...values, id: editingId.value || undefined });
    message.success(editingId.value ? "更新成功" : "新增成功");
    modalVisible.value = false;
    tableRef.value?.refresh();
  } catch {
    message.error("操作失败");
  } finally {
    submitting.value = false;
  }
}

function handleCancel() {
  modalVisible.value = false;
}

async function handleDelete(record: any) {
  try {
    await deleteMenu(record.id);
    message.success("删除成功");
    tableRef.value?.refresh();
  } catch {
    message.error("删除失败");
  }
}
</script>
