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

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

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

import { useTableGridOptions, useVbenVxeGrid } from '#/adapter';
import { LogApi } from '#/api';

import FormView from '../components/view.vue';
import { useExceptionColumns, useSearchSchema } from '../data.config';

const [FormViewModel, formViewApi] = useVbenModal({
  connectedComponent: FormView,
});

const handleView = (data: any) => {
  formViewApi
    .setData({
      baseData: { content: data.message },
    })
    .open();
};

const handleActionClick = async ({
  code,
  row,
}: OnActionClickParams<LogApi.RecordItem>) => {
  switch (code) {
    case 'view': {
      handleView(row);
      break;
    }
  }
};

const [Grid, { reload }] = useVbenVxeGrid(
  useTableGridOptions({
    formOptions: {
      fieldMappingTime: [['__date', ['startTime', 'endTime']]],
      schema: useSearchSchema(),
    },
    gridOptions: {
      columns: useExceptionColumns(handleActionClick),

      proxyConfig: {
        ajax: {
          query: async ({ page }, formValues) => {
            return await LogApi.getExceptionPage({
              pageIndex: page.currentPage,
              pageSize: page.pageSize,
              ...formValues,
            });
          },
        },
      },
    } as VxeTableGridOptions,
  }),
);

const handelClear = () => {
  confirm({
    title: '删除提示',
    content: `确定要清空日志记录吗?`,
    icon: 'question',
    beforeClose: async ({ isConfirm }: { isConfirm: boolean }) => {
      if (isConfirm) {
        await LogApi.clearLog('logException');
        message.success('数据删除成功');
        reload();
        return true;
      } else return false;
    },
  });
};
</script>

<template>
  <Page auto-content-height>
    <FormViewModel />
    <Grid>
      <template #table-title>
        <span class="border-l-primary border-l-8 border-solid pl-2">
          异常日志列表
        </span>
      </template>
      <template #toolbar-tools>
        <Button
          class="mr-2"
          type="primary"
          v-access:code="'logException:clear'"
          @click="() => handelClear()"
        >
          清空日志
        </Button>
      </template>
    </Grid>
  </Page>
</template>
