<template>
	<!-- 弹窗遮罩层 -->
	<view class="bind-lab-modal" v-if="visible">
		<view class="bind-lab-content" @tap.stop>
			<!-- 标题栏 -->
			<view class="modal-header">
				<text class="modal-title">绑定实验室</text>
				<text class="modal-close" @click="$emit('close')">×</text>
			</view>

			<view class="modal-body">
				<!-- 搜索框区域：使用 view 包裹以兼容点击事件 -->
				<view class="search-box" @tap="handleFocus">
					<input class="search-input" type="text" placeholder="输入实验室名称、房号或楼栋关键词搜索…" v-model="keyword"
						@input="handleSearch" />
					<text class="search-icon">⌄</text>
				</view>

				<!-- 搜索提示 -->
				<view class="search-tip">
					<text>此处请选择需要后续进入的科研实验室的名称，输入实验室名称、房号或楼栋关键词，再从检索结果中选择目标实验室。</text>
				</view>

				<!-- 搜索结果下拉 -->
				<scroll-view v-if="showDropdown" scroll-y class="bind-lab-dropdown">
					<!-- 情况1：有数据，显示列表 -->
					<view v-if="searchList.length > 0">
						<view class="bind-lab-option" v-for="(lab, index) in searchList" :key="index" @click="selectLab(lab)">
							<text>{{ lab.deptName }}{{ lab.subName }}{{ lab.roomNum?'('+lab.roomNum+')':'' }}{{ lab.buildName }}{{ lab.floorName }}</text>
						</view>
					</view>
					<!-- 情况2：无数据，显示暂无数据 -->
					<view v-else class="bind-lab-empty">
						<text>暂无数据</text>
					</view>
				</scroll-view>

				<!-- 实验室信息表格 -->
				<view class="bind-lab-info" v-if="selectedLab">
					<view class="info-row">
						<view class="info-label">实验室名称</view>
						<view class="info-value text-bold">{{ selectedLab.labName }}</view>
						<view class="info-label">所在位置</view>
						<view class="info-value text-bold">{{ selectedLab.location }}</view>
					</view>
					<view class="info-row">
						<view class="info-label">负责人</view>
						<view class="info-value">{{ selectedLab.head }}</view>
						<view class="info-label">所属单位</view>
						<view class="info-value">{{ selectedLab.dept }}</view>
					</view>
					<view class="info-row">
						<view class="info-label">安全分级</view>
						<view class="info-value">{{ selectedLab.level }}</view>
						<view class="info-label">安全分类</view>
						<view class="info-value">{{ selectedLab.category }}</view>
					</view>
					<view class="info-row">
						<view class="info-label">实验室类型</view>
						<view class="info-value full-width">{{ selectedLab.type }}</view>
					</view>
				</view>

				<!-- 无需进入实验室 -->
				<view class="no-lab-box">
					<view class="checkbox-row" @click="isNoLabChecked = !isNoLabChecked">
						<view class="custom-checkbox" :class="{ 'checked': isNoLabChecked }"></view>
						<text class="no-lab-title">无需进入实验室</text>
					</view>
					<view class="no-lab-desc">
						<text>人文、体育等相关学院，无需进入实验室的新研究生可选择此项，选择后学时要求为4小时，需通过应知应会考试。</text>
					</view>
				</view>

				<!-- 阅读协议 -->
				<view class="agree-row" @click="isAgreeChecked = !isAgreeChecked">
					<view class="custom-checkbox" :class="{ 'checked': isAgreeChecked }"></view>
					<view class="agree-text">
						<text>我已阅读并同意</text>
						<text class="agree-link">《新生绑定实验室须知及责任说明》</text>
					</view>
				</view>

				<!-- 底部按钮 -->
				<view class="modal-footer">
					<view class="btn-cancel" @click="$emit('close')">取消</view>
					<view class="btn-confirm" @click="handleConfirm">确认绑定</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		examElLabEduRelationLabLists
	} from '@/pages_safetyEducationExamination/api/index.js'

	export default {
		name: 'BindLabModal',
		props: {
			visible: {
				type: Boolean,
				default: false
			}
		},
		data() {
			return {
				keyword: '',
				showDropdown: false,
				searchList: [],
				selectedLab: null,
				isNoLabChecked: false,
				isAgreeChecked: false,
				searchTimer: null
			}
		},
		watch: {
			visible(val) {
				if (val) {
					this.resetState();
				}
			}
		},
		methods: {
			resetState() {
				this.keyword = '';
				this.showDropdown = false;
				this.searchList = [];
				this.selectedLab = null;
				this.isNoLabChecked = false;
				this.isAgreeChecked = false;
			},
			// 搜索输入处理
			handleSearch() {
				clearTimeout(this.searchTimer);
				const trimKeyword = this.keyword.trim();

				// 逻辑1：少于2个字符，隐藏下拉框
				if (trimKeyword.length < 2) {
					this.showDropdown = false;
					return;
				}

				// 逻辑2：防抖请求
				this.searchTimer = setTimeout(async () => {
					try {
						const res = await examElLabEduRelationLabLists({
							searchValue: trimKeyword
						});
						if (res.data.code === 200) {
							this.searchList = res.data.data || [];
							// 只要有搜索结果（哪怕为空数组），都显示下拉框，由模板决定显示列表还是“暂无数据”
							this.showDropdown = true;
						} else {
							this.searchList = [];
							this.showDropdown = true; // 接口报错也显示“暂无数据”
						}
					} catch (e) {
						console.error('搜索失败', e);
						this.searchList = [];
						this.showDropdown = true;
					}
				}, 300);
			},
			// 搜索框聚焦/点击处理
			handleFocus() {
				// 逻辑3：点击时，如果有关键词且之前搜过有结果，直接显示列表
				// 注意：这里需要加一个延时，确保 input 获取焦点后再显示，避免键盘弹起冲突
				setTimeout(() => {
					if (this.keyword.trim().length >= 2 && this.searchList.length > 0) {
						this.showDropdown = true;
					}
				}, 100);
			},
			selectLab(lab) {
				this.selectedLab = lab;
				this.showDropdown = false;
				this.keyword = lab.labName;
			},
			handleConfirm() {
				if (!this.isAgreeChecked) {
					return uni.showToast({
						title: '请先阅读并同意协议',
						icon: 'none'
					});
				}
				if (!this.selectedLab && !this.isNoLabChecked) {
					return uni.showToast({
						title: '请选择实验室或勾选无需进入',
						icon: 'none'
					});
				}
				this.$emit('bind-success');
				this.$emit('close');
				uni.showToast({
					title: '绑定成功',
					icon: 'success'
				});
			}
		}
	}
</script>

<style lang="stylus" scoped>
	.bind-lab-modal {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		z-index: 800;
		background: rgba(0, 0, 0, 0.5);
	}

	.bind-lab-content {
		position: absolute;
		top: 50%;
		left: 50%;
		transform: translate(-50%, -50%);
		background: #ffffff;
		border-radius: 24rpx;
		width: 85%;
		max-width: 840rpx;
		min-height: 400rpx;
		max-height: 90vh;
		overflow-y: auto;
		box-shadow: 0 16rpx 64rpx rgba(0, 0, 0, 0.18);
		box-sizing: border-box;
	}

	.modal-header {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 32rpx 40rpx 24rpx;
	}

	.modal-title {
		font-size: 34rpx;
		font-weight: 700;
		color: #1a1a1a;
	}

	.modal-close {
		font-size: 40rpx;
		color: #999;
		line-height: 1;
	}

	.modal-body {
		padding: 0 40rpx 32rpx;
	}

	.search-box {
		position: relative;
		margin-bottom: 16rpx;
		/* 确保点击区域覆盖整个输入框 */
		z-index: 10;
	}

	.search-input {
		width: 100%;
		box-sizing: border-box;
		height: 80rpx;
		line-height: 80rpx;
		padding: 0 42rpx 0 24rpx;
		border: 1px solid #d9d9d9;
		border-radius: 16rpx;
		font-size: 26rpx;
		color: #333;
		background: #fafafa;
		/* 确保 input 在最上层，可点击 */
		position: relative;
		z-index: 11;
	}

	.search-icon {
		position: absolute;
		right: 20rpx;
		top: 40%;
		transform: translateY(-50%);
		color: #bbb;
		font-size: 30rpx;
		pointer-events: none;
	}

	.search-tip {
		font-size: 22rpx;
		color: #1677ff;
		margin-bottom: 24rpx;
		line-height: 1.5;
	}

	/* 下拉列表样式 */
	.bind-lab-dropdown {
		max-height: 600rpx;
		border: 1px solid #e8e8e8;
		border-radius: 16rpx;
		margin-bottom: 24rpx;
		background: #fff;
		box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.08);
		z-index: 99;
		position: relative;
	}

	.bind-lab-option {
		padding: 24rpx 28rpx;
		font-size: 26rpx;
		color: #333;
		border-bottom: 1px solid #f0f0f0;
		box-sizing: border-box;

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

		&:active {
			background: #f9f9f9;
		}
	}

	/* 暂无数据样式 */
	.bind-lab-empty {
		padding: 30rpx 0;
		text-align: center;
		color: #999;
		font-size: 26rpx;
	}

	.bind-lab-info {
		border: 1px solid #e8e8e8;
		border-radius: 16rpx;
		overflow: hidden;
		margin-bottom: 28rpx;
	}

	.info-row {
		display: flex;
		border-bottom: 1px solid #f0f0f0;

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

	.info-label {
		padding: 18rpx 24rpx;
		color: #888;
		background: #fafafa;
		width: 28%;
		font-size: 24rpx;
		white-space: nowrap;
	}

	.info-value {
		padding: 18rpx 24rpx;
		color: #333;
		font-size: 24rpx;
		flex: 1;
	}

	.full-width {
		flex: 3;
	}

	.no-lab-box {
		background: #f6f8ff;
		border-radius: 16rpx;
		padding: 24rpx 28rpx;
		margin-bottom: 28rpx;
	}

	.checkbox-row {
		display: flex;
		align-items: flex-start;
		gap: 16rpx;
	}

	.custom-checkbox {
		position: relative;
		width: 32rpx;
		height: 32rpx;
		border-radius: 6rpx;
		border: 2rpx solid #ccc;
		margin-top: 4rpx;
		flex-shrink: 0;
		box-sizing: border-box;

		&.checked {
			background: #1677ff;
			border-color: #1677ff;

			&::after {
				content: '';
				position: absolute;
				top: 45%;
				left: 20%;
				width: 10rpx;
				height: 20rpx;
				border: solid #ffffff;
				border-width: 0 3rpx 3rpx 0;
				transform: rotate(45deg) translate(-50%, -50%);
			}
		}
	}

	.no-lab-title {
		font-size: 26rpx;
		font-weight: 600;
		color: #1a1a1a;
	}

	.no-lab-desc {
		font-size: 22rpx;
		color: #888;
		margin-top: 10rpx;
		line-height: 1.6;
		padding-left: 40rpx;
	}

	.agree-row {
		display: flex;
		align-items: center;
		gap: 16rpx;
		margin-bottom: 36rpx;
	}

	.agree-text {
		display: flex;
		font-size: 24rpx;
		color: #555;
	}

	.agree-link {
		color: #1677ff;
		font-weight: 500;
	}

	.modal-footer {
		display: flex;
		gap: 20rpx;
		justify-content: flex-end;
	}

	.btn-cancel,
	.btn-confirm {
		padding: 16rpx 44rpx;
		border-radius: 12rpx;
		font-size: 26rpx;
	}

	.btn-cancel {
		border: 1px solid #d9d9d9;
		background: #fff;
		color: #555;
	}

	.btn-confirm {
		background: #1677ff;
		color: #fff;
		font-weight: 600;
	}

	.text-bold {
		font-weight: 700;
	}
</style>