<template>
  <div class="modals">
    <BasicModal
      v-bind="$attrs"
      destroyOnClose
      @register="registerModal"
      :title="getTitle"
      @ok="handleSubmit"
      :width="880"
      @cancel="handleCancel"
    >
      <div class="!pl-8 !pt-4">
        <BasicForm @register="registerForm" />
      </div>
    </BasicModal>
  </div>
</template>
<script lang="ts" setup>
  import { ref, computed, unref } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { dataFormSchema } from './data';

  import { suppliesAdd, suppliesById, suppliesEdit } from '/@/api/biz/inventory/suppliesApi';

  const emit = defineEmits(['success', 'cancel', 'register']);

  const getTitle = computed(() => (!unref(isUpdate) ? '新增耗材' : '编辑耗材'));
  const isUpdate = ref(false);
  const rowId = ref();

  const { createMessage } = useMessage();
  const [registerForm, { resetFields, validate, setFieldsValue }] = useForm({
    layout: 'vertical',
    showResetButton: true,
    labelWidth: 100,
    schemas: dataFormSchema,
    showActionButtonGroup: false,
    actionColOptions: {
      span: 24,
    },
    baseColProps: {
      span: 12,
    },
    wrapperCol: {
      span: 22,
    },
  });
  const [registerModal, { setModalProps, closeModal }] = useModalInner(async data => {
    await resetFields();
    setModalProps({ confirmLoading: false });
    isUpdate.value = !!data?.isUpdate;

    if (unref(isUpdate)) {
      rowId.value = data.record.id;
      const resData = await suppliesById(data.record.id);
      console.log('resData::::', resData);
      await setFieldsValue({
        ...resData,
      });
    }
  });

  // 提交按钮事件
  async function handleSubmit() {
    try {
      const values = await validate();
      setModalProps({ confirmLoading: true });
      !unref(isUpdate)
        ? await suppliesAdd({ ...values })
        : await suppliesEdit({ ...values, id: rowId.value });
      !unref(isUpdate) ? createMessage.success('新增成功！') : createMessage.success('编辑成功！');
      closeModal();
      emit('success', { isUpdate: unref(isUpdate), values: { ...values, id: rowId.value } });
    } finally {
      setModalProps({ confirmLoading: false, canFullscreen: false });
    }
  }

  async function handleCancel() {
    closeModal();
    emit('cancel');
  }
</script>
<style lang="less" scoped>
  ::v-deep(.ant-modal) {
    background-color: #000;
  }
</style>
