<script setup lang="ts">
import type { VxeGridProps } from '#/adapter/vxe-table';
import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { Page } from '@vben/common-ui';
import {
  getRoleListApi,
  addRoleApi,
  editRoleApi,
  deleteRoleApi,
  getPermissionListApi,
  getRolePermissionsApi,
  setRolePermissionsApi,
} from '#/api/core/permission';
import type { PermissionApi } from '#/api/core/permission';
import {
  Button, Card, Space, Tag, Modal, message,
  Form, FormItem, Input, Textarea, Select, Spin, Tabs, TabPane, Transfer,
} from 'ant-design-vue';
import { ref, computed } from 'vue';

// ─── 弹窗状态 ─────────────────────────────────────────────
const modalOpen = ref(false);
const modalTitle = ref('新增权限组');
const modalLoading = ref(false);
const activeTab = ref('basic');

const editingId = ref<number | undefined>(undefined);
const formState = ref({ role_code: '', role_name: '', status: 1 as 0 | 1, remark: '' });

// 单点权限 Transfer
const allPermissions = ref<PermissionApi.Permission[]>([]);
const selectedPermissionIds = ref<string[]>([]);
const permissionTransferData = computed(() =>
  allPermissions.value.map((p) => ({
    key: String(p.id),
    title: `${p.permission_name}（${p.permission_code}）`,
    description: p.api_path ? `${p.http_method ?? ''} ${p.api_path}` : '',
    disabled: p.status !== 1,
  })),
);

async function openCreate() {
  editingId.value = undefined;
  formState.value = { role_code: '', role_name: '', status: 1, remark: '' };
  selectedPermissionIds.value = [];
  activeTab.value = 'basic';
  modalTitle.value = '新增权限组';
  modalLoading.value = true;
  modalOpen.value = true;
  try {
    const res = await getPermissionListApi({ page: 1, pageSize: 500 });
    allPermissions.value = res.items || [];
  } finally {
    modalLoading.value = false;
  }
}

async function openEdit(row: PermissionApi.Role) {
  editingId.value = row.id;
  formState.value = { role_code: row.role_code, role_name: row.role_name, status: row.status as 0 | 1, remark: row.remark || '' };
  selectedPermissionIds.value = [];
  activeTab.value = 'basic';
  modalTitle.value = '编辑权限组';
  modalLoading.value = true;
  modalOpen.value = true;
  try {
    const [permsRes, rolePerms] = await Promise.all([
      getPermissionListApi({ page: 1, pageSize: 500 }),
      getRolePermissionsApi(row.id!),
    ]);
    allPermissions.value = permsRes.items || [];
    selectedPermissionIds.value = (rolePerms || []).map((p) => String(p.id));
  } finally {
    modalLoading.value = false;
  }
}

async function handleConfirm() {
  if (!formState.value.role_code || !formState.value.role_name) {
    message.warning('请填写角色编码和名称');
    activeTab.value = 'basic';
    return;
  }
  modalLoading.value = true;
  try {
    const params: PermissionApi.Role = {
      id: editingId.value,
      role_code: formState.value.role_code,
      role_name: formState.value.role_name,
      status: formState.value.status,
      remark: formState.value.remark,
    };
    let roleId = editingId.value;
    if (editingId.value) {
      await editRoleApi(params);
      message.success('更新成功');
    } else {
      const res: any = await addRoleApi(params);
      roleId = res?.id ?? res;
      message.success('新增成功');
    }
    if (roleId) {
      await setRolePermissionsApi({ role_id: roleId, permission_ids: selectedPermissionIds.value.map(Number) });
    }
    modalOpen.value = false;
    GridApi.reload();
  } finally {
    modalLoading.value = false;
  }
}

// ─── 表格 ──────────────────────────────────────────────────
const gridOptions: VxeGridProps<PermissionApi.Role> = {
  columns: [
    { field: 'id', title: 'ID', width: 80 },
    { field: 'role_code', title: '角色编码', width: 160 },
    { field: 'role_name', title: '角色名称', minWidth: 150 },
    { field: 'is_system', title: '类型', width: 100, slots: { default: 'isSystemSlot' } },
    { field: 'status', title: '状态', width: 100, slots: { default: 'statusSlot' } },
    { field: 'remark', title: '备注', minWidth: 200 },
    { fixed: 'right', slots: { default: 'actionSlot' }, title: '操作', width: 160 },
  ],
  minHeight: 650,
  pagerConfig: {},
  proxyConfig: {
    response: { result: 'items', total: 'total' },
    ajax: {
      query: async ({ page }) =>
        getRoleListApi({ page: page.currentPage, pageSize: page.pageSize }),
    },
  },
  rowConfig: { isHover: true },
};

const [Grid, GridApi] = useVbenVxeGrid({ gridOptions });

function handleDelete(row: PermissionApi.Role) {
  Modal.confirm({
    title: '删除确认',
    content: `确认删除权限组「${row.role_name}」吗？系统内置角色无法删除。`,
    async onOk() {
      await deleteRoleApi(row.id!);
      message.success('删除成功');
      GridApi.reload();
    },
  });
}
</script>

<template>
  <Page auto-content-height>
    <!-- 新增/编辑弹窗 -->
    <Modal
      v-model:open="modalOpen"
      :confirm-loading="modalLoading"
      :title="modalTitle"
      width="760px"
      @ok="handleConfirm"
    >
      <Spin :spinning="modalLoading">
        <Tabs v-model:activeKey="activeTab">
          <TabPane key="basic" tab="基本信息">
            <Form layout="vertical" class="pt-3">
              <FormItem label="角色编码" required>
                <Input v-model:value="formState.role_code" placeholder="例如：R_ACTIVITY" />
              </FormItem>
              <FormItem label="角色名称" required>
                <Input v-model:value="formState.role_name" placeholder="例如：活动管理员" />
              </FormItem>
              <FormItem label="状态">
                <Select
                  v-model:value="formState.status"
                  :options="[{ label: '启用', value: 1 }, { label: '停用', value: 0 }]"
                  class="w-full"
                />
              </FormItem>
              <FormItem label="备注">
                <Textarea v-model:value="formState.remark" :rows="3" />
              </FormItem>
            </Form>
          </TabPane>

          <TabPane key="permissions" tab="单点权限配置">
            <p class="mb-3 text-gray-500 text-sm">为该权限组（角色）绑定单点权限：</p>
            <Transfer
              v-model:target-keys="selectedPermissionIds"
              :data-source="permissionTransferData"
              :render="(item: any) => item.title"
              :titles="['可选权限', '已选权限']"
              show-search
              :list-style="{ width: '100%', height: '320px' }"
            />
          </TabPane>
        </Tabs>
      </Spin>
    </Modal>

    <Card class="mb-4">
      <template #extra>
        <Button type="primary" @click="openCreate">新增权限组</Button>
      </template>
      <template #title>权限组（角色）管理</template>
    </Card>

    <Grid>
      <template #isSystemSlot="{ row }">
        <Tag :color="row.is_system === 1 ? 'blue' : 'default'">
          {{ row.is_system === 1 ? '系统内置' : '自定义' }}
        </Tag>
      </template>
      <template #statusSlot="{ row }">
        <Tag :color="row.status === 1 ? 'green' : 'red'">
          {{ row.status === 1 ? '启用' : '停用' }}
        </Tag>
      </template>
      <template #actionSlot="{ row }">
        <Space>
          <Button size="small" type="primary" @click="openEdit(row)">编辑</Button>
          <Button danger size="small" :disabled="row.is_system === 1" @click="handleDelete(row)">删除</Button>
        </Space>
      </template>
    </Grid>
  </Page>
</template>
