<script setup name="FormDesign">
import { onBeforeUnmount, onMounted, ref } from 'vue'
// import { erFormEditor } from 'everright-formeditor'
import { erFormEditor } from '@ER/formEditor'
// import 'Everright-formEditor/dist/style.css'
import useFlowStore from '@/store/modules/flow'
import { storeToRefs } from 'pinia'
const flowStore = useFlowStore()
const { processForm } = storeToRefs(flowStore)
const { VITE_APP_BASE_API } = import.meta.env
const EReditorRef = ref()
const uploadFileApi = ref(`${VITE_APP_BASE_API}/v1/oss/upload`)

const handleListener = obj => {}

// 保存当前的表单数据 processForm.value = '{formStructure: 表单结构值, formData: {}}
const exportJsonEv = () => {
	const formStructure = EReditorRef.value.getData()
	const finallyForm = { formStructure, formData: {} }
	processForm.value = JSON.stringify(finallyForm)
}

const validate = () => {
	// 根据后续的业务需求 调整 validate 的功能
	exportJsonEv()
	return new Promise((resolve, reject) => {
		const formStructure = EReditorRef.value.getData()
		const fields = formStructure?.fields || []
		const bool = fields.length
		if (bool) {
			resolve(true)
		} else {
			reject(false)
		}
	})
}

// onBeforeUnmount(() => {
// 	const formData = EReditorRef.value.getData()
// 	if (formData.hasOwnProperty('fields')) {
// 		// 离开前 做处理
// 		// const { fields } = formData
// 		// console.log(fields.length, '=======')
// 	} else {
// 		ElMessage.error(`表单设计有误，请重新配置`)
// 	}
// })

const updateCompInfo = () => {
	if (processForm.value) {
		// {formStructure: 表单结构值, formData: {}}
		const { formStructure } = JSON.parse(processForm.value)
		EReditorRef.value.setData(formStructure || {})
	}
}

// 初始化的时候，渲染当前组件的值
onMounted(() => {
	updateCompInfo()
})

defineExpose({
	exportJsonEv,
	validate,
	updateCompInfo
})
</script>
<template>
	<div class="form-design-wrap">
		<er-form-editor ref="EReditorRef" :is-show-i18n="false" :fileUploadURI="uploadFileApi" @listener="handleListener" />
	</div>
</template>
