<template>
  <PageContainer title="平台角色管理">
    <QueryToolbar>
      <el-button v-if="canManage" type="primary" @click="openCreateDrawer">新增角色</el-button>
      <el-button v-if="canRead" @click="load">刷新</el-button>
    </QueryToolbar>
    <el-table :data="rows">
      <el-table-column prop="roleCode" label="角色编码" />
      <el-table-column prop="roleName" label="角色名称" />
      <el-table-column prop="status" label="状态" width="120" :formatter="statusFormatter" />
      <el-table-column label="操作" width="360">
        <template #default="{ row }">
          <el-button v-if="canManage" size="small" @click="handleRename(row)">改名</el-button>
          <el-button v-if="canManage && canReadPerms" size="small" @click="openBindPermissions(row)">绑权限</el-button>
          <el-button v-if="canManage" size="small" @click="openBindMenus(row)">绑菜单</el-button>
          <el-button v-if="canManage && row.status === 'ENABLED'" size="small" type="warning" @click="handleDisable(row.id)">
            停用
          </el-button>
          <el-button v-else-if="canManage" size="small" type="success" @click="handleEnable(row.id)">启用</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-drawer v-model="createVisible" title="新增平台角色" :size="DRAWER_SIZE.sm" destroy-on-close>
      <el-form ref="formRef" :model="form" label-position="left" :label-width="LABEL_WIDTH.md" :rules="formRules">
        <el-form-item label="角色编码" prop="roleCode">
          <el-input v-model="form.roleCode" />
        </el-form-item>
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="form.roleName" />
        </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="bindDialogVisible" title="平台角色权限绑定" :width="DIALOG_WIDTH.md">
      <div v-if="permissionGroups.length === 0">暂无可绑定权限</div>
      <div v-for="group in permissionGroups" :key="group.module" class="mb-md">
        <div class="text-title mb-xs">{{ group.module }}</div>
        <el-checkbox-group v-model="selectedPermissionIds">
          <el-checkbox v-for="perm in group.items" :key="perm.id" :label="perm.id" class="mr-lg">
            {{ perm.permissionName }}（{{ perm.permissionCode }}）
          </el-checkbox>
        </el-checkbox-group>
      </div>
      <template #footer>
        <el-button @click="bindDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitBindPermissions">保存</el-button>
      </template>
    </el-dialog>
    <el-dialog v-model="bindMenuVisible" title="平台角色菜单绑定" :width="DIALOG_WIDTH.md">
      <div v-if="menus.length === 0">暂无可绑定菜单</div>
      <el-checkbox-group v-model="selectedMenuIds">
        <el-checkbox v-for="menu in menus" :key="menu.id" :label="menu.id" class="mr-lg mb-xs">
          {{ menu.menuName }}（{{ menu.routePath }}）
        </el-checkbox>
      </el-checkbox-group>
      <template #footer>
        <el-button @click="bindMenuVisible = false">取消</el-button>
        <el-button type="primary" @click="submitBindMenus">保存</el-button>
      </template>
    </el-dialog>
  </PageContainer>
</template>

<script setup lang="ts">
import { computed, onMounted, ref } from "vue";
import PageContainer from "../../components/PageContainer.vue";
import QueryToolbar from "../../components/QueryToolbar.vue";
import { DRAWER_SIZE, DIALOG_WIDTH, LABEL_WIDTH } from "../../constants/ui";
import { ElMessage, ElMessageBox } from "element-plus";
import type { FormInstance, FormRules } from "element-plus";
import {
  bindPlatformRoleMenus,
  bindPlatformRolePermissions,
  createPlatformRole,
  disablePlatformRole,
  enablePlatformRole,
  fetchPlatformMenus,
  fetchPlatformRoleMenus,
  fetchPlatformPermissions,
  fetchPlatformRolePermissions,
  fetchPlatformRoles,
  updatePlatformRole,
} from "../../api/modules";
import { PERMS } from "../../constants/permissions";
import { useAuthStore } from "../../stores/auth";
import { toZhStatus } from "../../utils/status";

const authStore = useAuthStore();
const rows = ref<any[]>([]);
const permissions = ref<any[]>([]);
const menus = ref<any[]>([]);
const selectedRoleId = ref<number | null>(null);
const selectedPermissionIds = ref<number[]>([]);
const selectedMenuIds = ref<number[]>([]);
const createVisible = ref(false);
const bindDialogVisible = ref(false);
const bindMenuVisible = ref(false);
const canRead = computed(() => authStore.hasPermission(PERMS.platform.roleRead));
const canManage = computed(() => authStore.hasPermission(PERMS.platform.roleManage));
const canReadPerms = computed(() => authStore.hasPermission(PERMS.platform.permissionRead));
const form = ref({
  roleCode: "PLATFORM_CUSTOM_" + Date.now(),
  roleName: "平台自定义角色",
});

const formRef = ref<FormInstance>();

const formRules = ref<FormRules>({
  roleCode: [{ required: true, message: "请输入角色编码", trigger: "blur" }],
  roleName: [{ required: true, message: "请输入角色名称", trigger: "blur" }],
});

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

const openCreateDrawer = () => {
  form.value = {
    roleCode: "PLATFORM_CUSTOM_" + Date.now(),
    roleName: "平台自定义角色",
  };
  createVisible.value = true;
};

const permissionGroups = computed(() => {
  const grouped: Record<string, any[]> = {};
  permissions.value.forEach((p) => {
    const key = p.module || "other";
    if (!grouped[key]) grouped[key] = [];
    grouped[key].push(p);
  });
  return Object.keys(grouped).map((module) => ({ module, items: grouped[module] }));
});

const load = async () => {
  try {
    if (!canRead.value) {
      rows.value = [];
      return;
    }
    const resp = await fetchPlatformRoles();
    rows.value = resp?.data?.list || [];
  } catch (e: any) {
    rows.value = [];
    ElMessage.error(e?.response?.data?.message || "平台角色数据加载失败");
  }
};

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

  try {
    await createPlatformRole({
      roleCode: String(form.value.roleCode).trim(),
      roleName: String(form.value.roleName).trim(),
    });
    ElMessage.success("平台角色创建成功");
    createVisible.value = false;
    form.value.roleCode = "PLATFORM_CUSTOM_" + Date.now();
    form.value.roleName = "平台自定义角色";
    await load();
  } catch (e: any) {
    ElMessage.error(e?.response?.data?.message || "平台角色创建失败");
  }
};

const handleRename = async (row: any) => {
  const dialog = await ElMessageBox.prompt("请输入新的角色名称", "编辑平台角色", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    inputValue: row.roleName,
  }).catch(() => null);
  if (!dialog) return;
  try {
    await updatePlatformRole(row.id, { roleName: dialog.value });
    ElMessage.success("平台角色更新成功");
    await load();
  } catch (e: any) {
    ElMessage.error(e?.response?.data?.message || "平台角色更新失败");
  }
};

const handleEnable = async (id: number) => {
  try {
    await enablePlatformRole(id);
    ElMessage.success("平台角色已启用");
    await load();
  } catch (e: any) {
    ElMessage.error(e?.response?.data?.message || "平台角色启用失败");
  }
};

const handleDisable = async (id: number) => {
  try {
    await disablePlatformRole(id);
    ElMessage.success("平台角色已停用");
    await load();
  } catch (e: any) {
    ElMessage.error(e?.response?.data?.message || "平台角色停用失败");
  }
};

const openBindPermissions = async (row: any) => {
  selectedRoleId.value = row.id;
  const [permResp, rolePermResp] = await Promise.all([fetchPlatformPermissions(), fetchPlatformRolePermissions(row.id)]);
  permissions.value = permResp?.data?.list || [];
  selectedPermissionIds.value = rolePermResp?.data || [];
  bindDialogVisible.value = true;
};

const submitBindPermissions = async () => {
  if (!selectedRoleId.value) return;
  try {
    await bindPlatformRolePermissions(selectedRoleId.value, { permissionIds: selectedPermissionIds.value });
    ElMessage.success("平台角色权限绑定成功，请重新登录刷新权限");
    bindDialogVisible.value = false;
  } catch (e: any) {
    ElMessage.error(e?.response?.data?.message || "平台角色权限绑定失败");
  }
};

const openBindMenus = async (row: any) => {
  selectedRoleId.value = row.id;
  const [menuResp, roleMenuResp] = await Promise.all([fetchPlatformMenus(), fetchPlatformRoleMenus(row.id)]);
  menus.value = menuResp?.data?.list || [];
  selectedMenuIds.value = roleMenuResp?.data || [];
  bindMenuVisible.value = true;
};

const submitBindMenus = async () => {
  if (!selectedRoleId.value) return;
  try {
    await bindPlatformRoleMenus(selectedRoleId.value, { menuIds: selectedMenuIds.value });
    ElMessage.success("平台角色菜单绑定成功，请重新登录刷新菜单");
    bindMenuVisible.value = false;
  } catch (e: any) {
    ElMessage.error(e?.response?.data?.message || "平台角色菜单绑定失败");
  }
};

onMounted(load);
</script>
