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

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

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

import { useVbenForm } from '#/adapter/form';

import { formColumnOptions } from '../data.config';

defineOptions({
  name: 'TableColumnEdit',
});
const emit = defineEmits(['success']);
const modelRef = ref<Record<string, any>>({});
const isUpdate = ref(true);

const [Form, { validate, setValues, getValues }] = useVbenForm({
  showDefaultActions: false,
  ...formColumnOptions,
});

const [Modal, { close, setState, getData }] = useVbenModal({
  fullscreenButton: false,
  draggable: true,
  onCancel() {
    close();
  },
  onConfirm: async () => {
    try {
      const { valid } = await validate();
      if (valid) {
        const values = await getValues();
        setState({ confirmLoading: true });
        const postParams = { ...unref(modelRef) };
        Object.assign(postParams, values);

        close();
        emit('success', {
          isUpdate: unref(isUpdate),
          data: postParams,
        });
      }
    } catch {
      message.error('操作失败');
    } finally {
      setState({ confirmLoading: false });
    }
  },
  onOpenChange: async (isOpen: boolean) => {
    if (isOpen) {
      setState({ loading: true });
      const data = getData<Record<string, any>>();
      isUpdate.value = !!data.isUpdate;
      modelRef.value = { ...data.baseData };
      setState({ title: unref(isUpdate) ? '编辑列' : '新增列' });

      if (unref(isUpdate)) {
        setValues({ ...data.baseData });
      }
      setState({ loading: false });
    }
  },
  title: '新增列',
});

onMounted(async () => {});
</script>
<template>
  <Modal class="w-[1000px]">
    <Form />
  </Modal>
</template>
