<script lang="ts" setup>
import { ref, watch } from 'vue';

import { BpmModelFormType } from '@vben/constants';

import FormCreate from '@form-create/ant-design-vue';

import { useVbenForm } from '#/adapter/form';
import { getFormDetail } from '#/api/bpm/form';
import { setConfAndFields2 } from '#/components/form-create';

import { useFormDesignFormSchema } from './form-data';

const [FormDesignForm, formDesignFormApi] = useVbenForm({
  commonConfig: {
    componentProps: {
      class: 'w-full',
    },
    formItemClass: 'col-span-2',
    labelWidth: 120,
  },
  layout: 'horizontal',
  schema: useFormDesignFormSchema(),
  showDefaultActions: false,
});

// 创建本地数据副本
const modelData = defineModel<any>();

// 表单预览数据
const formPreview = ref({
  formData: {} as any,
  rule: [],
  option: {
    submitBtn: false,
    resetBtn: false,
    formData: {},
  },
});

/** 监听表单ID变化，加载表单数据 */
watch(
  () => modelData.value.formId,
  async (newFormId) => {
    if (newFormId && modelData.value.formType === BpmModelFormType.NORMAL) {
      const data = await getFormDetail(newFormId);
      setConfAndFields2(formPreview.value, data.conf, data.fields);
      // 设置只读
      formPreview.value.rule.forEach((item: any) => {
        item.props = { ...item.props, disabled: true };
      });
    } else {
      formPreview.value.rule = [];
    }
  },
  { immediate: true },
);

/** 表单校验 */
async function validate() {
  await formDesignFormApi.validate();
}

defineExpose({ validate });
</script>
<template>
  <div>
    <FormDesignForm />
    <!-- 表单预览 -->
    <div
      v-if="
        modelData.formType === BpmModelFormType.NORMAL &&
        modelData.formId &&
        formPreview.rule.length > 0
      "
      class="mb-5 mt-7 rounded-sm border border-solid border-gray-200 p-5"
    >
      <div class="mb-4 flex items-center">
        <div class="mr-2 h-4 w-1 bg-blue-500"></div>
        <span class="text-base font-bold">表单预览</span>
      </div>
      <FormCreate
        v-model:api="formPreview.formData"
        :rule="formPreview.rule"
        :option="formPreview.option"
      />
    </div>
  </div>
</template>
