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

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

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

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { deleteUserMethod, listUsersMethod } from '#/api';
import { $t } from '#/locales';

import { useUserSearchFormSchema, useUserTableColumns } from './data';
import Form from './modules/form.vue';

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

const [Grid, gridApi] = useVbenVxeGrid({
  formOptions: {
    schema: useUserSearchFormSchema(),
    submitOnChange: true,
  },
  gridOptions: {
    columns: useUserTableColumns(onActionClick),
    height: 'auto',
    keepSource: true,
    proxyConfig: {
      ajax: {
        query({ page }, formValues) {
          return listUsersMethod(page.currentPage, page.pageSize, formValues);
        },
      },
    },
    rowConfig: {
      keyField: 'id',
    },

    toolbarConfig: {
      custom: true,
      export: false,
      refresh: true,
      search: true,
      zoom: true,
    },
  } as VxeTableGridOptions<SystemModel.User>,
});

function onActionClick(e: OnActionClickParams<SystemModel.User>) {
  switch (e.code) {
    case 'delete': {
      onDeleteHandle(e.row);
      break;
    }
    case 'edit': {
      onEditHandle(e.row);
      break;
    }
  }
}

function onRefresh() {
  gridApi.query();
}

function onEditHandle(row?: SystemModel.User) {
  formModalApi.setData(row ?? {}).open();
}

async function onDeleteHandle(row: SystemModel.User) {
  const hideLoading = message.loading({
    content: $t('ui.actionMessage.deleting', [row.name]),
    duration: 0,
    key: 'action_process_msg',
  });
  try {
    await deleteUserMethod(row);
    message.success({
      content: $t('ui.actionMessage.deleteSuccess', [row.name]),
      key: 'action_process_msg',
    });
    onRefresh();
  } finally {
    hideLoading();
  }
}
</script>
<template>
  <Page auto-content-height>
    <FormModal @success="onRefresh" />
    <Grid :table-title="$t('system.user.list')">
      <template #toolbar-tools>
        <Button type="primary" @click="onEditHandle()">
          <Plus class="size-5" />
          {{ $t('ui.actionTitle.create', [$t('system.user._')]) }}
        </Button>
      </template>
    </Grid>
  </Page>
</template>
