<template>
  <a-drawer v-model:visible="visible"
            :title="title"
            :width="width"
            :destroy-on-close="destroyOnClose"
            :placement="placement">
    <a-table :rowKey="rowKey"
             :columns="columns"
             :data-source="source"
             :pagination="tablePageOptions"
             @change="onPageChange">
      <template #operator="{ record }">
        <slot :data="record"></slot>
      </template>
    </a-table>
  </a-drawer>
</template>

<script lang="ts">
import { defineComponent, PropType, ref, watchEffect } from "vue";

import usePagination from "@/hooks/usePagination";

import { IMeta, PageOptions } from "@/types/api";

const DrawerWrapper = defineComponent({
  props: {
    show: {
      type: Boolean,
      default: false,
    },
    destroyOnClose: {
      type: Boolean,
      default: true,
    },
    width: {
      type: [Number, String],
      default: "70%",
    },
    placement: {
      type: String,
      default: "right",
    },
    rowKey: {
      type: String,
      default: "id",
    },
    title: String,
    source: Array,
    columns: Array,
    meta: {
      type: Object as PropType<Partial<IMeta>>,
      default: {},
    },
  },
  emits: ["update:show", "pageChange"],
  setup(props, { emit }) {
    const { meta, tablePageOptions } = usePagination();

    let visible = ref(props.show);

    watchEffect(() => (meta.value = props.meta));

    watchEffect(() => (visible.value = props.show));

    watchEffect(() => emit("update:show", visible.value));

    const onPageChange = (pagination: PageOptions) => {
      emit("pageChange", pagination.current);
    };

    return { visible, tablePageOptions, onPageChange };
  },
});

export default DrawerWrapper;
</script>