<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 { defineEmits } from 'vue';

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

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { unAuthRoleUser, updateRoleUsers } from '#/api/system/role/role';

import { drawerColumns, querySchema } from './config-data';

const emit = defineEmits<{ reload: [] }>();

// 定义传过来的角色Id
let roleId: number;
const formOptions: VbenFormProps = {
  commonConfig: {
    labelWidth: 80,
    componentProps: {
      allowClear: true,
    },
  },
  schema: querySchema(),
  wrapperClass: 'grid-cols-3',
};
const gridOptions: VxeGridProps = {
  checkboxConfig: {
    // 高亮
    highlight: true,
    // 翻页时保留选中状态
    reserve: true,
  },
  columns: drawerColumns,
  size: 'medium',
  height: 'auto',
  proxyConfig: {
    ajax: {
      query: async (_, formValues = {}) => {
        const resp = await unAuthRoleUser({
          ...formValues,
          roleId,
          pageNum: 1,
          pageSize: 10,
        });
        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,
});
const [Drawer, drawerApi] = useVbenDrawer({
  onOpenChange(isOpen: boolean) {
    if (!isOpen) {
      return;
    }
    const { queryRoleId } = drawerApi.getData();
    roleId = queryRoleId;
  },
  async onConfirm() {
    try {
      this.confirmLoading = true;
      const userIds = basicTableApi.grid
        .getCheckboxRecords()
        .map((item: User) => item.userId);
      if (userIds.length <= 0) {
        return;
      }
      // 调用更新用户角色
      await updateRoleUsers(roleId, userIds);
      emit('reload');
      // 关闭侧拉
      drawerApi.close();
      // 重置弹窗
      await basicTableApi.formApi.resetForm();
    } catch (error) {
      console.error(error);
    } finally {
      this.confirmLoading = false;
    }
  },
});
</script>
<template>
  <Drawer class="w-[800px]" title="选择用户">
    <BasicTable />
  </Drawer>
</template>
