<template>
  <BasicModal v-bind="$attrs" @register="registerModal" :title="getTitle" @ok="handleSubmit">
    <BasicForm @register="registerForm" />
  </BasicModal>
</template>
<script lang="ts" setup>
  import { computed, unref, ref } from 'vue';
  import { buildUUID } from '/@/utils/uuid';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm, FormSchema } from '/@/components/TableForm/index';
  import { useI18n } from '/@/hooks/web/useI18n';
  const { t } = useI18n();
  const isUpdate = ref(true);
  const rowKey = ref('');

  // 入参
  const props = defineProps({
    formOption: { type: [Array] as PropType<FormSchema[]>, required: true }, //表单配置json
  });

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

  const formOption = computed(() => props.formOption);

  const [registerForm, { validate, resetFields, setFieldsValue }] = useForm({
    labelWidth: 100,
    schemas: formOption,
    showActionButtonGroup: false,
    actionColOptions: {
      span: 23,
    },
  });

  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    isUpdate.value = !!data?.isUpdate;
    //如果是新增 重置表单
    if (!unref(isUpdate)) {
      rowKey.value = buildUUID();
      resetFields();
    } else {
      rowKey.value = data?.record.rowKey;
      setFieldsValue(data?.record);
    }
  });

  const getTitle = computed(() => (!unref(isUpdate) ? t('新增') : t('编辑')));

  async function handleSubmit() {
    try {
      const values = await validate();
      setModalProps({ confirmLoading: true });

      emits('success', { ...values, rowKey: rowKey.value });
      closeModal();
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }
</script>
