<template>
	<view class="container">
		<scroll-view class="content" scroll-y>
			<!-- 驳回意见提示 -->
			<view class="rejection-banner" v-if="rejectionInfo">
				<view class="rejection-icon">✕</view>
				<view class="rejection-text">驳回意见: {{ rejectionInfo }}</view>
			</view>

			<!-- 基本信息 -->
			<view class="form-section">
				<view class="form-item">
					<view class="form-label">
						<text class="required">*</text>
						<text>学术头衔</text>
					</view>
					<view class="form-input picker-input" :class="{ placeholder: !formData.academicTitle }"
						@click="showPicker('学术头衔', 'doctor_academic_title')">
						{{ formData.academicTitle || '请选择' }}
						<image class="icon" src="https://ysrw-1395926010.cos.ap-chengdu.myqcloud.com/image/icon_more.png"></image>
					</view>
				</view>

				<view class="form-item">
					<view class="form-label">
						<text class="required">*</text>
						<text>学术任职（多选）</text>
					</view>
					<view class="form-input picker-input" :class="{ placeholder: !formData.academicPositions }"
						@click="showPicker('学术任职', 'doctor_academic_position')">
						{{ formData.academicPositions || '请选择' }}
						<image class="icon" src="https://ysrw-1395926010.cos.ap-chengdu.myqcloud.com/image/icon_more.png"></image>
					</view>
				</view>
				<view class="form-item">
					<view class="form-label">
						<text class="required">*</text>
						<text>国际性期刊论文/著作数</text>
					</view>
					<input type="number" class="input" v-model="formData.internationalPapers"></input>
				</view>
				<view class="form-item">
					<view class="form-label">
						<text class="required">*</text>
						<text>全国性期刊论文/著作数</text>
					</view>
					<input type="number" class="input" v-model="formData.nationalPapers"></input>
				</view>
				<view class="form-item">
					<view class="form-label">
						<text class="required">*</text>
						<text>学术研究（多选）</text>
					</view>
					<view class="form-input picker-input" :class="{ placeholder: !formData.researchAreas }"
						@click="showPicker('学术研究', 'doctor_research_area')">
						{{ formData.researchAreas || '请选择' }}
						<image class="icon" src="https://ysrw-1395926010.cos.ap-chengdu.myqcloud.com/image/icon_more.png"></image>
					</view>
				</view>
				<view class="form-item">
					<view class="form-label">
						<text class="required">*</text>
						<text>临床工作经验年数</text>
					</view>
					<input type="number" class="input" v-model="formData.clinicalExperience"></input>
				</view>
				<view class="form-item">
					<view class="form-label">
						<text class="required">*</text>
						<text>学位</text>
					</view>
					<view class="form-input picker-input" :class="{ placeholder: !formData.degree }"
						@click="showPicker('学位', 'doctor_degree')">
						{{ formData.degree || '请选择' }}
						<image class="icon" src="https://ysrw-1395926010.cos.ap-chengdu.myqcloud.com/image/icon_more.png"></image>
					</view>
				</view>
				<view class="form-item">
					<view class="form-label">
						<text class="required">*</text>
						<text>申请级别</text>
					</view>
					<view class="form-input picker-input" :class="{ placeholder: !formData.applicationLevel }"
						@click="showPicker('申请级别', 'doctor_apply_level')">
						{{ formData.applicationLevel || '请选择' }}
						<image class="icon" src="https://ysrw-1395926010.cos.ap-chengdu.myqcloud.com/image/icon_more.png"></image>
					</view>
				</view>

				<view class="form-item column">
					<view class="form-label">
						<text class="required">*</text>
						<text>证明材料</text>
					</view>
					<view class="form-tips">如医院官网简介、论文截图、聘书等</view>
					<view class="upload-proof" @click="chooseProofImages">
						<view v-if="formData.proofImages && formData.proofImages.length > 0" class="uploaded-images">
							<view v-for="(image, index) in formData.proofImages" :key="index"
								class="uploaded-image-item">
								<image :src="image" mode="aspectFill"></image>
								<view class="image-delete" @click.stop="deleteProofImage(index)">×</view>
							</view>
							<view class="upload-placeholder">
								<image src="https://ysrw-1395926010.cos.ap-chengdu.myqcloud.com/image/icon_camera.png" mode="aspectFill"></image>
							</view>
						</view>
						<view v-else class="upload-placeholder">
							<image src="https://ysrw-1395926010.cos.ap-chengdu.myqcloud.com/image/icon_camera.png" mode="aspectFill"></image>
						</view>
					</view>
				</view>
			</view>
		</scroll-view>
		<view class="next-button" @click="submitForm">提交</view>
		<u-picker v-if="showPickerVisible" :title='pickerTitle' :show="true" confirmColor='#576B95' ref="uPicker"
			:columns="pickerData" @confirm="confirm" @cancel="cancel">
		</u-picker>

		<!-- 多选弹窗 -->
		<u-popup :show="showMultiSelectPopup" mode="bottom" round="20rpx" :closeable="false">
			<view class="u-popup-content">
				<view class="popup-header">
					<text class="popup-title">{{ multiSelectTitle }}</text>
					<text class="popup-close" @click="closeMultiSelectPopup">×</text>
				</view>
				<view class="popup-body">
					<view class="tag-group">
						<view v-for="(item, index) in multiSelectData" :key="index" class="tag-item"
							:class="{ active: selectedItems.includes(item) }" @click="toggleItem(item)">
							{{ item }}
						</view>
					</view>
				</view>
				<view class="popup-footer">
					<view class="popup-btn cancel-btn" @click="closeMultiSelectPopup">取消</view>
					<view class="popup-btn confirm-btn" @click="confirmMultiSelect">确定</view>
				</view>
			</view>
		</u-popup>

	</view>
</template>

<script>
	import utils from '@/utils/common.js'

	import {
		apply
	} from '@/api/speaker';
	export default {
		data() {
			return {
				academicTitle: [], //学术头衔
				academicPosition: [], //学术任职
				academicResearch: [], //学术研究
				degree: [], //学位
				applyLevel: [], //申请级别


				showPickerVisible: false,
				pickerData: [],
				pickerTitle: '',
				// 多选相关
				showMultiSelectPopup: false,
				multiSelectTitle: '',
				multiSelectData: [],
				selectedItems: [],
				currentMultiSelectType: '',
				// 申请级别选项
				applicationLevelColumns: [
					['一级', '二级', '三级', '四级']
				],
				rejectionInfo: '',
				formData: {
					// 学术信息
					academicTitle: '', // 学术头衔
					academicPositions: '', // 学术任职
					internationalPapers: 0, // 国际性期刊论文/著作数
					nationalPapers: 0, // 全国性期刊论文/著作数
					researchAreas: '', // 学术研究
					clinicalExperience: 0, // 临床工作经验年数
					degree: '', // 学位
					applicationLevel: '', // 申请级别
					proofImages: [] // 证明材料图片
				},
				pickerTitle: '默认标题',
				pickerData: [],
				userInfo: {},
				doctorId: null
			}
		},
		onLoad: async function(options) {
			try {
				console.log("options", options)
				this.doctorId = options.doctorId;
				this.academicTitle = await utils.getDicts("doctor_academic_title"); //学术头衔
				this.academicPosition = await utils.getDicts("doctor_academic_position"); //学术任职
				this.academicResearch = await utils.getDicts("doctor_academic_research"); //学术研究
				this.degree = await utils.getDicts("doctor_degree"); //学位
				this.applyLevel = await utils.getDicts("doctor_apply_level"); //申请级别
			} catch (e) {
				console.log('获取字典数据失败:', e)
			}


			if (options.rejectionInfo) {
				this.rejectionInfo = decodeURIComponent(options.rejectionInfo)
			}
			// 获取用户信息
			this.userInfo = uni.getStorageSync('userInfo') || '{}'
		},
		methods: {
			// 选择证明材料图片
			chooseProofImages() {
				uni.chooseImage({
					count: 9, // 最多选择9张
					sizeType: ['compressed'],
					sourceType: ['album', 'camera'],
					success: (res) => {
						// 上传图片
						this.uploadImages(res.tempFilePaths)
					}
				})
			},
			// 上传图片
			async uploadImages(tempFilePaths) {
				try {
					uni.showLoading({
						title: '上传中...'
					})
					const uploadedImages = []
					// 从storage获取动态域名
					const baseUrl = uni.getStorageSync('requestPath')
					// 逐个上传图片
					for (const tempFilePath of tempFilePaths) {
						// 使用uni.uploadFile上传图片
						const uploadRes = await new Promise((resolve, reject) => {
							uni.uploadFile({
								url: `${baseUrl}/system/file/upload`,
								filePath: tempFilePath,
								name: 'file',
								formData: {
									bizType: 'DOCTOR_APPLY'
								},
								header: {
									'AppToken': uni.getStorageSync('AppToken')
								},
								success: (res) => {
									// 解析上传结果
									const data = JSON.parse(res.data)
									if (data.code === 200) {
										console.log('上传成功:', data.data)
										resolve(data.data)
									} else {
										reject(new Error(data.message || '上传失败'))
									}
								},
								fail: (err) => {
									reject(err)
								}
							})
						})
						// 将上传成功的图片路径添加到数组
						uploadedImages.push(uploadRes.fileUrl)
					}
					// 更新表单数据
					this.formData.proofImages = [...this.formData.proofImages, ...uploadedImages]
					uni.hideLoading()
					uni.showToast({
						icon: 'success',
						title: '上传成功'
					})
				} catch (e) {
					uni.hideLoading()
					uni.showToast({
						icon: 'none',
						title: '上传失败'
					})
				}
			},

			// 删除证明材料图片
			deleteProofImage(index) {
				this.formData.proofImages.splice(index, 1)
			},

			// 显示选择器
			showPicker(title, type) {
				// 处理多选情况
				if (type === 'doctor_academic_position' || type === 'doctor_research_area') {
					// 获取数据
					let dictData = []
					if (type === 'doctor_academic_position') {
						dictData = this.academicPosition.map(item => item.dictLabel)
					} else if (type === 'doctor_research_area') {
						dictData = this.academicResearch.map(item => item.dictLabel)
					}

					// 设置多选数据
					this.multiSelectData = dictData
					this.multiSelectTitle = title
					this.currentMultiSelectType = type

					// 初始化已选项
					if (type === 'doctor_academic_position') {
						this.selectedItems = this.formData.academicPositions ? this.formData.academicPositions.split(',') :
							[]
					} else if (type === 'doctor_research_area') {
						this.selectedItems = this.formData.researchAreas ? this.formData.researchAreas.split(',') : []
					}

					// 显示多选弹窗
					this.showMultiSelectPopup = true
				} else {
					// 单选情况，保持原有逻辑
					// 先隐藏选择器，确保下次显示时重新创建
					this.showPickerVisible = false

					// 根据字典类型获取对应的数据
					let dictData = []
					if (type === 'doctor_academic_title') {
						dictData = this.academicTitle.map(item => item.dictLabel)
					} else if (type === 'doctor_degree') {
						dictData = this.degree.map(item => item.dictLabel)
					} else if (type === 'doctor_apply_level') {
						dictData = this.applyLevel.map(item => item.dictLabel)
					}

					// 设置数据
					this.pickerData = [dictData]
					this.pickerTitle = title

					// 延迟显示选择器，确保数据已更新
					setTimeout(() => {
						this.showPickerVisible = true
					}, 50)
				}
			},

			// 选择器确认
			confirm(e) {
				if (e.value && e.value.length > 0) {
					if (this.pickerTitle === '学术头衔') {
						this.formData.academicTitle = e.value[0]
					} else if (this.pickerTitle === '学术任职') {
						this.formData.academicPositions = e.value[0]
					} else if (this.pickerTitle === '学术研究') {
						this.formData.researchAreas = e.value[0]
					} else if (this.pickerTitle === '学位') {
						this.formData.degree = e.value[0]
					} else if (this.pickerTitle === '申请级别') {
						this.formData.applicationLevel = e.value[0]
					}
				}
				// 关闭选择器
				this.showPickerVisible = false
			},

			// 选择器取消
			cancel() {
				// 关闭选择器
				this.showPickerVisible = false
			},

			// 多选相关方法
			// 切换选项
			toggleItem(item) {
				const index = this.selectedItems.indexOf(item)
				if (index > -1) {
					// 取消选择
					this.selectedItems.splice(index, 1)
				} else {
					// 添加选择
					this.selectedItems.push(item)
				}
			},

			// 关闭多选弹窗
			closeMultiSelectPopup() {
				this.showMultiSelectPopup = false
			},

			// 确认多选结果
			confirmMultiSelect() {
				const selectedValues = this.selectedItems.join(',')

				if (this.currentMultiSelectType === 'doctor_academic_position') {
					this.formData.academicPositions = selectedValues
				} else if (this.currentMultiSelectType === 'doctor_research_area') {
					this.formData.researchAreas = selectedValues
				}

				this.showMultiSelectPopup = false
			},

			// 提交表单
			submitForm() {
				// 验证表单数据
				if (!this.formData.academicTitle) {
					uni.showToast({
						icon: 'none',
						title: '请选择学术头衔'
					})
					return
				}
				if (!this.formData.degree) {
					uni.showToast({
						icon: 'none',
						title: '请选择学位'
					})
					return
				}
				if (!this.formData.applicationLevel) {
					uni.showToast({
						icon: 'none',
						title: '请选择申请级别'
					})
					return
				}
				if (this.formData.proofImages.length === 0) {
					uni.showToast({
						icon: 'none',
						title: '请上传证明材料'
					})
					return
				}

				// 构建表单数据
				const formData = {
					// 基础字段
					id: 0,
					doctorId: this.doctorId || '',
					companyId: this.userInfo.companyId || 0,
					companyName: this.userInfo.companyName || '',
					// 学术信息
					academicTitle: this.formData.academicTitle,
					academicPosition: this.formData.academicPositions,
					internationalPapers: parseInt(this.formData.internationalPapers) || 0,
					nationalPapers: parseInt(this.formData.nationalPapers) || 0,
					academicResearch: this.formData.researchAreas,
					clinicalExperienceYears: parseInt(this.formData.clinicalExperience) || 0,
					degree: this.formData.degree,
					applyLevel: this.formData.applicationLevel,
					// 状态字段
					status: 0,
					deleted: 0,
					auditInstanceId: 0,
					// 证明材料
					materials: this.formData.proofImages.map((url, index) => {
						return {
							id: 0,
							companyId: this.userInfo.companyId || 0,
							applyId: 0,
							fileUrl: url,
							fileName: `proof_${index + 1}.jpg`,
							fileSize: 0,
							fileType: 'image/jpeg',
							sortOrder: index + 1,
							deleted: 0
						}
					})
				}

				// 调用apply接口提交表单
				uni.showLoading({
					title: '提交中...'
				})
				apply(formData).then(res => {
					uni.hideLoading()
					if (res.code === 200) {
						uni.showToast({
							icon: 'success',
							title: '提交成功'
						})
						uni.redirectTo({
							url: '/pages_task/success'
						})
						// 提交成功后返回上一页
						// setTimeout(() => {
						// 	uni.navigateBack()
						// }, 1500)
					} else {
						uni.showToast({
							icon: 'none',
							title: res.message || '提交失败'
						})
					}
				}).catch(err => {
					uni.hideLoading()
					uni.showToast({
						icon: 'none',
						title: '网络错误，请重试'
					})
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
	.container {
		min-height: 100vh;
		background: #ffffff;
		display: flex;
		flex-direction: column;
		position: relative;

		.content {
			flex: 1;
			box-sizing: border-box;

			.rejection-banner {
				display: flex;
				align-items: center;
				padding: 24rpx;
				background: #FF5030;
				color: #fff;
				margin: 24rpx;
				border-radius: 8rpx;

				.rejection-icon {
					width: 40rpx;
					height: 40rpx;
					border-radius: 50%;
					background: rgba(255, 255, 255, 0.3);
					display: flex;
					align-items: center;
					justify-content: center;
					font-size: 24rpx;
					margin-right: 16rpx;
				}

				.rejection-text {
					flex: 1;
					font-size: 28rpx;
					line-height: 1.5;
				}
			}

			.form-section {
				background: #fff;
				margin: 20rpx;
				border-radius: 16rpx;
				padding: 32rpx;

				.form-item {
					display: flex;
					justify-content: space-between;
					align-items: center;
					border-bottom: 1px solid #EBEDF0;
					padding: 30rpx 0;

					&:last-child {
						border-bottom: 0;
					}

					&.column {
						display: flex;
						flex-direction: column;
						justify-content: baseline;
						align-items: baseline;
					}

					.input {
						text-align: end;
						font-size: 28rpx;
						color: #C8C9CC;
					}

					.form-label {
						display: flex;
						align-items: center;
						font-size: 28rpx;
						color: #333;

						.required {
							color: #CF3546;
							margin-right: 4rpx;
						}
					}

					.form-tips {
						font-size: 24rpx;
						color: #999999;
						margin: 12rpx 0 24rpx;
					}

					.upload-proof {
						margin-top: 16rpx;

						.uploaded-images {
							display: flex;
							flex-wrap: wrap;
							gap: 20rpx;

							.uploaded-image-item {
								width: 160rpx;
								height: 160rpx;
								border-radius: 16rpx;
								position: relative;

								image {
									width: 100%;
									height: 100%;
									border-radius: 12rpx;
								}

								.image-delete {
									position: absolute;
									top: -12rpx;
									right: -12rpx;
									width: 40rpx;
									height: 40rpx;
									background: rgba(0, 0, 0, 0.6);
									color: #FFFFFF;
									border-radius: 50%;
									display: flex;
									align-items: center;
									justify-content: center;
									font-size: 32rpx;
									font-weight: bold;
									z-index: 1;
								}
							}


						}

						.upload-placeholder {
							width: 160rpx;
							height: 160rpx;
							background: #F7F8FA;
							border-radius: 16rpx;
							display: flex;
							flex-direction: column;
							align-items: center;
							justify-content: center;

							image {
								width: 48rpx;
								height: 48rpx;
							}

							.camera-icon {
								font-size: 48rpx;
								color: #CCCCCC;
								margin-bottom: 16rpx;
							}

							.upload-text {
								font-size: 24rpx;
								color: #999999;
							}
						}
					}

					.txt {
						font-size: 28rpx;
						color: #333333;
					}

					.form-input {
						flex: 1;
						font-size: 28rpx;
						color: #C8C9CC;

						&.placeholder {
							color: #C8C9CC;
						}

						&.picker-input {
							display: flex;
							align-items: center;
							justify-content: flex-end;
						}

						.icon {
							width: 36rpx;
							height: 36rpx;
						}
					}
				}
			}
		}

		.next-button {
			text-align: center;
			font-size: 32rpx;
			color: #FFFFFF;
			height: 88rpx;
			line-height: 88rpx;
			background: #388BFF;
			border-radius: 200rpx;
			margin: 32rpx;
		}

		/* 多选弹窗样式 */
		.u-popup-content {
			background: #fff;
			border-radius: 20rpx 20rpx 0 0;
			max-height: 80vh;
			display: flex;
			flex-direction: column;
			width: 100%;
		}

		.popup-header {
			display: flex;
			justify-content: space-between;
			align-items: center;
			padding: 32rpx;
			border-bottom: 1px solid #EBEDF0;
		}

		.popup-title {
			font-size: 32rpx;
			font-weight: bold;
			color: #333;
		}

		.popup-close {
			font-size: 40rpx;
			color: #999;
			cursor: pointer;
		}

		.popup-body {
			padding: 32rpx;
			flex: 1;
			overflow-y: auto;
		}

		.tag-group {
			display: flex;
			flex-wrap: wrap;
			gap: 16rpx;
		}

		.tag-item {
			padding: 16rpx 32rpx;
			border: 2rpx solid #DCDFE6;
			border-radius: 40rpx;
			font-size: 28rpx;
			color: #666;
			cursor: pointer;
			transition: all 0.3s;
			white-space: nowrap;
		}

		.tag-item.active {
			background: #388BFF;
			border-color: #388BFF;
			color: #fff;
		}

		.popup-footer {
			display: flex;
		}

		.popup-btn {
			flex: 1;
			gap: 20rpx;
			text-align: center;
			height: 88rpx;
			line-height: 88rpx;
			border: none;
			font-size: 28rpx;
			cursor: pointer;
			border-radius: 40rpx;
		}

		.cancel-btn {
			background: #fff;
			color: #666;
			border: 2rpx solid #DCDFE6;
		}

		.confirm-btn {
			background: #388BFF;
			color: #fff;
		}
	}

	::v-deep .u-popup__content {
		border-radius: 40rpx 40rpx 0 0 !important;
	}


	.popup-content {
		border-radius: 40rpx 40rpx 0rpx 0rpx;
		height: 70vh;
		background-color: #fff;

		.popup-header {
			padding: 40rpx 30rpx 20rpx;
			text-align: center;

			.close-icon {
				width: 44rpx;
				height: 44rpx;
				position: absolute;
				right: 32rpx;
			}

			flex-shrink: 0;

			.title {
				font-size: 32rpx;
				font-weight: 600;
				color: #333;
			}

			.popup-title {
				font-size: 32rpx;
				font-weight: 600;
				color: #333;
			}
		}

		.search-box {
			display: flex;
			align-items: center;
			background: #F7F8FA;
			border-radius: 38rpx;
			padding: 16rpx 28rpx;
			margin-bottom: 24rpx;

			.icon {
				width: 26rpx;
				height: 26rpx;
				margin-right: 10rpx;
			}
		}

		.project-list {
			height: calc(100% - 200rpx);

			.project-item {
				display: flex;
				justify-content: space-between;
				align-items: center;
				padding: 28rpx 0;
				font-size: 28rpx;
				border-bottom: 1rpx solid #eee;

				&:active {
					background-color: #f9f9f9;
				}

				&.active {
					.project-name {
						font-weight: 500;
						color: #388BFF;
					}

					.icon {
						opacity: 1;
					}
				}

				.project-name {
					color: #333;
					transition: all 0.2s ease;
				}

				.icon {
					width: 36rpx;
					height: 36rpx;
					opacity: 0;
					transition: opacity 0.2s ease;
				}
			}
		}

		.two-level-container {
			display: flex;
			flex: 1;
			border-top: 1rpx solid #f5f5f5;

			.primary-list {
				width: 40%;
				background-color: #f8f9fa;

				.primary-item {
					padding: 28rpx 20rpx;
					background: #F2F3F5;

					&:active {
						background: #FFFFFF;
					}

					&.primary-active {
						position: relative;
						background-color: #fff;

						&::before {
							content: '';
							position: absolute;
							top: 50%;
							left: 0;
							transform: translateY(-50%);
							width: 8rpx;
							height: 32rpx;
							background: #388BFF;
						}

						.primary-text {
							font-weight: 500;
						}
					}

					.primary-text {
						font-size: 28rpx;
						color: #666;
					}
				}
			}

			.secondary-list {
				width: 60%;
				padding: 0 20rpx;

				.secondary-item {
					display: flex;
					justify-content: space-between;
					align-items: center;
					padding: 28rpx 10rpx;
					font-size: 28rpx;
					color: #333;

					&.secondary-active {
						font-weight: 500;
						color: #388BFF;
					}
				}
			}
		}

		.popup-footer {
			padding: 20rpx 30rpx 40rpx;
			background-color: #fff;
			border-top: 1rpx solid #f5f5f5;
			flex-shrink: 0;

			.confirm-btn {
				width: 100%;
				height: 88rpx;
				line-height: 88rpx;
				background-color: #2979ff;
				color: #fff;
				font-size: 32rpx;
				border-radius: 200rpx 200rpx 200rpx 200rpx;

				&:active {
					opacity: 0.8;
				}
			}
		}
	}

	@media (prefers-color-scheme: dark) {
		.popup-content {
			background-color: #1e1e1e;

			.popup-header {

				.title,
				.popup-title {
					color: #fff;
				}
			}

			.two-level-container {
				.primary-list {
					background-color: #2d2d2d;
					border-right-color: #3d3d3d;

					.primary-item {
						border-bottom-color: #3d3d3d;

						&:active {
							background-color: #3d3d3d;
						}

						&.primary-active {
							background-color: #3d3d3d;

							.primary-text {
								color: #2979ff;
							}
						}

						.primary-text {
							color: #ccc;
						}
					}
				}

				.secondary-list {
					.secondary-item {
						border-bottom-color: #3d3d3d;

						&:active {
							background-color: #3d3d3d;
						}

						&.secondary-active {
							background-color: #2d2d2d;
						}

						.secondary-text {
							color: #fff;
						}
					}
				}
			}

			.popup-footer {
				background-color: #1e1e1e;
				border-top-color: #3d3d3d;
			}
		}
	}
</style>