<template>
	<el-drawer v-model="visibleDialog" class="le-drawer" size="100%" @close="handleCancel">
		<template #header>
			<div class="flex flex-pack-justify flex_align-center -my-2">
				<span class="text-[16px]">查看详情</span>
				<el-button type="primary" @click="saveDesignEv">保存</el-button>
			</div>
		</template>
		<div>
			<er-form-editor
				v-if="myProps.modelValue"
				ref="EReditorRef"
				:is-show-i18n="false"
				:file-upload-u-r-i="uploadFileApi"
				@listener="handleListener"
			/>
		</div>
	</el-drawer>
</template>

<script setup>
import { computed, ref, watch, nextTick } from 'vue'
import { erFormEditor } from '@ER/formEditor'
import { ElMessage } from 'element-plus'
import formtemplate from '@/api/flow/formtemplate'
const { VITE_APP_BASE_API } = import.meta.env
const EReditorRef = ref()
const formOptions = ref({})
const uploadFileApi = ref(`${VITE_APP_BASE_API}/v1/oss/upload`)

// 同步值
const $myEmit = defineEmits(['update:modelValue', 'successFn'])

const myProps = defineProps({
	modelValue: {
		type: Boolean,
		default: false
	},
	record: {
		type: Object,
		default: () => {}
	}
})

const handleListener = obj => {}

const handleCancel = () => {
	$myEmit('update:modelValue', false)
}

const saveDesignEv = async () => {
	const formStructure = EReditorRef.value.getData()
	const fields = formStructure?.fields || []
	const bool = fields.length
	if (!bool) {
		return ElMessage({
			message: '请设计您的表单模板内容',
			type: 'error'
		})
	}
	const content = JSON.stringify(formStructure)
	await formtemplate.formTemplateAddOrEditSaveApi({ ...myProps.record, content })
	ElMessage.success(`表单模板设计成功~`)
	handleCancel()
	$myEmit('successFn')
}

// computed
const visibleDialog = computed({
	get() {
		return myProps.modelValue
	},
	set(val) {
		$myEmit('update:modelValue', val)
	}
})

watch(
	() => myProps.modelValue,
	(val, oldValue) => {
		if (val) {
			nextTick(() => {
				if (myProps.record?.content) {
					const formStructure = JSON.parse(myProps.record.content || '{}')
					EReditorRef.value.setData(formStructure || {})
				}
			})
		}
	}
)
</script>

<style scoped lang="scss"></style>
