<template>
	<view class="container">
		<image class="bg" src="https://ysrw-1395926010.cos.ap-chengdu.myqcloud.com/images/bg_qestion.png" mode="widthFix"></image>
		<view class="fixed-top-box" :style="{background: bgColor }">
			<view class="status_bar" :style="{height: statusBarHeight}"></view>
			<view class="back-box" @click="goBack">
				<image src="@/static/image/back.png" mode=""></image>
				<text class="title">问卷调查</text>
				<text></text>
			</view>
		</view>
		<scroll-view class="content" scroll-y>
			<!-- 表单标题 -->
			<view class="form-header">
				<view class="form-title">{{ formTitle }}</view>
				<view class="form-tips">
					<view class="tip-item">请您根据患者真实情况选择并填写</view>
					<view class="tip-item">我们承诺对您及患者所提供的所有信息严格保密</view>
				</view>
			</view>
			
			<!-- 动态表单内容 -->
			<view class="form-section">
				<view 
					class="form-item" 
					v-for="(field, index) in formFields" 
					:key="getFieldKey(field, index)">
					<view class="form-label">
						<text class="required" v-if="field.__config__.required">*</text>
						<text>{{ index + 1 }}、{{ field.__config__.label }}</text>
					</view>
					
					<!-- 单行文本输入 -->
					<template v-if="field.__config__.tag === 'el-input' && field.type !== 'textarea'">
						<input 
							class="form-input" 
							:value="formData[field.__vModel__] || ''" 
							@input="(e) => onInputChange(field, e)"
							:placeholder="field.placeholder || '请输入' + field.__config__.label"
							type="text"
							:disabled="field.disabled"
							placeholder-class="text-placeholder"
						/>
					</template>
					
					<!-- 多行文本输入 -->
					<template v-else-if="field.__config__.tag === 'el-input' && field.type === 'textarea'">
						<textarea 
							class="form-textarea" 
							:value="formData[field.__vModel__] || ''" 
							@input="(e) => onInputChange(field, e)"
							:placeholder="field.placeholder || '请输入' + field.__config__.label"
							:maxlength="field.maxlength"
							:disabled="field.disabled"
							:auto-height="field.autosize ? true : false"
							placeholder-class="text-placeholder"
						/>
					</template>
					
					<!-- 计数器 -->
					<template v-else-if="field.__config__.tag === 'el-input-number'">
						<view class="input-number-wrapper">
							<view class="input-number-btn" @click="(e) => decreaseNumber(field, index)" :class="{ disabled: isNumberMin(field) }">-</view>
							<input 
								class="form-input input-number-input" 
								:value="formData[field.__vModel__] || ''" 
								@input="(e) => onNumberInputChange(field, e)"
								type="number"
								:placeholder="field.placeholder || '请输入' + field.__config__.label"
								:disabled="field.disabled"
								placeholder-class="text-placeholder"
							/>
							<view class="input-number-btn" @click="(e) => increaseNumber(field, index)" :class="{ disabled: isNumberMax(field) }">+</view>
						</view>
					</template>
					
					<!-- 下拉选择 -->
					<template v-else-if="field.__config__.tag === 'el-select'">
						<picker 
							mode="selector" 
							:range="getSelectOptions(field)" 
							range-key="label"
							:value="getSelectIndex(field)"
							@change="(e) => onSelectChange(field, e)">
							<view class="form-input picker-input" :class="{ placeholder: !formData[field.__vModel__] }">
								{{ getSelectLabel(field) || field.placeholder || '请选择' + field.__config__.label }}
								<image class="w48 h48" src="@/static/image/icon_more.png" mode=""></image>
							</view>
						</picker>
					</template>
					
					<!-- 滑块 -->
					<template v-else-if="field.__config__.tag === 'el-slider'">
						<view class="slider-wrapper">
							<slider 
								:value="formData[field.__vModel__] || field.__config__.defaultValue || 0"
								:min="field.min || 0"
								:max="field.max || 100"
								:step="field.step || 1"
								:show-value="true"
								activeColor="#388BFF"
								@change="(e) => onSliderChange(field, e)"
							/>
						</view>
					</template>
					
					<!-- 多选框组 -->
					<template v-else-if="field.__config__.tag === 'el-checkbox-group'">
						<checkbox-group @change="(e) => onCheckboxChange(field, e)" class="checkbox-group">
							<label 
								class="checkbox-item"
								v-for="(option, optIndex) in getSelectOptions(field)" 
								:key="optIndex">
								<checkbox 
									:value="option.value" 
									:checked="isCheckboxChecked(field, option.value)" 
									color="#388BFF" 
								/>
								<text>{{ option.label }}</text>
							</label>
						</checkbox-group>
					</template>
					
					<!-- 单选框组 -->
					<template v-else-if="field.__config__.tag === 'el-radio-group'">
						<radio-group @change="(e) => onRadioChange(field, e)" class="radio-group">
							<label 
								class="radio-item"
								v-for="(option, optIndex) in getSelectOptions(field)" 
								:key="optIndex">
								<radio 
									:value="option.value" 
									:checked="formData[field.__vModel__] == option.value" 
									color="#388BFF" 
								/>
								<text>{{ option.label }}</text>
							</label>
						</radio-group>
					</template>
					
					<!-- 文件上传 -->
					<template v-else-if="field.__config__.tag === 'el-upload'">
						<view class="upload-section">
							<view class="upload-item" v-for="(file, fileIndex) in getUploadFiles(field)" :key="fileIndex">
								<image class="uploaded-image" :src="file" mode="aspectFill" v-if="isImageFile(file)"></image>
								<view class="uploaded-file" v-else>
									<text class="file-name">{{ getFileName(file) }}</text>
								</view>
								<view class="delete-btn" @click="(e) => removeUploadFile(field, fileIndex, index)">×</view>
							</view>
							<view class="upload-item upload-placeholder" @click="(e) => chooseUploadFile(field, index)">
								<image class="w48 h48" src="@/static/image/icon_camera1.png" mode=""></image>
								<text class="upload-text">{{ field.__config__.buttonText || '点击上传' }}</text>
							</view>
						</view>
					</template>
					
					<!-- 开关 -->
					<template v-else-if="field.__config__.tag === 'el-switch'">
						<switch 
							:checked="formData[field.__vModel__] || false"
							:disabled="field.disabled"
							:color="field['active-color'] || '#388BFF'"
							@change="(e) => onSwitchChange(field, e)"
						/>
					</template>
					
					<!-- 时间选择 -->
					<template v-else-if="field.__config__.tag === 'el-time-picker' && !field['is-range']">
						<picker 
							mode="time" 
							:value="formData[field.__vModel__] || ''"
							@change="(e) => onTimePickerChange(field, e)">
							<view class="form-input picker-input" :class="{ placeholder: !formData[field.__vModel__] }">
								{{ formData[field.__vModel__] || field.placeholder || '请选择' + field.__config__.label }}
								<!-- <image class="w48 h48" src="@/static/image/icon_my_more.png" mode=""></image> -->
							</view>
						</picker>
					</template>
					
					<!-- 时间范围 -->
					<template v-else-if="field.__config__.tag === 'el-time-picker' && field['is-range']">
						<view class="time-range-wrapper">
							<picker 
								mode="time" 
								:value="getTimeRangeStart(field)"
								@change="(e) => onTimeRangeStartChange(field, e)">
								<view class="form-input picker-input time-range-input" :class="{ placeholder: !getTimeRangeStart(field) }">
									{{ getTimeRangeStart(field) || field['start-placeholder'] || '开始时间' }}
									<!-- <image class="w48 h48" src="@/static/image/icon_my_more.png" mode=""></image> -->
								</view>
							</picker>
							<text class="time-range-separator">{{ field['range-separator'] || '至' }}</text>
							<picker 
								mode="time" 
								:value="getTimeRangeEnd(field)"
								@change="(e) => onTimeRangeEndChange(field, e)">
								<view class="form-input picker-input time-range-input" :class="{ placeholder: !getTimeRangeEnd(field) }">
									{{ getTimeRangeEnd(field) || field['end-placeholder'] || '结束时间' }}
									<!-- <image class="w48 h48" src="@/static/image/icon_my_more.png" mode=""></image> -->
								</view>
							</picker>
						</view>
					</template>
					
					<!-- 日期选择 -->
					<template v-else-if="field.__config__.tag === 'el-date-picker' && field.type !== 'daterange'">
						<picker 
							mode="date" 
							:value="formData[field.__vModel__] || ''"
							:start="field['start-date'] || ''"
							:end="field['end-date'] || ''"
							@change="(e) => onDatePickerChange(field, e)">
							<view class="form-input picker-input" :class="{ placeholder: !formData[field.__vModel__] }">
								{{ formData[field.__vModel__] || field.placeholder || '请选择' + field.__config__.label }}
								<!-- <image class="w48 h48" src="@/static/image/icon_my_more.png" mode=""></image> -->
							</view>
						</picker>
					</template>
					
					<!-- 日期范围 -->
					<template v-else-if="field.__config__.tag === 'el-date-picker' && field.type === 'daterange'">
						<view class="date-range-wrapper">
							<picker 
								mode="date" 
								:value="getDateRangeStart(field)"
								@change="(e) => onDateRangeStartChange(field, e)">
								<view class="form-input picker-input date-range-input" :class="{ placeholder: !getDateRangeStart(field) }">
									{{ getDateRangeStart(field) || field['start-placeholder'] || '开始日期' }}
									<!-- <image class="w48 h48" src="@/static/image/icon_my_more.png" mode=""></image> -->
								</view>
							</picker>
							<text class="date-range-separator">{{ field['range-separator'] || '至' }}</text>
							<picker 
								mode="date" 
								:value="getDateRangeEnd(field)"
								@change="(e) => onDateRangeEndChange(field, e)">
								<view class="form-input picker-input date-range-input" :class="{ placeholder: !getDateRangeEnd(field) }">
									{{ getDateRangeEnd(field) || field['end-placeholder'] || '结束日期' }}
									<!-- <image class="w48 h48" src="@/static/image/icon_my_more.png" mode=""></image> -->
								</view>
							</picker>
						</view>
					</template>
					
					<!-- 评分 -->
					<template v-else-if="field.__config__.tag === 'el-rate'">
						<view class="rate-wrapper">
							<view 
								class="rate-star" 
								v-for="(star, starIndex) in (field.max || 5)" 
								:key="starIndex"
								@click="(e) => setRate(field, starIndex + 1, index)"
								:class="{ active: (formData[field.__vModel__] || 0) >= (starIndex + 1) }">
								★
							</view>
							<text class="rate-text" v-if="field['show-score']">{{ formData[field.__vModel__] || 0 }}分</text>
						</view>
					</template>
				</view>
			</view>
		</scroll-view>
		
		<!-- 提交按钮 -->
		<view v-if="caseDetail.periodNum!==0" class="submit-btn" @click="handleSubmit">提交</view>
	</view>
</template>

<script>
import { submitQuestionnaire, getQuestionnaireDetail} from '@/api/questionnaire'

export default {
		data() {
			return {
				top: 0,
				statusBarHeight: uni.getSystemInfoSync().statusBarHeight + 'px',
				questionnaireId: '',
				formTitle: '病例收集',
				formFields: [],
				formData: {},
				caseDetail: null ,// 保存详情数据，用于获取 company_id, table_name 等
			}
		},
	onLoad(options) {
		if (options.id) {
			this.questionnaireId = options.id
		}
		if (options.title) {
			this.formTitle = decodeURIComponent(options.title)
		}
		this.loadDetail()
	},
	onPageScroll(e) {
		this.top = e.scrollTop
	},
	computed: {
		bgColor() {
			const opacity = Math.min(this.top / 30, 1)
			return `rgba(255, 255, 255, ${opacity})`
		}
	},
	methods: {
		getFieldKey(field, index) {
			// 在非 H5 平台，:key 不支持表达式，需要使用方法来生成 key
			return field && field.__config__ && field.__config__.formId ? field.__config__.formId : `field_${index}`
		},
		goBack() {
			uni.navigateBack()
		},
		initFormData() {
			// 初始化表单数据
			this.formFields.forEach(field => {
				const vModel = field.__vModel__
				if (!vModel) {
					console.warn('字段缺少 __vModel__ 属性', field)
					return
				}
				
				// 如果字段已存在值，跳过初始化（保留已有数据）
				if (this.formData[vModel] !== undefined && this.formData[vModel] !== null) {
					return
				}
				
				const tag = field.__config__.tag
				const defaultValue = field.__config__.defaultValue
				
				// 根据字段类型设置默认值
				switch (tag) {
					// 单行文本输入
					case 'el-input':
						if (field.type === 'textarea') {
							// 多行文本
							this.$set(this.formData, vModel, defaultValue !== undefined ? defaultValue : '')
						} else {
							// 单行文本
							this.$set(this.formData, vModel, defaultValue !== undefined ? defaultValue : '')
						}
						break
					
					// 数字输入（计数器）
					case 'el-input-number':
						if (defaultValue !== undefined) {
							this.$set(this.formData, vModel, Number(defaultValue))
						} else {
							// 根据 min 值设置默认值，如果没有 min 则默认为 0
							const minValue = field.min !== undefined ? Number(field.min) : null
							this.$set(this.formData, vModel, minValue)
						}
						break
					
					// 下拉选择
					case 'el-select':
						this.$set(this.formData, vModel, defaultValue !== undefined ? defaultValue : '')
						break
					
					// 滑块
					case 'el-slider':
						if (defaultValue !== undefined) {
							this.$set(this.formData, vModel, Number(defaultValue))
						} else {
							// 默认值为 min 值，如果没有 min 则默认为 0
							const minValue = field.min !== undefined ? Number(field.min) : 0
							this.$set(this.formData, vModel, minValue)
						}
						break
					
					// 多选框组
					case 'el-checkbox-group':
						if (defaultValue !== undefined && Array.isArray(defaultValue)) {
							this.$set(this.formData, vModel, [...defaultValue])
						} else {
							this.$set(this.formData, vModel, [])
						}
						break
					
					// 单选框组
					case 'el-radio-group':
						this.$set(this.formData, vModel, defaultValue !== undefined ? defaultValue : '')
						break
					
					// 文件上传
					case 'el-upload':
						if (defaultValue !== undefined && Array.isArray(defaultValue)) {
							this.$set(this.formData, vModel, [...defaultValue])
						} else if (defaultValue !== undefined && typeof defaultValue === 'string') {
							// 如果是字符串（逗号分隔），转换为数组
							this.$set(this.formData, vModel, defaultValue.split(',').filter(item => item.trim()))
						} else {
							this.$set(this.formData, vModel, [])
						}
						break
					
					// 开关
					case 'el-switch':
						this.$set(this.formData, vModel, defaultValue !== undefined ? Boolean(defaultValue) : false)
						break
					
					// 时间选择
					case 'el-time-picker':
						if (field['is-range']) {
							// 时间范围
							if (defaultValue !== undefined && Array.isArray(defaultValue)) {
								this.$set(this.formData, vModel, [...defaultValue])
							} else {
								this.$set(this.formData, vModel, ['', ''])
							}
						} else {
							// 单个时间
							this.$set(this.formData, vModel, defaultValue !== undefined ? defaultValue : '')
						}
						break
					
					// 日期选择
					case 'el-date-picker':
						if (field.type === 'daterange') {
							// 日期范围
							if (defaultValue !== undefined && Array.isArray(defaultValue)) {
								this.$set(this.formData, vModel, [...defaultValue])
							} else {
								this.$set(this.formData, vModel, ['', ''])
							}
						} else {
							// 单个日期
							this.$set(this.formData, vModel, defaultValue !== undefined ? defaultValue : '')
						}
						break
					
					// 评分
					case 'el-rate':
						if (defaultValue !== undefined) {
							this.$set(this.formData, vModel, Number(defaultValue))
						} else {
							this.$set(this.formData, vModel, 0)
						}
						break
					
					// 默认情况：字符串类型
					default:
						this.$set(this.formData, vModel, defaultValue !== undefined ? defaultValue : '')
						break
				}
			})
		},
		async loadDetail() {
			try {
				uni.showLoading({ title: '加载中...' })
				const res = await getQuestionnaireDetail({ id: this.questionnaireId })
				uni.hideLoading()
				
				if (res.code === 200 && res.data) {
					// 保存详情数据
					this.caseDetail = res.data
					// 设置表单标题
					this.formTitle = res.data.questionnaireName || this.formTitle
					let question = res.data.surveyQuestionnaireVersion
					let formConfigData = question.formJson || ''
					// 如果 formConfigData 是字符串，需要解析 JSON
					if (typeof formConfigData === 'string') {
						try {
							formConfigData = JSON.parse(formConfigData)
						} catch (e) {
							console.error('解析表单配置 JSON 失败', e)
							formConfigData = null
						}
					}
					// 设置表单字段
					if (formConfigData && formConfigData.fields && Array.isArray(formConfigData.fields)) {
						this.formFields = formConfigData.fields
						this.initFormData()
					} else {
						// 接口返回的数据格式不正确，使用默认配置
						console.warn('表单配置格式不正确，使用默认配置', formConfigData)
							uni.showToast({
								icon: 'none',
								title: '表单配置加载失败'
							})
					}
					
					// 如果有已保存的数据，填充表单
					if (res.data.formData) {
						Object.assign(this.formData, res.data.formData)
					}
				} else {
					uni.showToast({
						icon: 'none',
						title: res.msg
					})
				}
			} catch (e) {
				uni.hideLoading()
				console.error('加载详情失败，使用默认配置', e)
				uni.showToast({
					icon: 'none',
					title: '表单配置加载失败'
				})
			}
		},
		getSelectOptions(field) {
			return field.__slot__?.options || []
		},
		getSelectIndex(field) {
			const value = this.formData[field.__vModel__]
			const options = this.getSelectOptions(field)
			const index = options.findIndex(opt => opt.value == value)
			return index >= 0 ? index : 0
		},
		getSelectLabel(field) {
			const value = this.formData[field.__vModel__]
			const options = this.getSelectOptions(field)
			const option = options.find(opt => opt.value == value)
			return option ? option.label : ''
		},
		onInputChange(field, e) {
			const value = e.detail.value || e.target.value || ''
			this.$set(this.formData, field.__vModel__, value)
		},
		onNumberInputChange(field, e) {
			const value = e.detail.value || e.target.value || ''
			const numValue = value === '' ? null : Number(value)
			// 如果输入的不是有效数字，保持原值
			if (value !== '' && isNaN(numValue)) {
				return
			}
			this.$set(this.formData, field.__vModel__, numValue)
		},
		onSelectChange(field, e) {
			const options = this.getSelectOptions(field)
			const index = e.detail.value
			if (options[index]) {
				this.$set(this.formData, field.__vModel__, options[index].value)
			}
		},
		onSliderChange(field, e) {
			this.$set(this.formData, field.__vModel__, e.detail.value)
		},
		onCheckboxChange(field, e) {
			this.$set(this.formData, field.__vModel__, e.detail.value)
		},
		onRadioChange(field, e) {
			this.$set(this.formData, field.__vModel__, e.detail.value)
		},
		isCheckboxChecked(field, value) {
			const checkedValues = this.formData[field.__vModel__] || []
			return checkedValues.includes(value)
		},
		getUploadFiles(field) {
			if (!field || !field.__vModel__) return []
			const files = this.formData[field.__vModel__] || []
			return Array.isArray(files) ? files : []
		},
		isImageFile(file) {
			if (typeof file === 'string') {
				return /\.(jpg|jpeg|png|gif|bmp|webp)$/i.test(file) || file.startsWith('data:image')
			}
			return false
		},
		getFileName(file) {
			if (typeof file === 'string') {
				const parts = file.split('/')
				return parts[parts.length - 1]
			}
			return '文件'
		},
		chooseUploadFile(field, formIndex) {
			// 如果 field 未定义，通过索引获取
			if (!field && formIndex !== undefined) {
				field = this.formFields[formIndex]
			}
			if (!field || !field.__vModel__) {
				console.error('上传字段未找到')
				return
			}
			const maxCount = field.multiple ? 9 : 3
			const currentFiles = this.getUploadFiles(field)
			const remaining = maxCount - currentFiles.length
			
			if (remaining <= 0) {
				uni.showToast({
					icon: 'none',
					title: '已达到最大上传数量'
				})
				return
			}
			
			const vm = this
			uni.chooseImage({
				//count: remaining,
				sizeType: ['compressed'],
				sourceType: ['album', 'camera'],
				success: (res) => {
					if (!res.tempFilePaths || res.tempFilePaths.length === 0) {
						uni.showToast({
							icon: 'none',
							title: '未选择文件'
						})
						return
					}
					
					uni.showLoading({ title: '上传中...' })
					const files = vm.formData[field.__vModel__] || []
					const requestPath = uni.getStorageSync('requestPath')
					const totalCount = res.tempFilePaths.length
					let completedCount = 0
					const uploadedUrls = []
					
					// 循环上传所有选择的图片
					res.tempFilePaths.forEach((filePath, index) => {
						uni.uploadFile({
							url: `${requestPath}/app/common/uploadOSS`,
							filePath: filePath,
							name: 'file',
							formData: {},
							success: (uploadRes) => {
								completedCount++
								try {
									const result = typeof uploadRes.data === 'string' ? JSON.parse(uploadRes.data) : uploadRes.data
									if (result.code == 200 && result.data && result.data.url) {
										uploadedUrls.push(result.data.url)
									} else if (result.code == 200 && result.url) {
										// 兼容不同的返回格式
										uploadedUrls.push(result.url)
									}
								} catch (e) {
									console.error('解析上传结果失败', e)
								}
								
								// 所有文件上传完成后，更新表单数据
								if (completedCount === totalCount) {
									uni.hideLoading()
									if (uploadedUrls.length > 0) {
										vm.$set(vm.formData, field.__vModel__, [...files, ...uploadedUrls])
										uni.showToast({
											icon: 'success',
											title: uploadedUrls.length === totalCount ? '上传成功' : `成功上传${uploadedUrls.length}/${totalCount}个文件`
										})
									} else {
										uni.showToast({
											icon: 'none',
											title: '上传失败'
										})
									}
								}
							},
							fail: (err) => {
								completedCount++
								console.error('上传失败', err)
								// 所有文件上传完成后，更新表单数据
								if (completedCount === totalCount) {
									uni.hideLoading()
									if (uploadedUrls.length > 0) {
										vm.$set(vm.formData, field.__vModel__, [...files, ...uploadedUrls])
										uni.showToast({
											icon: 'none',
											title: `成功上传${uploadedUrls.length}/${totalCount}个文件`
										})
									} else {
										uni.showToast({
											icon: 'none',
											title: '上传失败'
										})
									}
								}
							}
						})
					})
				},
				fail: (err) => {
					console.error('选择文件失败', err)
					uni.showToast({
						icon: 'none',
						title: '选择文件失败'
					})
				}
			})
		},
		removeUploadFile(field, fileIndex, formIndex) {
			// 如果 field 未定义，通过索引获取
			if (!field && formIndex !== undefined) {
				field = this.formFields[formIndex]
			}
			if (!field || !field.__vModel__) {
				console.error('上传字段未找到')
				return
			}
			const files = this.formData[field.__vModel__] || []
			if (fileIndex >= 0 && fileIndex < files.length) {
				files.splice(fileIndex, 1)
				this.$set(this.formData, field.__vModel__, files)
			}
		},
		// 计数器相关方法
		decreaseNumber(field, index) {
			// 如果 field 未定义，通过索引获取
			if (!field && index !== undefined) {
				field = this.formFields[index]
			}
			if (!field || !field.__vModel__) {
				console.error('计数器字段未找到')
				return
			}
			if (this.isNumberMin(field)) return
			const current = Number(this.formData[field.__vModel__] || 0)
			const step = field.step || 1
			const min = field.min !== undefined ? field.min : 0
			const newValue = Math.max(min, current - step)
			this.$set(this.formData, field.__vModel__, newValue)
		},
		increaseNumber(field, index) {
			// 如果 field 未定义，通过索引获取
			if (!field && index !== undefined) {
				field = this.formFields[index]
			}
			if (!field || !field.__vModel__) {
				console.error('计数器字段未找到')
				return
			}
			if (this.isNumberMax(field)) return
			const current = Number(this.formData[field.__vModel__] || 0)
			const step = field.step || 1
			const max = field.max !== undefined ? field.max : Infinity
			const newValue = Math.min(max, current + step)
			this.$set(this.formData, field.__vModel__, newValue)
		},
		isNumberMin(field) {
			if (!field || !field.__vModel__) return false
			const current = Number(this.formData[field.__vModel__] || 0)
			const min = field.min !== undefined ? field.min : 0
			return current <= min
		},
		isNumberMax(field) {
			if (!field || !field.__vModel__) return false
			const current = Number(this.formData[field.__vModel__] || 0)
			const max = field.max !== undefined ? field.max : Infinity
			return current >= max
		},
		// 开关相关方法
		onSwitchChange(field, e) {
			this.$set(this.formData, field.__vModel__, e.detail.value)
		},
		// 时间选择相关方法
		onTimePickerChange(field, e) {
			this.$set(this.formData, field.__vModel__, e.detail.value)
		},
		getTimeRangeStart(field) {
			const value = this.formData[field.__vModel__]
			if (Array.isArray(value) && value.length > 0) {
				return value[0]
			}
			return ''
		},
		getTimeRangeEnd(field) {
			const value = this.formData[field.__vModel__]
			if (Array.isArray(value) && value.length > 1) {
				return value[1]
			}
			return ''
		},
		onTimeRangeStartChange(field, e) {
			const value = this.formData[field.__vModel__] || []
			value[0] = e.detail.value
			this.$set(this.formData, field.__vModel__, [...value])
		},
		onTimeRangeEndChange(field, e) {
			const value = this.formData[field.__vModel__] || []
			value[1] = e.detail.value
			this.$set(this.formData, field.__vModel__, [...value])
		},
		// 日期选择相关方法
		onDatePickerChange(field, e) {
			this.$set(this.formData, field.__vModel__, e.detail.value)
		},
		getDateRangeStart(field) {
			const value = this.formData[field.__vModel__]
			if (Array.isArray(value) && value.length > 0) {
				return value[0]
			}
			return ''
		},
		getDateRangeEnd(field) {
			const value = this.formData[field.__vModel__]
			if (Array.isArray(value) && value.length > 1) {
				return value[1]
			}
			return ''
		},
		onDateRangeStartChange(field, e) {
			const value = this.formData[field.__vModel__] || []
			value[0] = e.detail.value
			this.$set(this.formData, field.__vModel__, [...value])
		},
		onDateRangeEndChange(field, e) {
			const value = this.formData[field.__vModel__] || []
			value[1] = e.detail.value
			this.$set(this.formData, field.__vModel__, [...value])
		},
		// 评分相关方法
		setRate(field, value, formIndex) {
			// 如果 field 未定义，通过索引获取
			if (!field && formIndex !== undefined) {
				field = this.formFields[formIndex]
			}
			if (!field || !field.__vModel__) {
				console.error('评分字段未找到')
				return
			}
			if (field.disabled) return
			this.$set(this.formData, field.__vModel__, value)
		},
		validateForm() {
			for (let field of this.formFields) {
			const value = this.formData[field.__vModel__]
			const fieldLabel = field.__config__.label || '该字段'
			const tag = field.__config__.tag
			const isRequired = field.__config__.required
			
			// 必填校验
				if (isRequired) {
					// 数组类型（多选框、文件上传、范围选择）
					if (tag === 'el-checkbox-group' || tag === 'el-upload') {
						const arr = tag === 'el-upload' ? this.getUploadFiles(field) : value
						if (!arr || !Array.isArray(arr) || arr.length === 0) {
							return { valid: false, message: tag === 'el-upload' ? `请上传${fieldLabel}` : `请选择${fieldLabel}` }
						}
					}
					// 范围选择（时间范围、日期范围）
					else if ((tag === 'el-time-picker' && field['is-range']) || (tag === 'el-date-picker' && field.type === 'daterange')) {
						const range = value || []
						if (!Array.isArray(range) || range.length < 2 || !range[0] || !range[1]) {
							return { valid: false, message: `请选择${fieldLabel}` }
						}
					}
					// 选择类型（下拉、单选框、时间、日期）
					else if (tag === 'el-select' || tag === 'el-radio-group' || 
					         (tag === 'el-time-picker' && !field['is-range']) || 
					         (tag === 'el-date-picker' && field.type !== 'daterange')) {
						if (!value && value !== 0 && value !== '0' && value !== false) {
							return { valid: false, message: `请选择${fieldLabel}` }
						}
					}
					// 文本输入
					else if (tag === 'el-input') {
						if (!value || (typeof value === 'string' && value.trim() === '')) {
							return { valid: false, message: `请输入${fieldLabel}` }
						}
					}
					// 数字类型（数字输入、滑块）
					else if (tag === 'el-input-number' || tag === 'el-slider') {
						if (value === null || value === undefined || value === '') {
							return { valid: false, message: tag === 'el-slider' ? `请设置${fieldLabel}` : `请输入${fieldLabel}` }
						}
					}
					// 评分
					else if (tag === 'el-rate') {
						if (!value || value === 0) {
							return { valid: false, message: `请为${fieldLabel}评分` }
						}
					}
					// 其他类型
					else if (!value && value !== 0 && value !== false) {
						return { valid: false, message: `请填写${fieldLabel}` }
					}
				}
				
				// 格式校验（必填和非必填都校验）
				if (value !== null && value !== undefined && value !== '') {
					// 文本长度校验
					if (tag === 'el-input' && typeof value === 'string') {
						if (field.maxlength && value.length > field.maxlength) {
							return { valid: false, message: `${fieldLabel}不能超过${field.maxlength}个字符` }
						}
						if (field.minlength && value.length < field.minlength) {
							return { valid: false, message: `${fieldLabel}不能少于${field.minlength}个字符` }
						}
					}
					// 数字范围校验
					else if ((tag === 'el-input-number' || tag === 'el-slider')) {
						const numValue = Number(value)
						if (!isNaN(numValue)) {
							if (field.min !== undefined && numValue < field.min) {
								return { valid: false, message: `${fieldLabel}不能小于${field.min}` }
							}
							if (field.max !== undefined && numValue > field.max) {
								return { valid: false, message: `${fieldLabel}不能大于${field.max}` }
							}
						}
					}
				}
			}
			return { valid: true }
		},
		async handleSubmit() {
			// 表单验证
			const validation = this.validateForm()
			if (!validation.valid) {
				uni.showToast({
					icon: 'none',
					title: validation.message
				})
				return
			}
			
			try {
				uni.showLoading({ title: '提交中...' })
				// 处理表单数据：将数组类型字段转换为逗号分隔的字符串
				const submitData = { ...this.formData }
				this.formFields.forEach(field => {
					const vModel = field.__vModel__
					const value = submitData[vModel]
					
					// 文件上传字段：数组转逗号分隔字符串
					if (field.__config__.tag === 'el-upload') {
						if (Array.isArray(value) && value.length > 0) {
							submitData[vModel] = value.join(',')
						} else if (value) {
							// 如果已经是字符串，保持不变
							submitData[vModel] = value
						} else {
							// 如果没有文件，设置为空字符串
							submitData[vModel] = ''
						}
					}
					// 多选框组：数组转逗号分隔字符串
					else if (field.__config__.tag === 'el-checkbox-group') {
						if (Array.isArray(value) && value.length > 0) {
							submitData[vModel] = value.join(',')
						} else if (value) {
							// 如果已经是字符串，保持不变
							submitData[vModel] = value
						} else {
							// 如果没有选择，设置为空字符串
							submitData[vModel] = ''
						}
					}
				})
				
				// 获取用户信息
				const userInfo = JSON.parse(uni.getStorageSync('userInfo') || '{}')
				const userName = userInfo.doctorName|| ''
				
				// 获取详情数据中的信息
				const companyId = this.caseDetail?.companyId
				const periodNum = this.caseDetail?.periodNum
				const tableName = this.caseDetail?.surveyQuestionnaireVersion.tableName || ''
				const version = this.caseDetail?.surveyQuestionnaireVersion.versionNo || 0
				// 添加公用字段
				submitData.company_id = Number(companyId) || 0
				submitData.table_name = tableName
				submitData.user_id = userInfo.id || 0
				submitData.user_name = userName
				submitData.version_id = Number(version) || 0
				submitData.periodNum = periodNum
				const res = await submitQuestionnaire(submitData)
				uni.hideLoading()
				if (res.code === 200) {
					uni.showToast({
						icon: 'success',
						title: '提交成功'
					})
					setTimeout(() => {
						uni.navigateBack()
					}, 1500)
				} else {
					uni.showToast({
						icon: 'none',
						title: res.msg || '提交失败'
					})
				}
			} catch (e) {
				uni.hideLoading()
				uni.showToast({
					icon: 'none',
					title: '提交失败'
				})
			}
		}
	}
}
</script>

<style lang="stylus">
.text-placeholder {
	color: #C8C9CC !important;
}

checkbox .wx-checkbox-input {
	border-radius: 0 !important;
}

checkbox .wx-checkbox-input.wx-checkbox-input-checked {
	border-radius: 0 !important;
}
</style>

<style lang="scss" scoped>
.container {
	min-height: 100vh;
	display: flex;
	flex-direction: column;
	
	.bg {
		width: 100%;
		position: absolute;
		top: 0;
		left: 0;
	}
}

.status-bar {
	width: 100%;
	background: transparent;
}

.fixed-top-box {
	width: 100%;
	position: fixed;
	top: 0;
	left: 0;
	z-index: 1000;
	
	.back-box {
		height: 88upx;
		padding: 0 24upx;
		display: flex;
		align-items: center;
		justify-content: space-between;
		
		image {
			width: 40upx;
			height: 40upx;
		}
		
		.title {
			font-family: PingFang SC, PingFang SC;
			font-weight: 600;
			font-size: 36rpx;
			color: #333333;
		}
	}
}

.content {
	margin-top: 168rpx;
	flex: 1;
	padding: 24rpx;
	box-sizing: border-box;
}

.form-header {
	margin-bottom: 32rpx;
	
	.form-title {
		font-family: PingFang SC, PingFang SC;
		font-weight: 600;
		font-size: 40rpx;
		color: #333333;
		margin-bottom: 32rpx;
		text-align: center;
	}
	
	.form-tips {
		.tip-item {
			font-family: PingFang SC, PingFang SC;
			font-weight: 400;
			font-size: 28rpx;
			color: #666666;
			line-height: 44rpx;
			text-align: center;
		}
	}
}

.form-section {
	padding-bottom: 160rpx;
}

.form-item {
	background: #fff;
	padding: 24rpx 32rpx;
	margin-bottom: 20rpx;
	border-radius: 16rpx;
	
	&:last-child {
		margin-bottom: 0;
	}
	
	.form-label {
		display: flex;
		align-items: center;
		font-size: 28rpx;
		color: #333;
		margin-bottom: 16rpx;
		
		.required {
			color: #FF5030;
			margin-right: 4rpx;
		}
	}
	
	.form-input {
		width: 100%;
		height: 72rpx;
		padding: 0 24rpx;
		border-radius: 12rpx;
		border: 2rpx solid #F5F5F5;
		font-size: 28rpx;
		color: #333;
		box-sizing: border-box;
		
		&.placeholder {
			color: #C8C9CC;
		}
		
		&.picker-input {
			display: flex;
			align-items: center;
			justify-content: space-between;
		}
	}
	
	.slider-wrapper {
		padding: 20rpx 0;
	}
	
	.radio-group,
	.checkbox-group {
		display: flex;
		flex-direction: column;
		gap: 48rpx;
		
		.radio-item,
		.checkbox-item {
			display: flex;
			align-items: center;
			gap: 16rpx;
			font-size: 28rpx;
			color: #333;
		}
	}
	
	.form-textarea {
		width: 100%;
		min-height: 200rpx;
		padding: 24rpx;
		border-radius: 12rpx;
		border: 2rpx solid #F5F5F5;
		font-size: 28rpx;
		color: #333;
		box-sizing: border-box;
		line-height: 1.6;
	}
	
	.input-number-wrapper {
		display: flex;
		align-items: center;
		gap: 16rpx;
		
		.input-number-btn {
			width: 60rpx;
			height: 60rpx;
			display: flex;
			align-items: center;
			justify-content: center;
			border: 2rpx solid #F5F5F5;
			border-radius: 8rpx;
			font-size: 32rpx;
			color: #333;
			background: #fff;
			
			&.disabled {
				opacity: 0.5;
				color: #C8C9CC;
			}
		}
		
		.input-number-input {
			flex: 1;
		}
	}
	
	.time-range-wrapper,
	.date-range-wrapper {
		display: flex;
		align-items: center;
		gap: 16rpx;
		
		.time-range-input,
		.date-range-input {
			flex: 1;
		}
		
		.time-range-separator,
		.date-range-separator {
			font-size: 28rpx;
			color: #666;
		}
	}
	
	.rate-wrapper {
		display: flex;
		align-items: center;
		gap: 16rpx;
		
		.rate-star {
			font-size: 48rpx;
			color: #E0E0E0;
			line-height: 1;
			cursor: pointer;
			
			&.active {
				color: #FFD700;
			}
		}
		
		.rate-text {
			font-size: 28rpx;
			color: #666;
		}
	}
	
	.upload-section {
		display: flex;
		gap: 16rpx;
		flex-wrap: wrap;
		padding: 10rpx;
		width: 100%;
		.upload-item {
			flex: 0 0 calc((100% - 32rpx) / 3);
			width: calc((100% - 32rpx) / 3);
			// height: calc((100% - 32rpx) / 3);
			min-height: 200rpx;
			border-radius: 8rpx;
			overflow: hidden;
			position: relative;
			box-sizing: border-box;
			.uploaded-image {
				width: 100%;
				height: 100%;
			}
			
			.uploaded-file {
				width: 100%;
				height: 100%;
				background: #f5f5f5;
				display: flex;
				align-items: center;
				justify-content: center;
				padding: 16rpx;
				box-sizing: border-box;
				
				.file-name {
					font-size: 24rpx;
					color: #666;
					text-align: center;
					word-break: break-all;
				}
			}
			
			.delete-btn {
				position: absolute;
				top: 0;
				right:0;
				width: 40rpx;
				height: 40rpx;
				background: rgba(0, 0, 0, 0.5);
				border-radius: 50%;
				display: flex;
				align-items: center;
				justify-content: center;
				font-size: 32rpx;
				color: #fff;
				line-height: 1;
			}
			
			&.upload-placeholder {
				background: #f5f5f5;
				display: flex;
				flex-direction: column;
				align-items: center;
				justify-content: center;
				gap: 8rpx;
				
				.upload-text {
					font-size: 24rpx;
					color: #999;
				}
			}
		}
	}
}

.submit-btn {
	position: fixed;
	bottom: 0;
	left: 0;
	right: 0;
	height: 88rpx;
	background: #388BFF;
	border-radius: 200rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	font-size: 32rpx;
	color: #fff;
	font-weight: 500;
	z-index: 100;
	margin: 40rpx 32rpx;
}
</style>
