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

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

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

import TablePage from '#/views/system/design/table/components/page.vue';

defineOptions({
  name: 'TablePreview',
});
const emit = defineEmits(['success']);
const state = reactive<{
  mode: 'page' | 'popup' | 'view';
  multiple: boolean;
  tableQueryCode: string;
}>({
  tableQueryCode: '',
  multiple: false,
  mode: 'popup',
});

const tablePageRef = ref();

const [Modal, { close, setState, getData }] = useVbenModal({
  draggable: true,
  fullscreen: false,
  onConfirm: async () => {
    try {
      setState({ confirmLoading: true });

      const selectedData = tablePageRef.value.getSelectRow();
      if (isEmpty(selectedData)) {
        message.warning('请选择数据');
        return;
      }

      close();
      emit('success', { type: 'update', data: selectedData });
    } finally {
      setState({ confirmLoading: false });
    }
  },
  onOpenChange: async (isOpen: boolean) => {
    if (isOpen) {
      setState({ loading: true });
      const data = getData<Record<string, any>>();
      state.multiple = !!data.multiple;
      state.tableQueryCode = data.baseData.code;
      setState({ title: `${data.baseData.name}` });
    }
  },
  title: '选择数据',
});

const handelLoadData = () => {
  setState({ loading: false });
};

const handleAppend = () => {
  try {
    setState({ confirmLoading: true });

    const selectedData = tablePageRef.value.getSelectRow();
    if (isEmpty(selectedData)) {
      message.warning('请选择数据');
      return;
    }

    close();
    emit('success', { type: 'append', data: selectedData });
  } finally {
    setState({ confirmLoading: false });
  }
};
</script>
<template>
  <Modal class="h-[800px] w-[1000px]">
    <TablePage ref="tablePageRef" v-bind="state" @success="handelLoadData" />
    <template #prepend-footer>
      <Button v-if="state.multiple" type="link" @click="handleAppend">
        追加
      </Button>
    </template>
  </Modal>
</template>
