<script lang="ts" setup>
import { useAccess } from '@vben/access';
import { Page, useVbenModal } from '@vben/common-ui';

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

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

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

const { hasAccessByCodes } = useAccess();

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

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

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

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

  formEditApi.open();
};

const handelSuccess = () => {
  reload();
};
</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>
      <template #action="{ row }">
        <TableAction
          :actions="[
            {
              label: '编辑',
              type: 'text',
              disabled: !hasAccessByCodes(['post:edit']),
              onClick: handleEdit.bind(null, row, true),
            },
            {
              label: '删除',
              type: 'text',
              danger: true,
              disabled: !hasAccessByCodes(['post:delete']),
              onClick: handleDelete.bind(null, row.id),
            },
          ]"
          :drop-down-actions="[
            {
              label: row.status === 1 ? '禁用' : '启用',
              type: 'link',
              disabled: !hasAccessByCodes(['role:setStatus']),
              onClick: handleUpdateStatus.bind(null, row),
            },
          ]"
        />
      </template>
    </Grid>
  </Page>
</template>
