<template>
  <BasicModal v-bind="$attrs" @register="registerModal" :title="title" width="640px" @ok="handleSubmit">
    <BasicForm @register="registerForm" />
  </BasicModal>
</template>

<script lang="ts" setup>
  import { computed, ref, unref } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { formSchema } from '../MesXslRackTrainCountSetting.data';
  import { queryById, saveSetting } from '../MesXslRackTrainCountSetting.api';

  const emit = defineEmits(['register', 'success']);
  const isDetail = ref(false);

  const [registerForm, { resetFields, setFieldsValue, validate, setProps }] = useForm({
    labelWidth: 100,
    schemas: formSchema,
    showActionButtonGroup: false,
  });

  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    await resetFields();
    setModalProps({ confirmLoading: false, showCancelBtn: data?.showFooter, showOkBtn: data?.showFooter });
    isDetail.value = !data?.showFooter;
    const record = data?.record || {};
    if (record.id) {
      try {
        const detail = await queryById({ id: record.id });
        await setFieldsValue({
          ...detail,
          mixingSpecId: detail.mixingSpecId || detail.id,
        });
      } catch {
        await setFieldsValue({
          ...record,
          mixingSpecId: record.mixingSpecId || record.id,
        });
      }
    }
    setProps({ disabled: !data?.showFooter });
  });

  const title = computed(() => (unref(isDetail) ? '架子车数设定详情' : '架子车数设定'));

  async function handleSubmit() {
    if (unref(isDetail)) {
      closeModal();
      return;
    }
    try {
      const values = await validate();
      setModalProps({ confirmLoading: true });
      await saveSetting({
        id: values.id,
        mixingSpecId: values.mixingSpecId || values.id,
        setTrainCount: values.setTrainCount,
      });
      closeModal();
      emit('success');
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }
</script>
