<template>
  <BasicModal v-bind="$attrs" @register="registerModal" destroyOnClose :title="getTitle" :width="800" @ok="handleSubmit">
    <BasicForm @register="registerForm" name="OroqenCultureCategoryForm" />
  </BasicModal>
</template>

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

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

  const isUpdate = ref(true);
  const rowId = ref('');

  // 表单配置
  const [registerForm, { setProps, resetFields, setFieldsValue, validate }] = useForm({
    labelWidth: 100,
    baseColProps: { span: 24 },
    schemas: formSchema,
    showActionButtonGroup: false,
    autoSubmitOnEnter: true,
  });

  // 表单赋值
  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    // 重置表单
    await resetFields();
    setModalProps({ confirmLoading: false, showCancelBtn: !!data?.showFooter, showOkBtn: !!data?.showFooter });
    isUpdate.value = !!data?.isUpdate;

    if (unref(isUpdate)) {
      rowId.value = data.record.id;
      // 表单赋值
      await setFieldsValue({
        ...data.record,
      });
    }

    // 隐藏底部时禁用整个表单
    setProps({ disabled: !data?.showFooter });
  });

  // 表单标题
  const getTitle = computed(() => (!unref(isUpdate) ? '新增' : '编辑'));

  // 表单提交
  async function handleSubmit() {
    try {
      const values = await validate();
      setModalProps({ confirmLoading: true });

      // 提交表单
      await saveOrUpdate(values, unref(isUpdate));
      // 关闭弹窗
      closeModal();
      // 刷新列表
      emit('success');
    } catch (error) {
      console.error('表单提交失败:', error);
      if (error?.errorFields) {
        console.log('验证错误字段:', error.errorFields);
        // 滚动到第一个错误字段
        const firstError = error.errorFields[0];
        if (firstError?.name?.[0]) {
          const fieldElement = document.querySelector(`[data-field="${firstError.name[0]}"]`);
          if (fieldElement) {
            fieldElement.scrollIntoView({ behavior: 'smooth', block: 'center' });
          }
        }
        // 显示具体的验证错误信息
        const errorMessages = error.errorFields.map(field => field.errors.join(', ')).join('; ');
        console.error('验证错误:', errorMessages);
        return;
      }
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }
</script>