<template>
  <PageContainer title="平台菜单与权限">
    <el-tabs v-model="activeTab" @tab-change="onTabChange">
      <el-tab-pane label="菜单管理" name="menus">
        <el-space wrap>
          <el-button v-if="canManage" type="primary" @click="openCreateDrawer">新增菜单</el-button>
          <el-button v-if="canManage" :disabled="rows.length === 0" @click="handleSaveOrder">保存排序</el-button>
          <el-button @click="loadMenus">刷新</el-button>
        </el-space>

        <el-table :data="rows">
          <el-table-column prop="menuCode" label="菜单编码" width="180" />
          <el-table-column prop="menuName" label="菜单名称" width="180" />
          <el-table-column prop="routePath" label="路由地址" min-width="240" />
          <el-table-column prop="permissionCode" label="权限码" min-width="220" />
          <el-table-column label="排序" width="120">
            <template #default="{ row }">
              <el-input-number v-if="canManage" v-model="row.sortNo" :min="1" />
              <span v-else>{{ row.sortNo }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="status" label="状态" width="100" :formatter="statusFormatter" />
          <el-table-column label="操作" width="260">
            <template #default="{ row }">
              <el-button v-if="canManage" size="small" @click="openEdit(row)">编辑</el-button>
              <el-button v-if="canManage" size="small" @click="openBindRoles(row)">绑角色</el-button>
              <el-button
                v-if="canManage"
                size="small"
                :type="row.status === 'ENABLED' ? 'warning' : 'success'"
                @click="toggleStatus(row)"
              >
                {{ row.status === "ENABLED" ? "停用" : "启用" }}
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
      <el-tab-pane label="权限管理" name="permissions">
        <el-button type="primary" @click="loadPermissions">刷新</el-button>
        <el-table :data="permissions" class="mt-md">
          <el-table-column prop="permissionCode" label="权限码" min-width="260" />
          <el-table-column prop="permissionName" label="权限名称" min-width="220" />
          <el-table-column prop="module" label="模块" width="160" />
        </el-table>
      </el-tab-pane>
    </el-tabs>

    <el-drawer v-model="createVisible" title="新增平台菜单" :size="DRAWER_SIZE.md" destroy-on-close>
      <el-form ref="formRef" :model="form" label-position="left" :label-width="LABEL_WIDTH.md" :rules="formRules">
        <el-form-item label="菜单编码" prop="menuCode">
          <el-input v-model="form.menuCode" />
        </el-form-item>
        <el-form-item label="菜单名称" prop="menuName">
          <el-input v-model="form.menuName" />
        </el-form-item>
        <el-form-item label="路由" prop="routePath">
          <el-input v-model="form.routePath" placeholder="/platform/xxx" />
        </el-form-item>
        <el-form-item label="权限码" prop="permissionCode">
          <el-input v-model="form.permissionCode" placeholder="如 platform.menu.manage" />
        </el-form-item>
        <el-form-item label="排序">
          <el-input-number v-model="form.sortNo" :min="1" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="createVisible = false">取消</el-button>
        <el-button v-if="canManage" type="primary" @click="handleCreate">创建</el-button>
      </template>
    </el-drawer>

    <el-dialog v-model="editVisible" title="编辑平台菜单" :width="DIALOG_WIDTH.md">
      <el-form ref="editFormRef" :model="editForm" label-position="left" :label-width="LABEL_WIDTH.md" :rules="formRules">
        <el-form-item label="菜单名称" prop="menuName">
          <el-input v-model="editForm.menuName" />
        </el-form-item>
        <el-form-item label="路由地址" prop="routePath">
          <el-input v-model="editForm.routePath" />
        </el-form-item>
        <el-form-item label="权限码" prop="permissionCode">
          <el-input v-model="editForm.permissionCode" />
        </el-form-item>
        <el-form-item label="排序">
          <el-input-number v-model="editForm.sortNo" :min="1" />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="editForm.status">
            <el-option label="启用" value="ENABLED" />
            <el-option label="停用" value="DISABLED" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="editVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSave">保存</el-button>
      </template>
    </el-dialog>

    <el-dialog v-model="bindVisible" title="菜单绑定角色" :width="DIALOG_WIDTH.md">
      <el-checkbox-group v-model="selectedRoleIds">
        <el-checkbox v-for="role in roles" :key="role.id" :label="role.id" class="mr-lg mb-sm">
          {{ role.roleName }}（{{ role.roleCode }}）
        </el-checkbox>
      </el-checkbox-group>
      <template #footer>
        <el-button @click="bindVisible = false">取消</el-button>
        <el-button type="primary" @click="submitBindRoles">保存</el-button>
      </template>
    </el-dialog>
  </PageContainer>
</template>

<script setup lang="ts">
import { computed, onMounted, ref } from "vue";
import PageContainer from "../../components/PageContainer.vue";
import { DRAWER_SIZE, DIALOG_WIDTH, LABEL_WIDTH } from "../../constants/ui";
import { ElMessage } from "element-plus";
import type { FormInstance, FormRules } from "element-plus";
import { useRoute, useRouter } from "vue-router";
import {
  bindPlatformMenuRoles,
  createPlatformMenu,
  fetchPlatformMenuRoles,
  fetchPlatformMenus,
  fetchPlatformPermissions,
  fetchPlatformRoles,
  reorderPlatformMenus,
  updatePlatformMenu,
} from "../../api/modules";
import { PERMS } from "../../constants/permissions";
import { useAuthStore } from "../../stores/auth";
import { toZhStatus } from "../../utils/status";

const authStore = useAuthStore();
const canManage = computed(() => authStore.hasPermission(PERMS.platform.menuManage));
const route = useRoute();
const router = useRouter();
const activeTab = ref(String(route.query.tab || "menus") === "permissions" ? "permissions" : "menus");
const rows = ref<any[]>([]);
const permissions = ref<any[]>([]);
const roles = ref<any[]>([]);
const selectedMenuId = ref<number | null>(null);
const selectedRoleIds = ref<number[]>([]);
const bindVisible = ref(false);
const createVisible = ref(false);
const editVisible = ref(false);
const editId = ref<number | null>(null);
const editForm = ref<any>({});
const form = ref({
  menuCode: "",
  menuName: "",
  routePath: "",
  permissionCode: "",
  sortNo: 100,
});

const formRef = ref<FormInstance>();
const editFormRef = ref<FormInstance>();
const formRules = ref<FormRules>({
  menuCode: [{ required: true, message: "请输入菜单编码", trigger: "blur" }],
  menuName: [{ required: true, message: "请输入菜单名称", trigger: "blur" }],
});

const statusFormatter = (_row: any, _column: any, value: unknown) => toZhStatus(value);

const openCreateDrawer = () => {
  form.value = {
    menuCode: "",
    menuName: "",
    routePath: "",
    permissionCode: "",
    sortNo: 100,
  };
  createVisible.value = true;
};

const loadMenus = async () => {
  const resp = await fetchPlatformMenus();
  rows.value = resp?.data?.list || [];
};

const loadPermissions = async () => {
  const resp = await fetchPlatformPermissions();
  permissions.value = resp?.data?.list || [];
};

const onTabChange = async (name: string | number) => {
  const tab = String(name);
  await router.replace({ path: "/platform/menus", query: tab === "permissions" ? { tab: "permissions" } : {} });
  if (tab === "permissions") {
    await loadPermissions();
  } else {
    await loadMenus();
  }
};

const handleCreate = async () => {
  if (!formRef.value) return;
  const valid = await formRef.value.validate().catch(() => false);
  if (!valid) return;

  await createPlatformMenu({
    menuCode: form.value.menuCode.trim(),
    menuName: form.value.menuName.trim(),
    routePath: form.value.routePath.trim(),
    permissionCode: form.value.permissionCode.trim(),
    sortNo: form.value.sortNo,
  });
  ElMessage.success("平台菜单创建成功");
  createVisible.value = false;
  await loadMenus();
};

const openEdit = (row: any) => {
  editId.value = row.id;
  editForm.value = { ...row };
  editVisible.value = true;
};

const handleSave = async () => {
  if (!editId.value) return;

  if (!editFormRef.value) return;
  const valid = await editFormRef.value.validate().catch(() => false);
  if (!valid) return;

  await updatePlatformMenu(editId.value, {
    menuName: String(editForm.value.menuName || "").trim(),
    routePath: String(editForm.value.routePath || "").trim(),
    permissionCode: String(editForm.value.permissionCode || "").trim(),
    sortNo: Number(editForm.value.sortNo || 100),
    status: String(editForm.value.status || "ENABLED") as "ENABLED" | "DISABLED",
  });
  ElMessage.success("平台菜单更新成功");
  editVisible.value = false;
  await loadMenus();
};

const handleSaveOrder = async () => {
  await reorderPlatformMenus({
    menus: rows.value.map((x) => ({ id: Number(x.id), sortNo: Number(x.sortNo) })),
  });
  ElMessage.success("平台菜单排序已保存");
  await loadMenus();
};

const toggleStatus = async (row: any) => {
  const nextStatus = row.status === "ENABLED" ? "DISABLED" : "ENABLED";
  await updatePlatformMenu(row.id, {
    menuName: row.menuName,
    routePath: row.routePath,
    permissionCode: row.permissionCode,
    sortNo: row.sortNo,
    status: nextStatus,
  });
  ElMessage.success(nextStatus === "ENABLED" ? "菜单已启用" : "菜单已停用");
  await loadMenus();
};

const openBindRoles = async (row: any) => {
  selectedMenuId.value = row.id;
  const [roleResp, menuRoleResp] = await Promise.all([fetchPlatformRoles(), fetchPlatformMenuRoles(row.id)]);
  roles.value = roleResp?.data?.list || [];
  selectedRoleIds.value = menuRoleResp?.data || [];
  bindVisible.value = true;
};

const submitBindRoles = async () => {
  if (!selectedMenuId.value) return;
  await bindPlatformMenuRoles(selectedMenuId.value, { roleIds: selectedRoleIds.value });
  ElMessage.success("平台菜单角色绑定成功");
  bindVisible.value = false;
};

onMounted(async () => {
  if (activeTab.value === "permissions") {
    await loadPermissions();
  } else {
    await loadMenus();
  }
});
</script>
