<template>
  <uni-forms 
    ref="formRef"
    v-bind="formProps"
    :model="formModel"
    :rules="formRules"
  >
    <SimpleDynamicFormCate
      v-if="formModel"
      :formModel="formModel"
      :formDefine="formDefine"
      :formDefineParentKey="''"
      :formDefineParentLabel="''"
    />
  </uni-forms>
</template>

<script setup lang="ts">
import { computed, onMounted, provide, reactive, ref, toRef, watch, type PropType } from 'vue';
import { toast } from '@imengyu/imengyu-utils/dist/uniapp/DialogAction';
import type { FormDefine, FormDefineItem, FormExport } from '.';
import SimpleDynamicFormCate from './SimpleDynamicFormCate.vue';
import { waitTimeOut } from '@imengyu/imengyu-utils';

const props = defineProps({	
  formDefine: {
    type: Object as PropType<FormDefine>,
    default: () => ({})
  },
  formProps: {
    type: Object,
    default: () => ({}) 
  },
  formGlobalParams: {
    type: Object,
    default: () => ({})
  },
});

const formRef = ref<any>();
const formModel = ref<any>(null);
const formRules = computed(() => {
  const rules: Record<string, any> = {};
  function loop(prevKey: string, arr: FormDefineItem[]) {
    if (!arr || !(arr instanceof Array))
     return;
    for (const item of arr) {
      const key = prevKey ? `${prevKey}.${item.name}` : item.name;
      if (key)
        rules[key] = { 
          label: item.label,
		      validateTrigger: 'submit',
          rules: item.rules
        };
      if (item.children) {
        loop(
          item.children.propNestType === 'flat' ? key : prevKey, 
          item.children.items
        );
      }
    }
  }
  loop('', props.formDefine.items);
  return rules;
});
const formGlobalParams = toRef(props.formGlobalParams);

provide('formTopModel', formModel);
provide('formGlobalParams', formGlobalParams);

watch(formRules, (v) => {
  formRef.value?.setRules(v);
});
watch(() => props.formDefine, (v) => {
  reloadFormData();
});

let isErrorState = false;
let initCb : () => any = () => {
  return {};
};

function initFormData(data: () => any) {
  initCb = data;
}
function loadFormData(value?: Record<string, any>) {
  const obj = reactive(initCb());

  function loop(prevKey: string, arr: FormDefineItem[]) {
    if (!arr || !(arr instanceof Array))
     return;
    for (let index = 0; index < arr.length; index++) {
      const item = arr[index];
      const key = prevKey ? `${prevKey}.${item.name}` : item.name;
      if (key) {
        const valueProvided = value?.[key] ;
        obj[key] = valueProvided == null || valueProvided == undefined ? 
          (typeof item.defaultValue === 'function' ? item.defaultValue() : item.defaultValue)  
          : valueProvided ?? null;
        item.fullName = key;
      } else {
        item.fullName = '';
      }
      if (item.children)
        loop(
          item.children.propNestType === 'flat' ? key : prevKey, 
          item.children.items
        );
    }
  }

  loop('', props.formDefine.items);
  formModel.value = obj;
}
async function submitForm<T = Record<string, any>>() : Promise<T|null> {
  await formRef.value.clearValidate();
  await waitTimeOut(50);
  
  try {
    await formRef.value.validate();
  } catch (e) {
    if (isErrorState)
      toast('请将表单填写完整');
    console.log(e);
    isErrorState = true;
    return null;
  }
  isErrorState = false;
  return formModel.value;
}
function resetForm() {
  loadFormData();
}

function reloadFormData() {
  if (!formModel.value)
    loadFormData();
  formRef.value.setRules(formRules.value);
}

onMounted(() => {
  setTimeout(() => reloadFormData(), 300);
});

defineExpose<FormExport>({
  initFormData,
  loadFormData,
  submitForm,
  resetForm,
})

</script>