<template>
  <CommonRoot class="main">
    <LoadingPage v-if="loading" /> 
    <FlexCol :padding="30">
      <DynamicForm
        ref="formRef"
        :model="formModel"
        :options="formDefine"
        :formGlobalParams="querys"
      />
      <Height :height="20" />
      <Button type="primary" @click="submit">提交</Button>
    </FlexCol>
  </CommonRoot>
</template>

<script setup lang="ts">
import { computed, nextTick, ref } from 'vue';
import { useLoadQuerys } from '@/common/composeabe/LoadQuerys';
import { showError } from '@/common/composeabe/ErrorDisplay';
import { alert, toast } from '@/components/dialog/CommonRoot';
import { backAndCallOnPageBack } from '@/components/utils/PageAction';
import { RequestApiError } from '@imengyu/imengyu-utils';
import { getVolunteerForm } from './data/volunteer';
import type { IDynamicFormOptions, IDynamicFormRef } from '@/components/dynamic';
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 Height from '@/components/layout/space/Height.vue';
import VillageApi, { VolunteerInfo } from '@/api/inhert/VillageApi';

const loading = ref(false);

const formRef = ref<IDynamicFormRef>();
const formModel = ref<VolunteerInfo>();
const formDefine = ref<IDynamicFormOptions>();

async function submit() {
  if (!formRef.value || !formModel.value)
    return;
  try {
    await formRef.value.validate();
  } catch (e) {
    toast({ content: '有必填项未填写，请检查' });
    return;
  }
  try {
    loading.value = true;
    formModel.value!.villageId = querys.value.villageId;
    console.log('formModel.value', formModel.value);
    
    if (querys.value.id >= 0) {
      await VillageApi.updateVolunteer(formModel.value!);
    } else {
      await VillageApi.addVolunteer(formModel.value!);
    };
    alert({
      title: '操作成功',
      icon: 'success-filling',
      iconColor: 'success',
      content: isNew.value ? '新增志愿者信息成功' : '更新志愿者信息成功',
      onConfirm() {
        backPrev(true);
      },
    });
  } catch (e) {
    showError(e);
  } finally {
    loading.value = false;
  }
}
function backPrev(needRefresh: boolean) {
  backAndCallOnPageBack('list', {
    needRefresh,
  });
}

const { querys } = useLoadQuerys({ 
  villageId: 0,  
  villageVolunteerId: 0,
  onlyPassword: false,
  id: 0,
}, async (querys) => {
  loading.value = true;
  if (!formRef.value)
    return;
  formDefine.value = getVolunteerForm({
    canSetCatalog: true,
    villageId: querys.villageId,
    onlyPassword: querys.onlyPassword,
    isNew,
    formRef,
  });

  let formData = undefined;

  try {
    formModel.value = new VolunteerInfo();
    if (querys.id >= 0)
      formData = await VillageApi.getVolunteerInfoByIdAdmin(querys.id);
  } catch (e) {
    if (!(e instanceof RequestApiError && e.errorMessage.startsWith('请完成')))
      showError(e, undefined, () => backPrev(false));
  } finally {
    loading.value = false;
  }

  if (formData) {
    formModel.value = formData;
  }
   
  await nextTick();
  formRef.value.initDefaultValuesToModel();
});
const isNew = computed(() => querys.value.id < 0);

</script>
