<template>
	<u-form :model="formData" ref="dataForm" :errorType="['toast']" label-position="left" label-width="150">
		<u-form-item :label="item.label" :prop="item.id" v-for="(item, i) in formConfCopy" :key="`${item.id}-${i}`">
			<JnpfInput v-if="useInputList.includes(item.__config__.jnpfKey)" input-align='right'
				v-model="formData[item.id]" :placeholder="textPrefix+item.label" clearable />
			<template v-if="['inputNumber','calculate'].includes(item.__config__.jnpfKey)">
				<JnpfInputNumber v-model="formData[item.id]" :precision="item.precision"
					:placeholder="textPrefix+item.__config__.label" v-if="item.__config__.isFromParam" />
				<JnpfNumberRange v-model="formData[item.id]"
					:precision="!item.precision && item.__config__.jnpfKey=='calculate'?0:item.precision" v-else />
			</template>
			<template v-if="['rate', 'slider'].includes(item.__config__.jnpfKey)">
				<JnpfNumberRange v-model="formData[item.id]" :precision="item.allowHalf ? 1 : 0" />
			</template>
			<JnpfSelect 
				v-if="useSelectList.includes(item.__config__.jnpfKey)" 
				v-model="formData[item.id]"
				:placeholder="selectPrefix+item.label" 
				:options="item.options || []" 
				:props="item.props || { label: 'label', value: 'value' }" 
				:multiple="!!item.searchMultiple" 
				:key="`select-${item.id}-${key}`" 
				filterable 
			/>
			
			<JnpfCascader v-if="item.__config__.jnpfKey==='cascader'" v-model="formData[item.id]"
				:placeholder="selectPrefix+item.label" :options="item.options || []" :props="item.props" filterable
				:showAllLevels="item.showAllLevels" :multiple="item.searchMultiple" />
			<JnpfAutoComplete v-if="item.__config__.jnpfKey==='autoComplete'" v-model="formData[item.id]"
				:interfaceName="item.interfaceName" :placeholder="selectPrefix+item.label"
				:interfaceId="item.interfaceId" :total="item.total" :templateJson="item.templateJson"
				:formData='formData' :relationField="item.relationField" :propsValue="item.propsValue"
				:clearable='item.clearable' />
			<JnpfGroupSelect v-if="item.__config__.jnpfKey==='groupSelect'" v-model="formData[item.id]"
				:vModel='item.id' :multiple="item.searchMultiple" :disabled="item.disabled"
				:placeholder="selectPrefix+item.label" :ableIds="item.ableIds" :selectType="item.selectType" />
			<JnpfRoleSelect v-if="item.__config__.jnpfKey==='roleSelect'" v-model="formData[item.id]"
				:multiple="item.searchMultiple" :disabled="item.disabled" :placeholder="selectPrefix+item.label"
				:ableIds="item.ableIds" :selectType="item.selectType" />
			<JnpfOrganizeSelect v-if="['organizeSelect','currOrganize'].includes(item.__config__.jnpfKey)"
				v-model="formData[item.id]" :placeholder="selectPrefix+item.label"
				:multiple="item.__config__.jnpfKey === 'currOrganize' ? true : item.searchMultiple"
				:ableIds="item.ableIds" :selectType="item.selectType" />
			<JnpfPosSelect v-if="['posSelect','currPosition'].includes(item.__config__.jnpfKey)"
				v-model="formData[item.id]" :placeholder="selectPrefix+item.label" :ableIds="item.ableIds"
				:selectType="item.selectType"
				:multiple="item.__config__.jnpfKey === 'currPosition' ? true : item.searchMultiple" />
			<JnpfUserSelect v-if="['userSelect','createUser', 'modifyUser'].includes(item.__config__.jnpfKey)"
				v-model="formData[item.id]" :placeholder="selectPrefix+item.label" :ableDepIds="item.ableDepIds"
				:ableIds="item.ableIds" :selectType="item.selectType!='custom'?'all':'custom'"
				:multiple="item.searchMultiple" />
			<JnpfUsersSelect v-if="item.__config__.jnpfKey==='usersSelect'" v-model="formData[item.id]"
				:placeholder="selectPrefix+item.label" :clearable="item.clearable" />
			<JnpfTreeSelect v-if="item.__config__.jnpfKey==='treeSelect'" v-model="formData[item.id]"
				:options="item.options || []" :props="item.props" :placeholder="selectPrefix+item.label" filterable
				:multiple="item.searchMultiple" />
			<JnpfAreaSelect v-if="item.__config__.jnpfKey==='areaSelect'" v-model="formData[item.id]"
				:placeholder="selectPrefix+item.label" :level="item.level" :multiple="item.searchMultiple" />
			
			<!-- 日期/时间选择 -->
			<template v-if="useDateList.includes(item.__config__.jnpfKey)">
				<JnpfDatePicker v-model="formData[item.id]" :format='item.format' v-if="item.__config__.isFromParam" />
				<JnpfDateRange v-model="formData[item.id]" :format='item.format' v-else />
			</template>
			<JnpfTimeRange v-if="item.__config__.jnpfKey==='timePicker'" v-model="formData[item.id]"
				:format='item.format' />
		</u-form-item>
	</u-form>
</template>
<script>

	const dyOptionsList = ['radio', 'checkbox', 'select', 'cascader', 'treeSelect'];
	const useSelectList = ['radio', 'checkbox', 'select'];
	const useInputList = ['input', 'textarea', 'text', 'link', 'billRule', 'location'];
	const useDateList = ['createTime', 'modifyTime', 'datePicker', 'dateCalculate'];
	const useArrList = ['cascader', 'address', 'numInput', 'calculate', ...useDateList]

	export default {
		props: ['formConf', 'webType', 'searchFormData'],
		data() {
			return {
				useInputList,
				useDateList,
				useSelectList,
				formConfCopy: [],  // 初始化为空，避免提前克隆
				formData: {},
				key: +new Date(),
				textPrefix: this.$t('common.inputTextPrefix') + ' ',
				selectPrefix: this.$t('common.chooseTextPrefix') + ' ',
			}
		},
		// 核心：深度监听formConf变化，确保数据同步
		watch: {
			// 监听父组件传递的formConf（深度+立即执行）
			formConf: {
				deep: true,
				immediate: true,
				handler(newVal) {
					if (!newVal) return;
					// 重新克隆最新的配置
					this.formConfCopy = this.$u.deepClone(newVal);
					// 延迟初始化，确保DOM更新
					this.$nextTick(() => {
						this.initRelationForm(this.formConfCopy);
						// 初始化时彻底跳过接口请求
						this.initFormData(this.formConfCopy, this.formData);
					});
				}
			},
			// 监听搜索数据变化
			searchFormData: {
				deep: true,
				immediate: true,
				handler(newVal) {
					this.formData = this.$u.deepClone(newVal);
				}
			}
		},
		methods: {
			/**
			 * 初始化表单数据（彻底跳过接口请求）
			 */
			initFormData(componentList, formData) {
				console.log('Parser接收的配置:', componentList);
				if (!componentList || !Array.isArray(componentList)) return;
				
				componentList.forEach(cur => {
					const config = cur.__config__ || {};
					if (cur.id && formData[cur.id] === undefined) {
						// 初始化表单默认值
						formData[cur.id] = cur.value || (cur.searchMultiple ? [] : '');
					}
					
					// 原接口逻辑全部注释，彻底跳过
					/* 
					if (dyOptionsList.indexOf(config.jnpfKey) > -1) {
						if (config.dataType === 'dictionary' && config.dictionaryType) {
							getDictionaryDataSelector(config.dictionaryType).then(res => {
								cur.options = res.data.list || []
								this.key = +new Date()
								this.resetForm()
							})
						}
						if (config.dataType === 'dynamic' && config.propsUrl) {
							const query = {
								paramList: this.jnpf.getParamList(config.templateJson) || []
							};
							getDataInterfaceRes(config.propsUrl, query).then(res => {
								let list = res.data || []
								cur.options = Array.isArray(list) ? list : [];
								this.key = +new Date()
								this.resetForm()
							})
						}
					}
					*/
				});
				
				// 更新key强制刷新组件
				this.key = +new Date();
			},
			
			/**
			 * 初始化关联表单配置
			 */
			initRelationForm(componentList) {
				if (!componentList) return;
				componentList.forEach(cur => {
					const config = cur.__config__ || {};
					if (config.jnpfKey == 'relationFormAttr' || config.jnpfKey == 'popupAttr') {
						const relationKey = cur.relationField?.split("_jnpfTable_")[0];
						if (!relationKey) return;
						componentList.forEach(item => {
							const noVisibility = Array.isArray(item.__config__?.visibility) && !item.__config__.visibility.includes('app');
							if ((relationKey == item.id) && (noVisibility || !!item.__config__?.noShow)) {
								cur.__config__.noShow = true;
							}
						});
					}
					if (cur.__config__?.children && cur.__config__.children.length) {
						this.initRelationForm(cur.__config__.children);
					}
				});
			},
			
			/**
			 * 获取表单数据（空值处理）
			 */
			allCondition() {
				const result = {...this.formData};
				for (let key in result) {
					if (result[key] === 0) continue;
					if (!result[key] || (Array.isArray(result[key]) && result[key].length === 0)) {
						delete result[key];
					}
				}
				return result;
			},
			
			/**
			 * 提交表单
			 */
			submitForm() {
				if (!this.$refs.dataForm) {
					this.$emit('submit', this.allCondition());
					return;
				}
				this.$refs.dataForm.validate(valid => {
					if (!valid) return;
					this.$emit('submit', this.allCondition());
				});
			},
			
			/**
			 * 重置表单
			 */
			resetForm() {
				if (this.$refs.dataForm) {
					this.$refs.dataForm.resetFields();
				}
			}
		}
	}
</script>