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

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

import { useVbenVxeGrid } from '#/adapter';
import { QueryApi } from '#/api';

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

const { hasAccessByCodes } = useAccess();

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

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

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

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

  formEditApi.open();
};

const handleView = (id: number) => {
  formViewApi.setData({ baseData: { id } });
  formViewApi.open();
};

const handelSuccess = () => {
  reload();
};
</script>

<template>
  <Page auto-content-height>
    <FormEditModal :close-on-click-modal="false" @success="handelSuccess" />
    <FormViewModal :close-on-click-modal="false" />
    <Grid>
      <template #toolbar-tools>
        <Button
          class="mr-2"
          type="primary"
          v-access:code="'query:add'"
          @click="() => handleEdit({}, false)"
        >
          新增查询
        </Button>
      </template>
      <template #action="{ row }">
        <div class="flex items-center">
          <Button
            :disabled="!hasAccessByCodes(['query:edit'])"
            type="link"
            @click="() => handleEdit(row, true)"
          >
            编辑
          </Button>
          <Button
            :disabled="!hasAccessByCodes(['query:view'])"
            danger
            type="link"
            @click="() => handleView(row.id)"
          >
            查看
          </Button>

          <Dropdown>
            <a class="ant-dropdown-link" @click.prevent>
              <More class="size-4" />
            </a>
            <template #overlay>
              <Menu>
                <Menu.Item
                  key="0"
                  :disabled="!hasAccessByCodes(['query:delete'])"
                  @click="() => handleDelete(row.id)"
                >
                  <a href="#">删除</a>
                </Menu.Item>
              </Menu>
            </template>
          </Dropdown>
        </div>
      </template>
    </Grid>
  </Page>
</template>
