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

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

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

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

import FormEdit from './components/edit.vue';
import { useColumns, useSearchSchema } from './data.config';

const [FormEditModal, formEditApi] = useVbenModal({
  connectedComponent: FormEdit,
});

const handelSuccess = () => {
  reload();
};
const handleDelete = async (id: number) => {
  await PostApi.deleteDetail(id);
  message.success('数据删除成功');
  handelSuccess();
};

const handleUpdateStatus = async (record: any) => {
  await PostApi.updateStatus({
    id: record.id,
    status: record.status === 1 ? 2 : 1,
  });
  handelSuccess();
};

const handleEdit = (record: any, isUpdate: boolean) => {
  formEditApi
    .setData({
      isUpdate,
      baseData: { id: record.id },
    })
    .open();
};

const handleActionClick = async ({
  code,
  row,
}: OnActionClickParams<PostApi.RecordItem>) => {
  switch (code) {
    case 'delete': {
      await handleDelete(row.id);
      break;
    }
    case 'edit': {
      handleEdit(row, true);
      break;
    }
    case 'setStatus': {
      await handleUpdateStatus(row);
      break;
    }
  }
};

const [Grid, { reload }] = useVbenVxeGrid(
  useTableGridOptions({
    formOptions: {
      schema: useSearchSchema(),
    },
    gridOptions: {
      columns: useColumns(handleActionClick),
      proxyConfig: {
        ajax: {
          query: async ({ page }, formValues) => {
            return await PostApi.getPage({
              pageIndex: page.currentPage,
              pageSize: page.pageSize,
              ...formValues,
            });
          },
        },
      },
    } as VxeTableGridOptions,
  }),
);
</script>

<template>
  <Page auto-content-height>
    <FormEditModal :close-on-click-modal="false" @success="handelSuccess" />
    <Grid>
      <template #toolbar-tools>
        <Button
          class="mr-2"
          type="primary"
          v-access:code="'post:add'"
          @click="() => handleEdit({}, false)"
        >
          新增岗位
        </Button>
      </template>
    </Grid>
  </Page>
</template>
