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

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

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

import { useVbenForm } from '#/adapter/form';
import { createRegion, updateRegion } from '#/views/system/region/api';
import { modalFormProps } from '#/views/system/region/config/form';

const isUpdate = ref(false);
const onSuccessRef = ref<(() => void) | null>(null);

const [Form, formApi] = useVbenForm(modalFormProps);

function buildSubmitPayload(values: Record<string, any>) {
  const formLevel = Number(values.formLevel);
  return {
    id: values.id,
    name: values.name,
    pid: formLevel === 1 ? 0 : values.pid,
    express_fee: values.express_fee ?? 0,
  };
}

function validateFormValues(values: Record<string, any>) {
  const formLevel = Number(values.formLevel);
  if (!String(values.name ?? '').trim()) {
    message.error('请输入名称');
    return false;
  }
  if (formLevel === 2 && !values.pid) {
    message.error('请选择父级地区');
    return false;
  }
  if (
    values.express_fee === null ||
    values.express_fee === undefined ||
    values.express_fee === ''
  ) {
    message.error('请输入快递费');
    return false;
  }
  return true;
}

const modalTitle = ref('新增快递费');

const [Modal, modalApi] = useVbenModal({
  fullscreenButton: false,
  draggable: true,
  onCancel() {
    modalApi.close();
  },
  onConfirm: async () => {
    const values = await formApi.getValues();
    if (!validateFormValues(values)) {
      return;
    }
    const payload = buildSubmitPayload(values);
    modalApi.setState({ loading: true, confirmLoading: true });
    const submitApi = isUpdate.value ? updateRegion : createRegion;
    submitApi(payload)
      .then(() => {
        message.success('保存成功');
        onSuccessRef.value?.();
        modalApi.close();
      })
      .finally(() => {
        modalApi.setState({ loading: false, confirmLoading: false });
      });
  },
  onOpenChange(isOpen: boolean) {
    if (isOpen) {
      const { values, update, formLevel, onSuccess } = modalApi.getData<
        Record<string, any>
      >();
      isUpdate.value = update;
      onSuccessRef.value = onSuccess ?? null;
      const levelLabels: Record<number, string> = {
        1: '地区',
        2: '子地区',
      };
      modalTitle.value = `${update ? '编辑' : '新增'}${levelLabels[formLevel] ?? '快递费'}`;
      formApi.resetForm();
      if (values) {
        formApi.setValues({ ...values, formLevel });
      }
    } else {
      onSuccessRef.value = null;
    }
  },
});
</script>
<template>
  <Modal :title="modalTitle" class="w-[32%]">
    <Form />
  </Modal>
</template>
