<script lang="ts" setup>
import type {
  OnActionClickParams,
  VxeTableGridOptions,
} from '#/adapter/vxe-table';
import type { SystemDeptApi } from '#/api/system/dept';
import type { SystemUserApi } from '#/api/system/user';

import { ref } from 'vue';

import { Page, useVbenModal } from '@vben/common-ui';
import { Download, Plus, Upload } from '@vben/icons';

import { Button, message, Modal } from 'ant-design-vue';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import {
  deleteUser,
  exportUser,
  getUserPage,
  updateUserStatus,
} from '#/api/system/user';
import { DocAlert } from '#/components/doc-alert';
import { $t } from '#/locales';
import { DICT_TYPE, getDictLabel } from '#/utils/dict';
import { downloadByData } from '#/utils/download';

import { useGridColumns, useGridFormSchema } from './data';
import AssignRoleForm from './modules/assign-role-form.vue';
import DeptTree from './modules/dept-tree.vue';
import Form from './modules/form.vue';
import ImportForm from './modules/import-form.vue';
import ResetPasswordForm from './modules/reset-password-form.vue';

const [FormModal, formModalApi] = useVbenModal({
  connectedComponent: Form,
  destroyOnClose: true,
});

const [ResetPasswordModal, resetPasswordModalApi] = useVbenModal({
  connectedComponent: ResetPasswordForm,
  destroyOnClose: true,
});

const [AssignRoleModal, assignRoleModalApi] = useVbenModal({
  connectedComponent: AssignRoleForm,
  destroyOnClose: true,
});

const [ImportModal, importModalApi] = useVbenModal({
  connectedComponent: ImportForm,
  destroyOnClose: true,
});

/** 刷新表格 */
function onRefresh() {
  gridApi.query();
}

/** 导出表格 */
async function onExport() {
  const data = await exportUser(await gridApi.formApi.getValues());
  downloadByData(data, '用户.xls');
}

/** 选择部门 */
const searchDeptId = ref<number | undefined>(undefined);
async function onDeptSelect(dept: SystemDeptApi.Dept) {
  searchDeptId.value = dept.id;
  onRefresh();
}

/** 创建用户 */
function onCreate() {
  formModalApi.setData(null).open();
}

/** 导入用户 */
function onImport() {
  importModalApi.open();
}

/** 编辑用户 */
function onEdit(row: SystemUserApi.User) {
  formModalApi.setData(row).open();
}

/** 删除用户 */
async function onDelete(row: SystemUserApi.User) {
  const hideLoading = message.loading({
    content: $t('ui.actionMessage.deleting', [row.username]),
    duration: 0,
    key: 'action_process_msg',
  });
  try {
    await deleteUser(row.id as number);
    message.success({
      content: $t('ui.actionMessage.deleteSuccess', [row.username]),
      key: 'action_process_msg',
    });
    onRefresh();
  } catch {
    hideLoading();
  }
}

/** 重置密码 */
function onResetPassword(row: SystemUserApi.User) {
  resetPasswordModalApi.setData(row).open();
}

/** 分配角色 */
function onAssignRole(row: SystemUserApi.User) {
  assignRoleModalApi.setData(row).open();
}

// TODO @芋艿：后续怎么简化一下 confirm 的实现。
/** 更新用户状态 */
async function onStatusChange(
  newStatus: number,
  row: SystemUserApi.User,
): Promise<boolean | undefined> {
  return new Promise((resolve, reject) => {
    Modal.confirm({
      title: '切换状态',
      content: `你要将${row.username}的状态切换为【${getDictLabel(DICT_TYPE.COMMON_STATUS, newStatus)}】吗？`,
      onCancel() {
        reject(new Error('已取消'));
      },
      onOk() {
        // 更新用户状态
        updateUserStatus(row.id as number, newStatus)
          .then(() => {
            // 提示并返回成功
            message.success({
              content: $t('ui.actionMessage.operationSuccess'),
              key: 'action_process_msg',
            });
            resolve(true);
          })
          .catch((error) => {
            reject(error);
          });
      },
    });
  });
}

/** 表格操作按钮的回调函数 */
function onActionClick({ code, row }: OnActionClickParams<SystemUserApi.User>) {
  switch (code) {
    case 'assign-role': {
      onAssignRole(row);
      break;
    }
    case 'delete': {
      onDelete(row);
      break;
    }
    case 'edit': {
      onEdit(row);
      break;
    }
    case 'reset-password': {
      onResetPassword(row);
      break;
    }
  }
}

const [Grid, gridApi] = useVbenVxeGrid({
  formOptions: {
    schema: useGridFormSchema(),
  },
  gridOptions: {
    columns: useGridColumns(onActionClick, onStatusChange),
    height: 'auto',
    keepSource: true,
    proxyConfig: {
      ajax: {
        query: async ({ page }, formValues) => {
          return await getUserPage({
            pageNo: page.currentPage,
            pageSize: page.pageSize,
            ...formValues,
            deptId: searchDeptId.value,
          });
        },
      },
    },
    rowConfig: {
      keyField: 'id',
    },
    toolbarConfig: {
      refresh: { code: 'query' },
      search: true,
    },
  } as VxeTableGridOptions<SystemUserApi.User>,
});
</script>

<template>
  <Page auto-content-height>
    <DocAlert title="用户体系" url="https://doc.iocoder.cn/user-center/" />
    <DocAlert title="三方登陆" url="https://doc.iocoder.cn/social-user/" />
    <DocAlert
      title="Excel 导入导出"
      url="https://doc.iocoder.cn/excel-import-and-export/"
    />

    <FormModal @success="onRefresh" />
    <ResetPasswordModal @success="onRefresh" />
    <AssignRoleModal @success="onRefresh" />
    <ImportModal @success="onRefresh" />

    <div class="flex h-full">
      <!-- 左侧部门树 -->
      <div class="w-4/24 pr-3">
        <DeptTree @select="onDeptSelect" />
      </div>
      <!-- 右侧用户列表 -->
      <div class="w-18/24">
        <Grid table-title="用户列表">
          <template #toolbar-tools>
            <Button
              type="primary"
              @click="onCreate"
              v-access:code="['system:user:create']"
            >
              <Plus class="size-5" />
              {{ $t('ui.actionTitle.create', ['用户']) }}
            </Button>
            <Button
              type="primary"
              class="ml-2"
              @click="onExport"
              v-access:code="['system:user:export']"
            >
              <Download class="size-5" />
              {{ $t('ui.actionTitle.export') }}
            </Button>
            <Button
              type="primary"
              class="ml-2"
              @click="onImport"
              v-access:code="['system:user:import']"
            >
              <Upload class="size-5" />
              {{ $t('ui.actionTitle.import', ['用户']) }}
            </Button>
          </template>
        </Grid>
      </div>
    </div>
  </Page>
</template>
