<script lang="ts" setup>
import { reactive, ref, unref } from 'vue';

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

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

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

defineOptions({
  name: 'QueryView',
});
const modelRef = ref<Record<string, any>>({});

const gridOptions = reactive<VxeGridProps<QueryApi.BasicRecordItem>>({
  columns: [{ title: '序号', type: 'seq', width: 50 }],
  height: 'auto',
  keepSource: true,
  pagerConfig: { enabled: false },
  proxyConfig: {
    autoLoad: false,
    ajax: {
      query: async ({ page }, formValues) => {
        return await QueryApi.postExecuteReal({
          pageIndex: page.currentPage,
          pageSize: page.pageSize,
          ...formValues,
          id: unref(modelRef).id,
        });
      },
    },
  },
});

const [Grid, { reload, setGridOptions }] = useVbenVxeGrid({
  gridOptions,
});

const [Modal, { getData, setState }] = useVbenModal({
  fullscreenButton: true,
  draggable: true,
  footer: false,
  onOpenChange: async (isOpen: boolean) => {
    if (isOpen) {
      setState({ loading: true });

      const data = getData<Record<string, any>>();

      modelRef.value = { ...data.baseData };

      const resColumns = await QueryApi.getColumns(data.baseData.id);

      const columns = [
        { align: 'center', title: '序号', type: 'seq', width: 50 },
      ];

      resColumns.forEach((column) => {
        columns.push({
          align: 'left',
          field: column.alias,
          title: column.remark,
        });
      });

      setGridOptions({
        columns,
      });

      await reload();

      setState({ loading: false });
    }
  },
  title: '查看查询',
});
</script>
<template>
  <Modal class="h-[750px] w-[1000px]">
    <Grid>
      <template #toolbar-tools>
        <Button class="mr-2" type="primary" @click="reload"> 刷新 </Button>
      </template>
    </Grid>
  </Modal>
</template>
