<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 { createProcess, updateProcess } from '#/views/system/process/api';
import { modalFormProps } from '#/views/system/process/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);
  const payload: Record<string, any> = {
    id: values.id,
  };

  if (formLevel === 3) {
    payload.node_type = 'note';
    payload.rule_id = values.rule_id;
    payload.note = values.note;
    if (values.volume !== undefined && values.volume !== null) {
      payload.volume = values.volume;
    }
    if (values.real_id) {
      payload.real_id = values.real_id;
    }
    return payload;
  }

  payload.node_type = 'rule';
  payload.name = values.name;
  payload.pid = formLevel === 1 ? 0 : values.pid;
  if (formLevel === 2) {
    payload.calc_method = values.calc_method;
    payload.price = values.price;
    payload.unit = values.unit;
  }

  return payload;
}

function validateFormValues(values: Record<string, any>) {
  const formLevel = Number(values.formLevel);
  if (formLevel === 3) {
    if (!String(values.note ?? '').trim()) {
      message.error('请输入备注名称');
      return false;
    }
    if (values.volume === null || values.volume === undefined || values.volume === '') {
      message.error('请输入毫升');
      return false;
    }
    return true;
  }
  if (!String(values.name ?? '').trim()) {
    message.error('请输入名称');
    return false;
  }
  if (formLevel === 2) {
    if (!values.pid) {
      message.error('请选择父级制剂');
      return false;
    }
    if (!values.calc_method) {
      message.error('请选择计算方式');
      return false;
    }
    if (values.price === null || values.price === undefined || values.price === '') {
      message.error('请输入计算价格');
      return false;
    }
    if (!values.unit) {
      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 ? updateProcess : createProcess;
    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: '煎法',
        3: '备注',
      };
      modalTitle.value = `${update ? '编辑' : '新增'}${levelLabels[formLevel] ?? '加工费'}`;
      formApi.resetForm();
      if (values) {
        const formValues = {
          ...values,
          formLevel,
          note: values.note ?? values.name,
          has_children: values.has_children ?? false,
        };
        formApi.setValues(formValues);
      }
    } else {
      onSuccessRef.value = null;
    }
  },
});
</script>
<template>
  <Modal :title="modalTitle" class="w-[32%]">
    <Form />
  </Modal>
</template>
