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

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

import { message } from 'ant-design-vue';
import dayjs from 'dayjs';

import { ACTION_ICON, TableAction, useVbenVxeGrid } from '#/adapter/vxe-table';
import {
  deleteProject,
  exportProject,
  getProjectPage,
} from '#/api/license/project';
import { $t } from '#/locales';

import { useGridColumns, useGridFormSchema } from './data';
import Form from './modules/form.vue';
import ImportForm from './modules/import-form.vue';
import Progress from './modules/progress.vue';

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

const [ProgressDrawer, progressDrawerApi] = useVbenDrawer({
  connectedComponent: Progress,
  destroyOnClose: true,
});

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

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

/** 创建项目 */
function onCreate() {
  formModalApi.setData({}).open();
}

/** 编辑项目 */
function onEdit(row: ProjectApi.Project) {
  formModalApi.setData(row).open();
}

/** 项目进展 */
function onProgress(row: ProjectApi.Project) {
  progressDrawerApi.setData(row).open();
}

/** 删除项目 */
async function onDelete(row: ProjectApi.Project) {
  const hideLoading = message.loading({
    content: $t('ui.actionMessage.deleting', [row.name]),
    duration: 0,
    key: 'action_process_msg',
  });
  try {
    await deleteProject(row.id as number);
    hideLoading();
    message.success($t('ui.actionMessage.deleteSuccess', [row.name]));
    onRefresh();
  } catch {
    hideLoading();
  }
}

/** 导出表格 */
async function onExport(body: any) {
  const formValues = await gridApi.formApi.getValues();
  const data = await exportProject({ ...body, ...formValues });
  downloadFileFromBlobPart({
    fileName: `${body.filename}.xlsx`,
    source: data,
  });
}

/** 表格操作按钮的回调函数 */
function onActionClick({ code, row }: OnActionClickParams<ProjectApi.Project>) {
  switch (code) {
    case 'delete': {
      onDelete(row);
      break;
    }
    case 'edit': {
      onEdit(row);
      break;
    }
    case 'progress': {
      onProgress(row);
      break;
    }
  }
}

const [Grid, gridApi] = useVbenVxeGrid({
  formOptions: {
    collapsed: true,
    collapsedRows: 2,
    schema: useGridFormSchema(),
    submitOnEnter: true,
    wrapperClass: 'grid-cols-1 md:grid-cols-2 lg:grid-cols-4',
  },
  gridOptions: {
    columns: useGridColumns(onActionClick),
    height: 'auto',
    pagerConfig: {
      enabled: true,
    },
    id: 'license-project-list',
    customConfig: {
      storage: true,
    },
    exportConfig: {
      remote: true,
      type: 'xlsx',
      types: ['xlsx'],
      mode: 'all',
      modes: [
        { label: '导出全部数据', value: 'all' },
        { label: '导出当前页数据', value: 'current' },
      ],
      filename() {
        return `项目数据${dayjs().format('YYYYMMDDHHmmss')}`;
      },
      sheetName() {
        return `项目列表`;
      },
      slots: {
        parameter: 'exportParameter',
      },
      async exportMethod({ options, $grid }) {
        const proxyInfo = $grid?.getProxyInfo();
        // 处理条件参数
        const body = {
          filename: options.filename,
          sheetName: options.sheetName,
          isHeader: options.isHeader,
          original: options.original,
          mode: options.mode,
          pageNo: proxyInfo ? proxyInfo.pager.currentPage : null,
          pageSize: proxyInfo ? proxyInfo.pager.pageSize : null,
          ids:
            options.mode === 'selected'
              ? options.data.map((item) => item.id)
              : [],
          includeFields: options.columns.map((column) => {
            return column.field;
          }),
        };
        await onExport(body);
      },
    },
    proxyConfig: {
      sort: true,
      ajax: {
        query: async ({ page, sort }, formValues) => {
          return await getProjectPage({
            pageNo: page.currentPage,
            pageSize: page.pageSize,
            sortField: sort.field,
            sortOrder: sort.order,
            ...formValues,
          });
        },
      },
    },
    rowConfig: {
      keyField: 'id',
      isHover: true,
    },
    sortConfig: {
      remote: true,
      multiple: false,
    },
    toolbarConfig: {
      refresh: { code: 'query' },
      search: true,
      export: true,
    },
  } as VxeTableGridOptions<ProjectApi.Project>,
});
</script>

<template>
  <Page auto-content-height>
    <FormModal @success="onRefresh" />
    <ProgressDrawer @success="onRefresh" />
    <ImportModal @success="onRefresh" />

    <Grid :table-title="$t('project.list')">
      <template #toolbar-tools>
        <TableAction
          :actions="[
            {
              label: $t('ui.actionTitle.create', [$t('project.project')]),
              type: 'primary',
              icon: ACTION_ICON.ADD,
              auth: ['license:project:create'],
              onClick: onCreate,
            },
          ]"
        />
      </template>
    </Grid>
  </Page>
</template>
