<!-- 表单预览 - 抽屉方式 -->
<template>
	<el-dialog
		v-model="visible"
		v-loading="loading"
		:title="showTitle"
		:before-close="handleClose"
		:modal="false"
		:width="showWidth"
		destroy-on-close
		center
		:modal-append-to-body="false"
		:close-on-click-modal="false"
	>
		<div>
			<v-form-render
				ref="vFormRef"
				:dynamic-creation="true"
				:form-json="dataForm.formJson"
				:form-data="dataForm.formData"
				:option-data="dataForm.optionData"
				:disabled-mode="dataForm.isLook == 1"
				@appendButtonClick="testOnAppendButtonClick"
			></v-form-render>
		</div>
		<template #footer>
			<el-button v-for="(item, index) in dataForm.btnList" v-auth="getBtnAuth(item)" v-show="dataForm.isLook == 0" v-prevent-reclick type="primary" @click="btnForm(item)"
				>{{ item.btnLabel }}
			</el-button>
		</template>
		<report-dev-review-dialog ref="reportDialogRef" @close="closeReportDialog" @confirmAddRow="reportDialogAddData"></report-dev-review-dialog>
	</el-dialog>
</template>
<script setup lang="ts">
import { nextTick, reactive, ref } from 'vue'
import { btnServerUrl, defaultBtnServer, getFormConfig, getInfo, saveForm, updateForm } from '../api/formDevReview'
import { ElMessage, ElMessageBox } from 'element-plus'
import ReportDevReviewDialog from '../report/reportDevReviewDialog.vue'

const emit = defineEmits(['refreshDataList'])
const visible = ref(false)
const loading = ref(false)
const vFormRef = ref()
const showWidth = ref('70%')
const showTitle = ref('')
const reportDialogRef = ref()

const getBtnAuth = (item:any)=>{
  return item.btnCode;
}
const dataForm = reactive({
	formCode: '',
	loading: false,
	formJson: {},
	formData: {},
	optionData: {},
	formId: 0,
	btnList: [],
	id: '',
	btnCode: '',
	isLook: 0,
	appendButtonClickCall: {
		appendButtonClickBreakData: '',
		appendButtonClickBreakSetData: '',
		subFormRowIndex: -1,
		subFormName: ''
	}
})

const init = (formCode?: string, formData: any, isLook: number, btnCode: any, clickBtnData: any) => {
	dataForm.id = ''
	dataForm.btnCode = ''
	dataForm.isLook = isLook
	if (formData) {
		dataForm.id = formData.id
	}
	// 重置表单数据
	if (vFormRef.value) {
		//vFormRef.value.resetFields()
		vFormRef.value.setFormData({})
	}
	if (clickBtnData) {
		if (clickBtnData.btnLinkFormWidth && clickBtnData.btnLinkFormWidth != '') {
			showWidth.value = clickBtnData.btnLinkFormWidth
		}
		if (clickBtnData.btnLinkFormTitle && clickBtnData.btnLinkFormTitle != '') {
			showTitle.value = clickBtnData.btnLinkFormTitle
		}
	}
	visible.value = true

	if (formCode) {
		showForm(formCode, btnCode, formData)
	}
}

const showForm = (formCode: any, btnCode: any, formData: any) => {
	debugger
	var data = { formCode: formCode }
	dataForm.formCode = formCode
	getFormConfig(data).then(response => {
    if(/(%[0-9A-F2-F]{2})+/i.test(response.data.formJson)){
      response.data.formJson = decodeURIComponent(response.data.formJson);
    }
		dataForm.formJson = JSON.parse(response.data.formJson)
		dataForm.btnList = response.data.fastFormBtnList

		if (dataForm.id != '') {
			var obj = { devFormCode: dataForm.formCode, btnCode: btnCode, btnFormData: { id: dataForm.id } }
			getInfo(obj).then(res => {
				vFormRef.value.setFormJson(dataForm.formJson)
				nextTick(() => {
					if (formData.reportToFormData) {
						debugger
						vFormRef.value.setFormData(formData.reportToFormData)
					}
					vFormRef.value.setFormData(res.data)
				})
			})
		} else {
			vFormRef.value.setFormJson(dataForm.formJson)
			nextTick(() => {
				//从列表透传过来的数据，如果存在，则赋值给到表单
				if (formData.reportToFormData) {
					vFormRef.value.setFormData(formData.reportToFormData)
				}
			})
		}
	})
}

const btnForm = (btnData: any) => {
	if (btnData.serviceType == 10 || btnData.serviceType == 20 || btnData.serviceType == 55 || btnData.serviceType == 60) {
		submitForm(btnData)
	}
}
const handleClose = () => {
	visible.value = false
	vFormRef.value.setBlankFormJson()
	emit('refreshDataList')
}
const submitForm = (btnData: any) => {
	vFormRef.value
		.getFormData()
		.then(formData => {
			ElMessageBox.confirm('请确定要执行此操作吗？', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			}).then(() => {
				var obj = { devFormCode: dataForm.formCode, btnCode: btnData.btnCode, btnFormData: formData }
				console.log('form表单请求内容:', obj)
				if (dataForm.id != '') {
					obj.btnFormData.id = dataForm.id
					if (btnData.serviceType == '10') {
						updateForm(obj).then(res => {
							ElMessage.success({
								message: '修改成功',
								duration: 500,
								onClose: () => {
									handleClose()
								}
							})
							//请求后增强
							btnClickAfterEnhance(btnData, res, obj)
						})
					} else if (btnData.serviceType == '55') {
						defaultBtnServer(obj).then(res => {
							ElMessage.success({
								message: '操作成功',
								duration: 500,
								onClose: () => {
									handleClose()
								}
							})
							//请求后增强
							btnClickAfterEnhance(btnData, res, obj)
						})
					} else if (btnData.serviceType == '60') {
						btnServerUrl(btnData.btnServerUrl, obj).then(res => {
							ElMessage.success({
								message: '操作成功',
								duration: 500,
								onClose: () => {
									handleClose()
								}
							})
							//请求后增强
							btnClickAfterEnhance(btnData, res, obj)
						})
					}
				} else {
					if (btnData.serviceType == '10') {
						saveForm(obj).then(res => {
							ElMessage.success({
								message: '保存成功',
								duration: 500,
								onClose: () => {
									handleClose()
								}
							})
							//请求后增强
							btnClickAfterEnhance(btnData, res, obj)
						})
					} else if (btnData.serviceType == '55') {
						defaultBtnServer(obj).then(res => {
							ElMessage.success({
								message: '操作成功',
								duration: 500,
								onClose: () => {
									handleClose()
								}
							})
							//请求后增强
							btnClickAfterEnhance(btnData, res, obj)
						})
					} else if (btnData.serviceType == '60') {
						btnServerUrl(btnData.btnServerUrl, obj).then(res => {
							ElMessage.success({
								message: '操作成功',
								duration: 500,
								onClose: () => {
									handleClose()
								}
							})
							//请求后增强
							btnClickAfterEnhance(btnData, res, obj)
						})
					}
				}
			})
		})
		.catch(error => {
			ElMessage.error({
				message: error,
				duration: 500
			})
		})
}

/**
 * 按钮请求后增强
 * @param btnData
 * @param res
 */
const btnClickAfterEnhance = (btnData: any, res: any, reqData: any) => {
	if (btnData.btnClickAfterEnhance && btnData.btnClickAfterEnhance != '') {
		console.log(res)
		console.log(reqData)
		var enhance = decodeURIComponent(btnData.btnClickAfterEnhance)
		eval(enhance)
	}
}

const testOnAppendButtonClick = (sourceCall: any) => {
	dataForm.appendButtonClickCall.appendButtonClickBreakData = sourceCall.field.options.appendButtonClickBreakData
	dataForm.appendButtonClickCall.appendButtonClickBreakSetData = sourceCall.field.options.appendButtonClickBreakSetData
	dataForm.appendButtonClickCall.subFormRowIndex = sourceCall.subFormRowIndex
	dataForm.appendButtonClickCall.subFormName = sourceCall.subFormName
	reportDialogRef.value.init(sourceCall.field.options.appendButtonClickFormCode, sourceCall.btnQueryForm,sourceCall.field.options.checkMany)
}
const closeReportDialog = (isSearch: any) => {
	console.log('closeReportDialog')
}
const reportDialogAddData = (selectedData: any) => {
	console.log('选中的数据:', selectedData)
	//表单确认返回值
	var appendButtonClickBreakData = dataForm.appendButtonClickCall.appendButtonClickBreakData.split(',')
	//表示清除数据
	if (selectedData.length == 0) {
		var obj = {}
		for (var i = 0; i < appendButtonClickBreakData.length; i++) {
			obj[appendButtonClickBreakData[i]] = ''
		}
		selectedData.push(obj)
	}
	//表单确认返设值
	var appendButtonClickBreakSetData = dataForm.appendButtonClickCall.appendButtonClickBreakSetData.split(',')
	//子表
	if (dataForm.appendButtonClickCall.subFormName && dataForm.appendButtonClickCall.subFormName != '') {
		//表格绑定数据名称
		var appendButtonTableDataName = dataForm.appendButtonClickCall.subFormName
		//表格绑定数据行
		var appendButtonTableRowIndex = dataForm.appendButtonClickCall.subFormRowIndex
		if (appendButtonTableDataName && appendButtonTableDataName != null) {
			selectedData.forEach(item => {
				for (var i = 0; i < appendButtonClickBreakData.length; i++) {
					vFormRef.value.setSubFormDataByIndex(
						appendButtonTableDataName,
						appendButtonTableRowIndex,
						appendButtonClickBreakSetData[i],
						item[appendButtonClickBreakData[i]]
					)
				}
			})
		}
	} else {
		//表单
		selectedData.forEach(item => {
			for (var i = 0; i < appendButtonClickBreakData.length; i++) {
				vFormRef.value.setFieldValue(appendButtonClickBreakSetData[i], item[appendButtonClickBreakData[i]])
			}
		})
	}
	vFormRef.value.validateForm()

	closeReportDialog()
}
defineExpose({
	init
})
</script>
