<script lang="ts" setup>
import type { VxeGridListeners } from '#/adapter/vxe-table';

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

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

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { DictionaryApi } from '#/api';
import { TableAction } from '#/components/table-action';

import { gridOptions, searchFormOptions } from './data.config';
import FormEdit from './edit.vue';

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

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

const [Grid, { reload }] = useVbenVxeGrid({
  gridEvents,
  formOptions: searchFormOptions,
  gridOptions,
});

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

const handleDelete = (id: number) => {
  Modal.confirm({
    iconType: 'info',
    title: '删除提示',
    content: `确定要删除选择的记录吗?`,
    cancelText: `关闭`,
    onOk: async () => {
      await DictionaryApi.deleteTypeDetail(id);
      message.success('数据删除成功');
      reload();
    },
  });
};

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

  formEditApi.open();
};

const handelSuccess = () => {
  reload();
};
</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>
      <template #action="{ row }">
        <TableAction
          :actions="[
            {
              label: '编辑',
              type: 'text',
              disabled: !hasAccessByCodes(['dict:edit']),
              onClick: handleEdit.bind(null, row, true),
            },
            {
              label: '删除',
              type: 'text',
              disabled: !hasAccessByCodes(['dict:delete']),
              onClick: handleDelete.bind(null, row.id),
            },
          ]"
        />
      </template>
    </Grid>
  </div>
</template>
