<script setup lang="ts">
import type { VbenFormProps } from '@vben/common-ui';

import type { VxeGridProps } from '#/adapter/vxe-table';
import type { User } from '#/api/system/user/model';

import { useRoute } from 'vue-router';

import { Page, useVbenDrawer } from '@vben/common-ui';

import { ElMessageBox } from 'element-plus';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import {
  authRoleUser,
  unAllRoleUsers,
  unRoleUsers,
} from '#/api/system/role/role';

import { columns, querySchema } from './config-data';
import RoleAssignDrawer from './role-assign-drawer.vue';

const route = useRoute();
const roleId = route.params.roleId as string;

const [AuthDrawer, authDrawerApi] = useVbenDrawer({
  connectedComponent: RoleAssignDrawer,
});
const formOptions: VbenFormProps = {
  commonConfig: {
    labelWidth: 80,
    componentProps: {
      allowClear: true,
    },
  },
  schema: querySchema(),
  wrapperClass: 'grid-cols-4',
};
const gridOptions: VxeGridProps = {
  checkboxConfig: {
    // 高亮
    highlight: true,
    // 翻页时保留选中状态
    reserve: true,
  },
  columns,
  size: 'medium',
  height: 'auto',
  proxyConfig: {
    ajax: {
      query: async ({ page }, formValues = {}) => {
        const resp = await authRoleUser({
          ...formValues,
          roleId,
          pageNum: page.currentPage,
          pageSize: page.pageSize,
        });
        return { items: resp.rows, total: resp.total };
      },
    },
  },
  rowConfig: {
    keyField: 'userId',
  },
  toolbarConfig: {
    custom: true,
    refresh: true,
    zoom: true,
  },
  id: 'system-role-auth-index',
};
const [BasicTable, basicTableApi] = useVbenVxeGrid({
  formOptions,
  gridOptions,
});
function handelAdd() {
  authDrawerApi.setData({ queryRoleId: roleId }).open();
}
// 批量取消授权
async function unAuthHandle() {
  const checkRecords = basicTableApi.grid.getCheckboxRecords();
  const userIds = checkRecords.map((item: User) => item.userId);
  if (userIds.length <= 0) {
    return;
  }
  ElMessageBox.confirm(`确认删除选中的${userIds.length}条数据吗?`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    await unAllRoleUsers(roleId, userIds);
    await basicTableApi.reload();
  });
}
// 单个取消授权
async function confirmEvent(row: User) {
  await unRoleUsers(roleId, row.userId);
  await basicTableApi.reload();
}
</script>
<template>
  <Page :auto-content-height="true">
    <BasicTable table-title="已分配用户列表">
      <template #toolbar-tools>
        <ElSpace>
          <ElButton
            type="danger"
            :disabled="
              !(basicTableApi?.grid?.getCheckboxRecords?.()?.length > 0)
            "
            @click="unAuthHandle"
          >
            取消授权
          </ElButton>
          <ElButton type="primary" @click="handelAdd"> 新增 </ElButton>
        </ElSpace>
      </template>
      <template #action="{ row }">
        <ElPopconfirm title="确认取消授权" @confirm="confirmEvent(row)">
          <template #reference>
            <ElButton size="small" type="danger" plain> 取消授权 </ElButton>
          </template>
        </ElPopconfirm>
      </template>
    </BasicTable>
    <AuthDrawer @reload="basicTableApi.reload()" />
  </Page>
</template>
