<template>
  <CommonRoot class="main">
    <LoadingPage v-if="loading" /> 
    <FlexCol :padding="30">
      <DynamicForm
        ref="formRef"
        :formDefine="formDefine"
        :formProps="{
          labelPosition: 'top',
          labelAlign: 'left',
        }"
        :formGlobalParams="querys"
      />
      <Height :height="20" />
      <Button type="primary" @click="submit">提交</Button>
    </FlexCol>
  </CommonRoot>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import { showError } from '@/common/composeabe/ErrorDisplay';
import { useLoadQuerys } from '@/common/composeabe/LoadQuerys';
import { getVillageInfoForm } from './forms';
import { backAndCallOnPageBack } from '@imengyu/imengyu-utils/dist/uniapp/PageAction';
import { RequestApiError } from '@imengyu/imengyu-utils/dist/request';
import VillageInfoApi, { CommonInfoModel } from '@/api/inhert/VillageInfoApi';
import DynamicForm from '@/components/dynamic/DynamicForm.vue';
import LoadingPage from '@/components/display/loading/LoadingPage.vue';
import Button from '@/components/basic/Button.vue';
import CommonRoot from '@/components/dialog/CommonRoot.vue';
import FlexCol from '@/components/layout/FlexCol.vue';
import type { FormDefine, FormExport } from '@/components/dynamic';
import Height from '@/components/layout/space/Height.vue';

const popupRef = ref();
const loading = ref(false);

const formRef = ref<FormExport>();
const formDefine = ref<FormDefine>();

async function submit() {
  if (!formRef.value)
    return;
  try {
    const data = await formRef.value.submitForm<CommonInfoModel>();
    if (!data)
      return;
    loading.value = true;
    data.type = querys.value.subId;
    await VillageInfoApi.updateInfo(
      querys.value.subType,
      querys.value.villageId,
      querys.value.villageVolunteerId,
      data,
    );
    popupRef.value.open();
  } catch (e) {
    showError(e);
  } finally {
    loading.value = false;
  }
}
function backPrev(needRefresh: boolean) {
  backAndCallOnPageBack('list', {
    needRefresh,
  });
}

const { querys } = useLoadQuerys({ 
  villageId: 0,  
  villageVolunteerId: 0,
  subType: '',
  subId: 0,
  id: 0,
}, async (querys) => {
  loading.value = true;
  if (!formRef.value)
    return;

  let formData = undefined;

  try {
    const [model, forms] = getVillageInfoForm(querys.subType, querys.subId);
    formRef.value.initFormData(() => new model());
    formDefine.value = forms;
    if (querys.id >= 0)
      formData = await VillageInfoApi.getInfo(
        querys.subType, 
        querys.subId,
        querys.villageId, 
        querys.villageVolunteerId,
        querys.id,
        model,
      );
  } catch (e) {
    if (!(e instanceof RequestApiError && e.errorMessage.startsWith('请完成')))
      showError(e, undefined, () => backPrev(false));
  } finally {
    loading.value = false;
  }

  if (formData) {
    formRef.value.loadFormData(formData);
  }
});
</script>
