<template>
  <div>
    <BasicDrawer
      v-bind="$attrs"
      size="large"
      @register="registerDrawer"
      @close="handleCloser"
      :title="t('表单预览')"
      v-if="isDesignPreview"
    >
      <div>
        <SimpleForm ref="formRef" :formProps="state.formProps" :formModel="state.formModel" />
      </div>
    </BasicDrawer>
    <BasicModal
      v-bind="$attrs"
      size="large"
      @register="registerModal"
      @close="handleCloser"
      :title="t('表单预览')"
      v-else
    >
      <div>
        <SimpleForm ref="formRef" :formProps="state.formProps" :formModel="state.formModel" />
      </div>
    </BasicModal>
  </div>
</template>
<script lang="ts" setup>
  import { reactive, ref } from 'vue';
  import SimpleForm from './components/SimpleForm.vue';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { buildOption } from '/@/utils/helper/designHelper';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { getQnExecuteInfo } from '/@/api/questionnaire/template';

  const props = defineProps({
    isDesignPreview: Boolean,
  });

  const { t } = useI18n();
  const state = reactive({
    formProps: {} as any,
    formModel: {},
  });

  const formRef = ref();
  const [registerDrawer, { setDrawerProps }] = useDrawerInner(async (option) => {
    setDrawerProps({
      destroyOnClose: true,
      width: option?.config?.formWidth || 800,
      canFullscreen: true,
    });
    useInner(option);
  });

  const [registerModal, { setModalProps }] = useModalInner(async (option) => {
    setModalProps({
      destroyOnClose: true,
      canFullscreen: true,
      fixedHeight: true,
      width: 800,
    });
    useInner(option);
  });

  const useInner = async (option) => {
    setTimeout(async () => {
      if (option.id && option.dataId) {
        const data = await getQnExecuteInfo({ id: option.id, dataId: option.dataId });
        formRef.value.setFieldsValue(data);
        option.formJson.list?.map((info) => {
          info.options.disabled = true;
        });
      }
      formRef.value.setProps({
        ...buildOption(option.formJson, false),
        layout: 'vertical',
        showResetButton: !!props.isDesignPreview,
        showSubmitButton: !!props.isDesignPreview,
      });
      if (props.isDesignPreview) {
        formRef.value.setDefaultValue();
        formRef.value.resetFields();
      }
    }, 50);
  };

  //关闭方法
  const handleCloser = () => {
    formRef.value!.resetFields(); //重置表单
    state.formProps = {};
  };
</script>
