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

import type {
  OnActionClickParams,
  VxeTableGridOptions,
} from '#/adapter/vxe-table';
import type { SysUserApi } from '#/api/auth/user';

import { ref } from 'vue';

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

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

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { deleteUser, getUserList, userExportData } from '#/api/auth/user';
import { commonDownloadExcel } from '#/utils/file/download';

import { querySchema, useColumns } from './data';
import DeptTree from './deptTree.vue';
import Form from './form.vue';
import resetPwdModal from './resetPwdModal.vue';
import UserImportModal from './user-import-modal.vue';

/**
 * 导入
 */
const [UserImpotModal, userImportModalApi] = useVbenModal({
  connectedComponent: UserImportModal,
});
function handleImport() {
  userImportModalApi.open();
}

const selectDeptId = ref<number[]>([]);

const formOptions: VbenFormProps = {
  schema: querySchema,
  commonConfig: {
    labelWidth: 80,
    componentProps: {
      allowClear: true,
    },
  },
  handleReset: async () => {
    selectDeptId.value = [];

    const { formApi, reload } = gridApi;
    await formApi.resetForm();
    const formValues = formApi.form.values;
    formApi.setLatestSubmissionValues(formValues);
    await reload(formValues);
  },
  // wrapperClass: 'grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4',
};

const [FormDrawer, formDrawerApi] = useVbenDrawer({
  connectedComponent: Form,
  // destroyOnClose: true,
});

const [Grid, gridApi] = useVbenVxeGrid({
  formOptions,
  gridOptions: {
    columns: useColumns(onActionClick),
    height: 'auto',
    keepSource: true,
    pagerConfig: {
      enabled: true,
    },
    proxyConfig: {
      ajax: {
        query: async ({ page }, formValues = {}) => {
          // 部门树选择处理
          if (selectDeptId.value.length === 1) {
            formValues.deptId = selectDeptId.value[0];
          } else {
            Reflect.deleteProperty(formValues, 'deptId');
          }
          return await getUserList({
            pageNo: page.currentPage,
            pageSize: page.pageSize,
            ...formValues,
          });
        },
      },
    },
    rowConfig: {
      keyField: 'id',
      // 高亮当前行
      isCurrent: true,
    },
  } as VxeTableGridOptions,
});

function onActionClick({ code, row }: OnActionClickParams<SysUserApi.User>) {
  switch (code) {
    case 'delete': {
      onDelete(row);
      break;
    }
    case 'edit': {
      onEdit(row);
      break;
    }
    case 'resetPwd': {
      onResetPwd(row);
      break;
    }
    default: {
      break;
    }
  }
}

const [ResetPwdModal, resetPwdModalApi] = useVbenModal({
  connectedComponent: resetPwdModal,
});

function onResetPwd(row: SysUserApi.User) {
  resetPwdModalApi.setData(row).open();
}

function onRefresh() {
  gridApi.query();
}
function onEdit(row: SysUserApi.User) {
  formDrawerApi.setData({ id: row.id }).open();
}
function onCreate() {
  formDrawerApi.setData({}).open();
}

function onDelete(row: SysUserApi.User) {
  const hideLoading = message.loading({
    content: `正在删除${row.name}...`,
    duration: 0,
    key: 'action_process_msg',
  });
  deleteUser(row.id || 0)
    .then(() => {
      message.success({
        content: `${row.name}删除成功`,
        key: 'action_process_msg',
      });
      onRefresh();
    })
    .catch(() => {
      hideLoading();
    });
}
function handleDownloadExcel() {
  commonDownloadExcel(userExportData, '用户列表', gridApi.formApi.form.values);
}
</script>
<template>
  <Page auto-content-height>
    <div class="flex h-full gap-[8px]">
      <DeptTree
        v-model:select-dept-id="selectDeptId"
        class="w-[260px]"
        @reload="() => gridApi.reload()"
        @select="() => gridApi.reload()"
      />
      <Grid class="flex-1 overflow-hidden" table-title="系统用户列表">
        <template #toolbar-tools>
          <Space>
            <Button v-access:code="['auth:user:import']" @click="handleImport">
              导入
            </Button>
            <Button
              v-access:code="['auth:user:export']"
              @click="handleDownloadExcel"
            >
              导出
            </Button>
            <Button
              type="primary"
              v-access:code="['auth:user:add']"
              @click="onCreate"
            >
              <Plus class="size-5" />
              新增
            </Button>
          </Space>
        </template>
      </Grid>
    </div>
    <FormDrawer @success="onRefresh" />
    <ResetPwdModal />
    <UserImpotModal @reload="onRefresh" />
  </Page>
</template>
