<template>
	<el-drawer
		:close-on-click-modal="false"
		class="local-launch_drawer-wrap"
		:title="record.processName"
		:model-value="modelValue"
		size="760px"
		@update:model-value="updateModelValue"
	>
		<div v-if="validateForm.loading" v-loading="true" class="local_loading"></div>

		<div class="info-wrap">
			<el-divider content-position="left">{{ record.processName }}表单</el-divider>
			<!-- 表单设计 -->
			<template v-if="record.formTemplate.type === 0">
				<div class="self-Everright-formEditor">
					<er-form-preview ref="EReditorRef" :is-show-complete-button="false" :file-upload-u-r-i="uploadFileApi" />
				</div>
			</template>

			<!-- vue自定义 -->
			<template v-if="record.formTemplate.type === 1">
				<component :is="dyVueComponent" ref="dyVueComponentRef" @form-valid="onSubmit"></component>
			</template>

			<el-divider content-position="left">审批流程</el-divider>
			<flow-trend ref="flowTrendRef" v-model="modelContentConfig"></flow-trend>
			<el-divider></el-divider>
		</div>

		<template #footer>
			<el-button @click="updateModelValue(false)">{{ $t('le.btn.cancel') }}</el-button>
			<el-button :disabled="validateForm.loading" type="primary" style="margin-left: 8px" @click="handleFormValid">{{
				$t('le.btn.confirm')
			}}</el-button>
		</template>
	</el-drawer>
</template>

<script setup lang="ts">
import purchaseOrder from '@/api/test/purchaseOrder'
import { ElMessage } from 'element-plus'
import { erFormPreview } from '@ER/formEditor'
import FlowTrend from '@/components/Flow/FlowTrend.vue'
import type { ModelContentConfig } from '@/views/approve/components/config.ts'
import { nextTick, onMounted, ref, markRaw, defineAsyncComponent, provide } from 'vue'

type Props = {
	modelValue: boolean
	record: { processId: string; processName: string; [key: string]: any }
}

// 当前form 表单数据字符串
let cur_processForm_str = '{}'

const updateModelValue = (bool: boolean) => emit('update:modelValue', bool)
const props = defineProps<Props>()
const emit = defineEmits<{
	'update:modelValue': [bool: boolean] // 具名元组语法
	update: [value: string]
}>()
const validateForm = ref({ loading: false })

const { VITE_APP_BASE_API } = import.meta.env
const uploadFileApi = ref(`${VITE_APP_BASE_API}/v1/oss/upload`)
const EReditorRef = ref()
const modelContentConfig = ref<ModelContentConfig | any>({})
const dyVueComponent = ref(undefined)
const dyVueComponentRef = ref()
const flowTrendRef = ref()
const dyVueForm = ref({})

provide('dyVueForm', dyVueForm) // 这里主要是存放动态的form的属性值

/**
 * 1、校验表单
 *  1.1 type=1 校验系统表单
 *  1.2 type=0 校验表单设计
 * 2、提交API
 */
const handleFormValid = () => {
	const { type } = props.record.formTemplate
	if (type) {
		dyVueComponentRef.value.validateForm()
	} else {
		validateDesignForm()
	}
}

// 校验表单设计
const validateDesignForm = () => {
	const form = EReditorRef.value.getSelfFormRef()
	form.validate((valid: any) => {
		if (!valid) return false
		// 提交数据
		onSubmit()
	})
}

const onSubmit = async () => {
	const processId = props.record.processId
	const { type } = props.record.formTemplate
	// 这里要从子节点获取流程图信息 进行保存
	const _assigneeMap = flowTrendRef.value.getAssigneeMap()
	const assigneeMap_ = Object.keys(_assigneeMap).reduce((obj, nodeKey: string) => {
		const _o = _assigneeMap[nodeKey]
		obj[nodeKey] = {
			assigneeList: _o.assignees,
			type: _o.type
		}
		return obj
	}, {} as { [nodeKey: string]: any })
	const paramCommon = {
		id: props.record.rowId,
		test: '', // 系统表单JSON内容
		processStart: {
			processId, // 流程ID
			processForm: '', // 设计表单JSON内容
			assigneeMap: assigneeMap_
		}
	}
	validateForm.value.loading = true
	// type: 0 设计表单  1 vue系统表单
	if (type) {
		const testData = {
			formStructure: '@/views/flow/test/test1.vue',
			formData: dyVueComponentRef.value.getComponentData()
		}
		paramCommon.test = JSON.stringify(testData)
	} else {
		const formData = EReditorRef.value.getData()
		let processForm = JSON.parse(cur_processForm_str)
		processForm = { ...processForm, formData }
		paramCommon.processStart.processForm = JSON.stringify(processForm)
	}
	purchaseOrder
		.postlaunchApi(paramCommon)
		.then(res => {
			ElMessage.success('提交成功')
			updateModelValue(false)
		})
		.finally(() => {
			validateForm.value.loading = false
		})
}

// 获取当前表单中的详情
const getDetailInfo = () => {
	validateForm.value.loading = true
	let modelContent_config = {}
	const modelContent = JSON.parse(props.record.modelContent) // modelContent 这个是后台返回来的
	modelContent_config = modelContent.nodeConfig ?? modelContent.childNode
	modelContentConfig.value = modelContent_config
	const { content, type } = props.record.formTemplate
	if (!type) {
		// type: 0 表单设计  1 vue自定义表单
		cur_processForm_str = `{"formStructure":${content}}` || '{}' //  processForm 这个是后台返回来的
		const { formStructure } = JSON.parse(cur_processForm_str)
		EReditorRef.value.setData(formStructure)
	} else {
		// dyVueForm.value = {
		// 	dy: {
		// 		name: '测试名字',
		// 		region: 1,
		// 		delivery: true,
		// 		type: ['1'],
		// 		resource: 'Sponsor',
		// 		desc: '啦啦啦'
		// 	}
		// }
		dyVueComponent.value = markRaw(defineAsyncComponent(() => import('@/views/flow/test/test1.vue')))
	}
	validateForm.value.loading = false
}

onMounted(() => {
	nextTick(() => {
		getDetailInfo()
	})
})
</script>

<style lang="scss">
// 和ItemDrawer一样可以公用，待提取
.local-launch_drawer-wrap {
	.el-drawer__header {
		display: flex;
		padding: 16px 24px;
		align-items: center;
		justify-content: space-between;
		background-color: var(--el-color-info-light-9);
		text-align: left;
		/* margin-right: 0; */
		margin-bottom: 0;
	}
	.el-drawer__close-btn {
		padding: 0;
		margin-right: -12px;
	}
	.el-drawer__body {
		position: relative;
		display: flex;
		flex-direction: column;
	}
	.el-drawer__footer {
		border-top: 1px solid var(--el-border-color-lighter);
		padding: 12px 24px;
	}
	.local_loading {
		position: absolute;
		left: 0;
		display: flex;
		align-items: center;
		justify-content: center;
		width: 100%;
		height: 100%;
		z-index: 999;
		background: rgba(0, 0, 0, 0.05);
	}
}
</style>

<style scoped lang="scss">
.info-wrap {
	.form-wrap {
		flex: 1;
	}

	// 修改everright 表单的样式
	.self-Everright-formEditor {
		:deep(.Everright-formEditor-selectElement) {
			padding: 0px 16px;
		}
	}
}
</style>
