<template>
  <!-- 表单 -->
  <div class="about main-background main-background-type0">
    <div class="nav-placeholder"></div>
    <!-- 表单 -->
    <section class="main-section ">
      <div class="content">
        <div class="title">
          <h2>{{ title }}</h2>
        </div>
        <a-spin v-if="loadingData" />
        <template v-else>
          <DynamicForm
            ref="form"
            :model="(formModel as any)" 
            :options="formOptions"
          />
          <a-button 
            type="primary"
            block 
            :loading="loading" class="mt-3" 
            @click="handleSubmit"
          >
            提交
          </a-button>
        </template>
      </div>
    </section>
  </div>
</template>

<script setup lang="ts" generic="T extends DataModel">
import InheritorContent from '@/api/inheritor/InheritorContent';
import type { DataModel } from '@imengyu/js-request-transform';
import { DynamicForm, type IDynamicFormOptions, type IDynamicFormRef } from '@imengyu/vue-dynamic-form';
import { message, Modal, type FormInstance } from 'ant-design-vue';
import { onMounted, ref, toRefs, type PropType } from 'vue';
import { useRouter } from 'vue-router';

const props = defineProps({
  title: {
    type: String,
    default: '项目申报'
  },
  formModel: {
    type: Object as PropType<T>,
    required: true
  },
  formOptions: {
    type: Object as PropType<IDynamicFormOptions>,
    required: true
  },
  load: {
    type: Function as PropType<() => Promise<T|undefined|void>>,
    default: () => Promise.resolve()
  },
  save: {
    type: Function as PropType<(model: T) => Promise<void>>,
    default: () => Promise.resolve()
  }
})

const { formModel, formOptions, load } = toRefs(props);
const form = ref<IDynamicFormRef>();

const router = useRouter();
const loading = ref(false);
const loadingData = ref(false);

async function handleSubmit() {
  loading.value = true;

  const ref = (form.value?.getFormRef() as FormInstance);
  try {
    await ref.validate();
  } catch (e) {
    message.warn('请填写完整信息');
    loading.value = false;
    if ((e as any).errorFields)
      ref.scrollToField((e as any).errorFields[0].name, { block: 'center' })
    return;
  }
  try {
    const result = await InheritorContent.saveBaseInfo(formModel.value);
    await props.save(formModel.value);
    Modal.success({
      title: '提交成功',
      content: result.message,
      onOk() {
        router.push({ path: '/' })
      },
    });
  } catch (error) {
    Modal.error({
      title: '提交失败',
      content: '' + error,
    });
  } finally {
    loading.value = false;
  }
}
async function loadData() {
  loadingData.value = true;
  try {
    await load.value();
  } catch (error) {
    Modal.error({
      title: '加载失败',
      content: '' + error,
    });
  } finally {
    loadingData.value = false;
  }
}

onMounted(async () => {
  await loadData();
})
</script>

