<template>
  <div class="my-form-viewer">
    <BasicForm ref="myDataBaseFormRef" @register="registerForm" />
  </div>
</template>

<script lang="ts" setup>
  import { onMounted, ref, defineProps } from 'vue';
  import { BasicForm, useForm } from '@/components/Form';
  import { functionGetFormDataFormScheme, LoadFormScheme } from '@/api/demo/formScheme';

  const formColumns: FormSchema[] = [];
  const props = defineProps({
    formConfig: Object,
    processId: String,
    formVerison: String,
    formRelationId: String,
    flowFormData: Object,
  });
  props.formConfig.forEach((element) => {
    element.componentProps.disabled = !element.disabled;
  });
  formColumns.value = props.formConfig;
  const [registerForm, { getFieldsValue, setFieldsValue, resetFields, validate }] = useForm({
    labelWidth: 100,
    schemas: props.formConfig,
    showActionButtonGroup: false,
    baseColProps: { lg: 24, md: 24 },
  });

  const keyValue = ref('');
  async function getFormHistory() {
    const data = await LoadFormScheme({
      schemeId: props.formVerison,
    });
    if (data) {
      const scheme = JSON.parse(data.scheme);
      scheme.formInfo.schemas.forEach((element) => {
        if (element.field == props.formRelationId) {
          keyValue.value = element.componentProps.fieldName;
          getFormDetail();
        }
      });
    }
  }
  async function getFormDetail() {
    const querys = {
      id: props.formVerison,
      key: keyValue.value,
      keyValue: props.processId,
    };
    const data = await functionGetFormDataFormScheme(querys);
    let obj = new Object();
    data.forEach((element) => {
      obj[element.columnName] = element.value;
    });
    console.log(obj);
    setFieldsValue({
      ...obj,
    });
  }
  async function getForm() {
    try {
      const values = await validate();
      let query = values;
      return query;
    } catch (error) {
      console.log(error);
      return false;
    }
  }
  defineExpose({
    getForm,
  });
  onMounted(() => {
    if (props.formVerison) {
      getFormHistory();
    } else {
      console.log(props.flowFormData);
      setFieldsValue({
        ...props.flowFormData,
      });
    }
  });
</script>

<style lang="less" scoped>
  .my-process-designer {
    width: 100%;
  }
</style>
