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

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

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

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

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

defineOptions({
  name: 'DictionaryType',
});

const emit = defineEmits(['change']);

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

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

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

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

const gridEvents: VxeGridListeners<DictionaryApi.RecordItem> = {
  currentChange: ({ row }) => {
    emit('change', row.code);
  },
};

const [Grid, { reload }] = useVbenVxeGrid(
  useTableGridOptions({
    gridEvents,
    formOptions: {
      schema: useSearchSchema(),
    },
    gridOptions: {
      rowConfig: {
        isCurrent: true,
        isHover: true,
      },
      columns: useColumns(handleActionClick),
      proxyConfig: {
        ajax: {
          query: async ({ page }, formValues) => {
            return await DictionaryApi.getTypePage({
              pageIndex: page.currentPage,
              pageSize: page.pageSize,
              ...formValues,
            });
          },
        },
      },
    } as VxeTableGridOptions,
  }),
);
</script>
<template>
  <div class="h-full">
    <FormEditModal :close-on-click-modal="false" @success="handelSuccess" />
    <Grid>
      <template #toolbar-tools>
        <Button
          class="mr-2"
          type="primary"
          v-access:code="'dict:add'"
          @click="() => handleEdit({}, false)"
        >
          新增字典类型
        </Button>
      </template>
    </Grid>
  </div>
</template>
