<script setup lang="ts">
import type { VxeGridProps } from '#/adapter/vxe-table';
import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { Page } from '@vben/common-ui';
import {
  getUserGroupListApi,
  addUserGroupApi,
  editUserGroupApi,
  deleteUserGroupApi,
  getRoleListApi,
  getGroupRolesApi,
  setGroupRolesApi,
  getPermissionListApi,
} 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({ group_code: '', group_name: '', status: 1 as 0 | 1, remark: '' });

// 权限组（角色）Transfer
const allRoles = ref<PermissionApi.Role[]>([]);
const selectedRoleIds = ref<string[]>([]);
const roleTransferData = computed(() =>
  allRoles.value.map((r) => ({
    key: String(r.id),
    title: `${r.role_name}（${r.role_code}）`,
    disabled: r.status !== 1,
  })),
);

// 单点权限 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 = { group_code: '', group_name: '', status: 1, remark: '' };
  selectedRoleIds.value = [];
  selectedPermissionIds.value = [];
  activeTab.value = 'basic';
  modalTitle.value = '新增用户组';
  modalLoading.value = true;
  modalOpen.value = true;
  try {
    const [rolesRes, permsRes] = await Promise.all([
      getRoleListApi({ page: 1, pageSize: 500 }),
      getPermissionListApi({ page: 1, pageSize: 500 }),
    ]);
    allRoles.value = rolesRes.items || [];
    allPermissions.value = permsRes.items || [];
  } finally {
    modalLoading.value = false;
  }
}

async function openEdit(row: PermissionApi.UserGroup) {
  editingId.value = row.id;
  formState.value = { group_code: row.group_code, group_name: row.group_name, status: row.status as 0 | 1, remark: row.remark || '' };
  selectedRoleIds.value = [];
  selectedPermissionIds.value = [];
  activeTab.value = 'basic';
  modalTitle.value = '编辑用户组';
  modalLoading.value = true;
  modalOpen.value = true;
  try {
    const [rolesRes, permsRes, groupRoles] = await Promise.all([
      getRoleListApi({ page: 1, pageSize: 500 }),
      getPermissionListApi({ page: 1, pageSize: 500 }),
      getGroupRolesApi(row.id!),
    ]);
    allRoles.value = rolesRes.items || [];
    allPermissions.value = permsRes.items || [];
    selectedRoleIds.value = (groupRoles || []).map((r) => String(r.id));
  } finally {
    modalLoading.value = false;
  }
}

async function handleConfirm() {
  if (!formState.value.group_code || !formState.value.group_name) {
    message.warning('请填写用户组编码和名称');
    activeTab.value = 'basic';
    return;
  }
  modalLoading.value = true;
  try {
    const params: PermissionApi.UserGroup = {
      id: editingId.value,
      group_code: formState.value.group_code,
      group_name: formState.value.group_name,
      status: formState.value.status,
      remark: formState.value.remark,
    };
    let groupId = editingId.value;
    if (editingId.value) {
      await editUserGroupApi(params);
      message.success('更新成功');
    } else {
      const res: any = await addUserGroupApi(params);
      groupId = res?.id ?? res;
      message.success('新增成功');
    }
    if (groupId) {
      await setGroupRolesApi({ group_id: groupId, role_ids: selectedRoleIds.value.map(Number) });
    }
    modalOpen.value = false;
    GridApi.reload();
  } finally {
    modalLoading.value = false;
  }
}

// ─── 表格 ──────────────────────────────────────────────────
const gridOptions: VxeGridProps<PermissionApi.UserGroup> = {
  columns: [
    { field: 'id', title: 'ID', width: 80 },
    { field: 'group_code', title: '用户组编码', width: 150 },
    { field: 'group_name', title: '用户组名称', minWidth: 150 },
    { 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 }) =>
        getUserGroupListApi({ page: page.currentPage, pageSize: page.pageSize }),
    },
  },
  rowConfig: { isHover: true },
};

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

function handleDelete(row: PermissionApi.UserGroup) {
  Modal.confirm({
    title: '删除确认',
    content: `确认删除用户组「${row.group_name}」吗？`,
    async onOk() {
      await deleteUserGroupApi(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.group_code" placeholder="例如：G_OP" />
              </FormItem>
              <FormItem label="用户组名称" required>
                <Input v-model:value="formState.group_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="roles" tab="权限组配置">
            <p class="mb-3 text-gray-500 text-sm">将权限组（角色）绑定到该用户组：</p>
            <Transfer
              v-model:target-keys="selectedRoleIds"
              :data-source="roleTransferData"
              :render="(item: any) => item.title"
              :titles="['可选权限组', '已选权限组']"
              show-search
              :list-style="{ width: '100%', height: '280px' }"
            />
          </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: '280px' }"
            />
          </TabPane>
        </Tabs>
      </Spin>
    </Modal>

    <Card class="mb-4">
      <template #extra>
        <Button type="primary" @click="openCreate">新增用户组</Button>
      </template>
      <template #title>用户组管理</template>
    </Card>

    <Grid>
      <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" @click="handleDelete(row)">删除</Button>
        </Space>
      </template>
    </Grid>
  </Page>
</template>
