<template>
	<view v-if="show" class="mask" @click="onMaskClick">
		<!-- 弹窗容器（阻止冒泡，避免点击内容关闭弹窗） -->
		<view class="popup-container" @click.stop>
			<!-- 弹窗头部 -->
			<view class="popup-header">
				<text class="popup-title">{{ isEdit ? '编辑用户' : title }}</text>
				<view class="close-btn" @click="onClose">
					<image src="/static/image/device/close_icon32.png" mode="widthFix"></image>
				</view>
			</view>

			<!-- 弹窗主体内容 -->
			<view class="popup-content">
				<view class="card-box">
					<view class="card-title">用户基本信息</view>
					<view class="form-item2">
						<view class="x-f">
							<text class="label">姓名：</text>
							<input type="text" v-model="form.username" class="form-input" placeholder="请输入姓名"
								placeholder-class="text-input" />
						</view>

						<view class="x-f">
							<text class="label">年龄：</text>
							<input type="number" v-model="form.age" class="form-input" placeholder="请输入年龄"
								placeholder-class="text-input" />
						</view>
					</view>

					<view class="form-item2">
						<text class="label">性别：</text>
						<radio-group class="r-box">
							<label style="margin-right: 30px;">
								<radio color="#8F6726" value="1" :checked="form.sex === 1" @click="genderChange(1)"
									style="margin-right: 12px;" />
								<text class="option-text">男</text>
							</label>
							<label>
								<radio color="#8F6726" value="0" :checked="form.sex === 0" @click="genderChange(0)"
									style="margin-right: 12px;" />
								<text class="option-text">女</text>
							</label>
						</radio-group>
					</view>
					<view class="form-item2">
						<view class="x-f">
							<text class="label">身高(cm)：</text>
							<input type="digit" v-model="form.height" class="form-input" placeholder="请输入身高"
								placeholder-class="text-input" />
						</view>
						<view class="x-f">
							<text class="label">体重(kg)：</text>
							<input type="digit" v-model="form.weight" class="form-input" placeholder="请输入体重"
								placeholder-class="text-input" />
						</view>
					</view>
					<view class="form-item">
						<text class="label">手机号：</text>
						<input type="number" v-model="form.phone" maxlength="11" class="form-input" placeholder="请输入手机号"
							placeholder-class="text-input" />
					</view>
				</view>

				<view class="card-box">
					<view class="card-title">既往病史(多选)</view>
					<view class="form-item3">
						<view class="card-list">
							<view v-for="(item,index) in qw" :key="item.id"
								:class="selectedIds.includes(item.id)?'card-btn active':'card-btn'"
								@click="changeQw(item)" :title="item.name">
								{{item.name}}
							</view>
							<view class="card-btn" style="padding: 0;border: 0;"></view>
							<view class="card-btn" style="padding: 0;border: 0;"></view>
						</view>
						<input v-if="isQw" type="text" v-model="otherQw" class="other-input" placeholder="请输入相关描述"
							placeholder-class="text-input" />
					</view>
				</view>
				<view class="card-box">
					<view class="card-title">过敏史</view>
					<view class="form-item3">
						<view class="card-list">
							<view v-for="(item,index) in all" :key="item.id"
								:class="aIndex==item.id?'card-btn active':'card-btn'" @click="changeAll(item)"
								:title="item.name">
								{{item.name}}
							</view>
							<view class="card-btn" style="padding: 0;border: 0;"></view>
							<view class="card-btn" style="padding: 0;border: 0;"></view>
						</view>
						<input v-if="isAll" type="text" v-model="otherAll" class="other-input" placeholder="请输入相关描述"
							placeholder-class="text-input" />
					</view>
				</view>
				<view class="card-box">
					<view class="card-title">生活习惯</view>
					<view class="form-item3">
						<!-- <text class="label">既往病史：</text> -->
						<view class="card-list">
							<view v-for="(item,index) in habits" :key="item.qId" class="card-text">
								{{index+1}}、{{item.typeName}}
								<view class="card-text-box">
									<view v-for="(it,idx) in item.option" :key="it.id" class="card-btn2"
										@click="changeH(it,item)" :class="{ 'active': item.selectedId == it.id}"
										:title="it.name">
										{{it.name}}
									</view>
									<view class="card-btn2" style="padding: 0;border: 0;"></view>
									<view class="card-btn2" style="padding: 0;border: 0;"></view>
								</view>

							</view>
						</view>
					</view>
				</view>
			</view>

			<!-- 弹窗底部按钮 -->
			<view class="popup-footer">
				<view class="btn2 cancel-btn2" @click="onClose">
					<text>取消</text>
				</view>
				<!-- <view class="btn2 confirm-btn2" @click="onConfirm">
		  <text>下一步</text>
		</view> -->
				<view class="btn2 confirm-btn2" @click="onConfirm">
					<text>确认</text>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		el
	} from 'date-fns/locale';

	export default {
		name: 'UserFormPopup',
		props: {
			// 控制弹窗显示/隐藏
			show: {
				type: Boolean,
				default: false
			},
			// 弹窗标题（默认“新建用户”，可自定义）
			title: {
				type: String,
				default: '新建用户'
			},
			// 初始表单数据（用于编辑场景）
			initialForm: {
				type: Object,
				default: () => ({})
			}
		},
		data() {
			return {
				form: {
					username: '', // 姓名
					phone: '', // 手机号
					sex: 1, // 性别（1-男，0-女）
					age: '', // 年龄
					height: '', // 身高
					weight: '', // 体重
					previousMedicalHistory: '', // 既往病史
					habitList: [], //饮食习惯
					historyOfAllergies: '' //过敏史
				},
				isEdit: false,
				qIndex: null,
				aIndex: null,
				isAll: false,
				isQw: false,
				otherAll: null,
				otherQw: null,
				selectedIds: [],
				initialFormKeys:[],
				qw: [{
						name: '无',
						id: 1
					},
					{
						name: '糖尿病',
						id: 2
					},
					{
						name: '高血压',
						id: 3
					},
					{
						name: '心脑血管疾病',
						id: 4
					},
					{
						name: '胃病',
						id: 5
					},
					{
						name: '排便异常',
						id: 6
					},
					{
						name: '肝病',
						id: 7
					},
					{
						name: '肾病',
						id: 8
					},
					{
						name: '其他',
						id: 9,
						isQw: true
					},
				],
				all: [{
						name: '无',
						id: 1
					},
					{
						name: '药物',
						id: 2
					},
					{
						name: '食物',
						id: 3
					},
					{
						name: '花粉',
						id: 4
					},
					{
						name: '其他',
						id: 5,
						isAll: true
					},
				],
				habits: [{
						typeName: '睡眠状况',
						qId: 1,
						option: [{
							name: '很差',
							id: 1,
						}, {
							name: '差',
							id: 2
						}, {
							name: '一般',
							id: 3
						}, {
							name: '良好',
							id: 4
						}, ],
						selectedId: null // 存储选中的选项ID
					},
					{
						typeName: '睡眠时间',
						qId: 2,
						option: [{
							name: '<6小时',
							id: 1,
						}, {
							name: '6-8小时',
							id: 2
						}, {
							name: '9-10小时',
							id: 3
						}, {
							name: '>10小时',
							id: 4
						}, ],
						selectedId: null // 存储选中的选项ID
					},
					{
						typeName: '是否经常熬夜',
						qId: 3,
						option: [{
							name: '经常',
							id: 1,
						}, {
							name: '偶尔',
							id: 2
						}, {
							name: '很少',
							id: 3
						}, {
							name: '无',
							id: 4
						}, ],
						selectedId: null // 存储选中的选项ID
					},
					{
						typeName: '饮食习惯',
						qId: 4,
						option: [{
								name: '正常就餐',
								id: 1,
							},
							{
								name: '暴饮暴食',
								id: 2,
							},
							{
								name: '压力大进食',
								id: 3
							},
							{
								name: '就外就餐多',
								id: 4
							},
							{
								name: '不吃早餐',
								id: 5
							},

						],
						selectedId: null // 存储选中的选项ID
					},
					{
						typeName: '日常运动量',
						qId: 5,
						option: [{
								name: '久坐不动',
								id: 1,
							},
							{
								name: '轻度运动',
								id: 2
							},
							{
								name: '中度运动',
								id: 3
							},
							{
								name: '大量运动',
								id: 4
							},
						],
						selectedId: null // 存储选中的选项ID
					},
					{
						typeName: '每周锻炼次数',
						qId: 6,
						option: [{
								name: '≤2次',
								id: 1,
							},
							{
								name: '3-5次',
								id: 2
							},
							{
								name: '>5次',
								id: 3
							},
						],
						selectedId: null // 存储选中的选项ID
					},
					{
						typeName: '每次锻炼时间多少分钟',
						qId: 7,
						option: [{
								name: '≤20分钟',
								id: 1,
							},
							{
								name: '20-40分钟',
								id: 2
							},
							{
								name: '41-60分钟',
								id: 3
							},
							{
								name: '>60分钟',
								id: 4
							},
						],
						selectedId: null // 存储选中的选项ID
					},
				]
			};
		},
		watch: {
			// 监听初始数据变化（用于编辑时回显）
			initialForm: {
				immediate: true,
				handler(val) {

					if (val && Object.keys(val).length > 0) {
						this.form = {
							...val
						};
						this.isEdit = true
						this.init()
						//console.log(this.form,'---')
					} else {
						this.isEdit = false
					}
				}
			},
			// 监听弹窗显示状态，每次显示时重置表单（可选）
			show(newVal) {
				//console.log(newVal)
				if (!newVal) {
					this.resetForm();
				}

			}
		},
		created() {
		    // 初始化时记录form的所有初始键（只执行一次）
		    const formKeys = Object.keys(this.form);
			const extraKeys = ['userId','id','username','fsUserId'];
			    // 3. 合并并去重（避免重复字段）
		    this.initialFormKeys = [...new Set([...formKeys, ...extraKeys])];
			if (!Array.isArray(this.form.habitList)) {
			    this.form.habitList = [];
			 }
		  },
		methods: {
			//回显数据处理
			init() {
				// 1. 既往病史回显
				if (this.form.previousMedicalHistory !== '') {
					const historyArr = this.form.previousMedicalHistory.split('，');
					const presetNames = this.qw.map(item => item.name);
					// 1. 筛选出属于预设选项的内容，回显到选中状态
					const selectedPresetIds = this.qw
						.filter(option => historyArr.includes(option.name))
						.map(option => option.id);
					this.selectedIds = selectedPresetIds;

					// 2. 筛选出不属于预设选项的内容（归为“其他”）
					const otherTexts = historyArr.filter(text =>
						!presetNames.includes(text) // 排除预设选项名称
					);

					// 3. 处理“其他”选项的回显
					if (otherTexts.length > 0) {
						// 自动勾选“其他”选项
						if (!this.selectedIds.includes(9)) {
							this.selectedIds.push(9);
						}
						// 合并所有非预设内容到“其他”输入框
						this.isQw = true;
						this.otherQw = otherTexts.join('，'); // 多个非预设内容用逗号拼接
					}
				}

				// 2. 过敏史回显
				if (this.form.historyOfAllergies !== '') {
					const allergyItem = this.all.find(item => item.name === this.form.historyOfAllergies);
					this.aIndex = allergyItem ? allergyItem.id : 5; // 找不到则默认“其他”
					if (this.aIndex === 5) {
						this.isAll = true;
						this.otherAll = this.form.historyOfAllergies;
					}
				}

				// 3. 生活习惯回显
				if (Array.isArray(this.form.habitList) && this.form.habitList.length > 0) {
				  this.habits.forEach(habit => {
				    const matched = this.form.habitList.find(item => item.qId === habit.qId);
				    if (matched) {
				      habit.selectedId = matched.optionId; // 回显选中状态
				    }else {
      // 可选：无匹配数据时，强制清空选中状态（避免残留旧数据）
      habit.selectedId = null; 
    }
				  });
				}
				
			},
			// 重置表单
			resetForm() {
				this.form = {
					username: '',
					phone: '',
					sex: 1,
					age: '',
					height: '',
					weight: '',
					previousMedicalHistory: '',
					habitList: [],
					historyOfAllergies: ''
				};
				this.selectedIds = [],
					this.habits.forEach(item => {
						item.selectedId = null; // 遍历每个问题，清空选中ID
					});
				this.isEdit = false,
					this.qIndex = null,
					this.aIndex = null,
					this.isAll = null,
					this.isQw = null,
					this.otherAll = null,
					this.otherQw = null
			},
			// 性别切换
			genderChange(sex) {
				this.form.sex = sex;
			},
			changeQw(item) {
				this.qIndex = item.id
				// 检查当前项是否已选中
				const index = this.selectedIds.indexOf(item.id);
				if (item.id === 1) { // 选中“无”
					this.selectedIds = [1];
					this.isQw = false;
					this.otherQw = '';
					return;
				}
				if (index > -1) {
					// 如果已选中，则移除
					this.selectedIds.splice(index, 1);
					// 如果移除的是"其他"选项，隐藏输入框
					if (item.isQw) {
						this.isQw = false;
						this.otherQw = '';
					}
				} else {
					this.selectedIds = this.selectedIds.filter(id => id !== 1);
					// 如果未选中，则添加
					this.selectedIds.push(item.id);
					// 如果选中的是"其他"选项，显示输入框
					if (item.isQw) {
						this.isQw = true;
					}
				}
			},
			// 拼接选中的病史为字符串
			getSelectedHistoryString() {
				// 收集所有选中项的名称
				const selectedNames = [];

				this.selectedIds.forEach(id => {
					const item = this.qw.find(item => item.id === id);
					if (item) {
						//console.log(item,'item')
						// 如果是"其他"选项且有输入内容，使用输入的内容
						if (item.id === 9 ) {
							const otherVal = (this.otherQw || '').trim();
							  if (otherVal) { // 仅当有有效内容时才添加
							    selectedNames.push(otherVal);
							  }
						}
						// 排除没有输入内容的"其他"选项
						else if (item.id !== 9) {
							selectedNames.push(item.name);
						}
					}
				});

				// 将数组拼接为逗号分隔的字符串
				return selectedNames.join('，'); // 使用中文逗号分隔
			},
			//拼接选中的过敏史名称为字符串
			getAllergyString() {
				if (!this.aIndex) return '';

				const selectedItem = this.all.find(item => item.id === this.aIndex);
				if (!selectedItem) return '';

				// 处理"其他"选项
				if (this.aIndex === 5) {
					const otherVal = this.otherAll || ''; // 若为null/undefined，转为空字符串
					    if (otherVal.trim()) { // 此时调用trim()不会报错
					      return otherVal.trim();
					    }
				}

				return selectedItem.name;
			},
			changeAll(item) {
				this.aIndex = item.id
				if (item.isAll) {
					this.isAll = true
				} else {
					this.isAll = false
				}
			},
			changeH(option, question) {
				//console.log(question,'question')
				// 单选逻辑：设置当前问题的选中ID为点击的选项ID
				question.selectedId = option.id
				this.updateHabitList(question, option)
			},
			// 更新生活习惯列表
			updateHabitList(question, selectedOption) {
				if (!Array.isArray(this.form.habitList)) {
				    this.form.habitList = []; // 强制转为空数组
				  }
				// 查找当前问题在habitList中的索引
				const index = this.form.habitList.findIndex(item => item.qId === question.qId);

				// 构建生活习惯数据对象
				const habitData = {
					qId: question.qId,
					typeName: question.typeName,
					optionId: selectedOption.id,
					optionName: selectedOption.name,
				};
				// 如果已存在则更新，否则添加
				if (index > -1) {
					this.form.habitList.splice(index, 1, habitData);
				} else {
					this.form.habitList.push(habitData);
				}
				//console.log(this.form.habitList)
			},
			// 关闭弹窗
			onClose() {
				this.$emit('close');
			},
			// 点击遮罩层关闭（可选）
			onMaskClick() {
				this.$emit('close');
			},
			// 确认提交
			onConfirm() {
				// 表单校验
				if (this.form.username == null || this.form.username == '') {
					uni.showToast({
						title: "姓名不能为空",
						icon: "none"
					})
					return
				}
				if (this.form.age == null || this.form.age == '') {
					uni.showToast({
						title: "年龄不能为空",
						icon: "none"
					})
					return
				}
				if (this.form.height == null || this.form.height == '') {
					uni.showToast({
						title: "身高不能为空",
						icon: "none"
					})
					return
				}
				if (this.form.weight == null || this.form.weight == '') {
					uni.showToast({
						title: "体重不能为空",
						icon: "none"
					})
					return
				}
				const phoneError = this.checkPhone(this.form.phone);
				if (phoneError) {
					uni.showToast({
						title: phoneError, // 直接显示具体错误
						icon: "none"
					});
					return;
				}
				const isOtherSelected = this.selectedIds.includes(9);
				if (isOtherSelected && (this.otherQw==null || this.otherQw=='')) {
					uni.showToast({
						title: "请输入其他描述",
						icon: "none"
					})
					return
				}
				this.form.previousMedicalHistory = this.getSelectedHistoryString();
				if (this.form.previousMedicalHistory == '') {
					uni.showToast({
						title: "既往病史不能为空",
						icon: "none"
					})
					return;
				}
				this.form.historyOfAllergies = this.getAllergyString();
				if (this.form.historyOfAllergies=='') {
					uni.showToast({
						title: "过敏史不能为空",
						icon: "none"
					})
					return;
				}
				if (this.aIndex == 5 && (this.otherAll==null || this.otherAll=='')) {
					uni.showToast({
						title: "请输入其他描述",
						icon: "none"
					})
					return
				}

				const unselected = this.habits.find(question => question.selectedId === null);
				if (unselected) {
					uni.showToast({
						title: `请选择${unselected.typeName}`,
						icon: "none"
					})
					return;
				}

				// 校验通过，提交表单数据
				if (this.isEdit) {
					 const submitData = {};
					      this.initialFormKeys.forEach(key => {
					        submitData[key] = this.form[key]; // 即使值为空也保留键
					      });
						  
					submitData.habitList = this.form.habitList.filter(item => !item.option);
					// 修改逻辑：通常需要携带唯一标识（如id）
					this.$emit('update', {
						...submitData
					});
				} else {
					this.$emit('confirm', {
						...this.form
					});
				}
			},
			// 手机号校验函数
			checkPhone(val) {
				const phone = val?.trim(); // 去除首尾空格

				// 1. 非空校验
				if (!phone) {
					uni.showToast({
						title: "手机号不能为空",
						icon: "none"
					});
					return "请输入正确的手机号";
				}

				// 2. 格式校验（中国大陆手机号规则：11位数字，以1开头）
				const phoneReg = /^1[3-9]\d{9}$/; // 正则表达式
				if (!phoneReg.test(phone)) {
					uni.showToast({
						title: "请输入正确的手机号",
						icon: "none"
					});
					return "请输入正确的手机号";
				}

				// 校验通过
				return '';
			}

		}
	};
</script>

<style scoped lang="scss">
	/* 遮罩层 */
	.mask {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background-color: rgba(0, 0, 0, 0.5);
		display: flex;
		justify-content: center;
		align-items: center;
		z-index: 999;
	}

	/* 弹窗容器 */
	.popup-container {
		width: 85%;
		height: 85%;
		/* max-width: 500px; */
		background-color: #fff;
		border-radius: 12px;
		overflow: hidden;
	}

	/* 弹窗头部 */
	.popup-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 20px;
		border-bottom: 1px solid #eee;
		background: #E9DDCD;
	}

	.popup-title {
		flex: 1;
		font-family: Source Han Serif CN, Source Han Serif CN;
		font-weight: bold;
		font-size: 24px;
		color: #8F6726;
		text-align: center;
	}

	.close-btn {
		width: 24px;
		height: 24px;
	}

	.close-btn image {
		width: 100%;
		height: 100%;
	}

	/* 弹窗内容 */
	.popup-content {
		padding: 30px;
		height: 80%;
		overflow-y: auto;
	}

	.popup-content::-webkit-scrollbar {
		display: block !important;
		width: 10px !important;
		/* 滚动条宽度 */
	}

	.popup-content::-webkit-scrollbar-thumb {
		background: #8F6726 !important;
		/* 滚动条滑块颜色 */
		border-radius: 5px !important;
		/* 滑块圆角 */
	}

	.card-box {
		border-radius: 12px;
		border: 1px solid #8F6726;
		padding: 20px;
		margin-bottom: 20px;
	}

	.card-title {
		font-size: 24px;
		color: #222;
		/* margin-bottom: 20px; */
	}

	.card-list {
		width: 100%;
		display: flex;
		align-items: center;
		flex-direction: row;
		justify-content: space-between;
		flex-wrap: wrap;
		gap: 15px;
		margin-top: 20px;
	}

	.card-text {
		display: flex;
		align-items: flex-start;
		flex-direction: column;
		width: 100%;
		font-size: 20px;
		color: #8F6726;
		padding-bottom: 20px;
		// border-bottom: 1px solid #E9DDCD;

		// margin-bottom: 10px;
		&:last-child {
			border-bottom: 0;
		}
	}

	.card-text-box {
		display: flex;
		align-items: center;
		flex-direction: row;
		justify-content: space-between;
		flex-wrap: wrap;
		width: 100%;
		gap: 15px;
		margin-top: 10px;
	}

	.card-btn2 {
		width: calc(100% /3.5);
		color: #8F6726;
		border: 1px solid #8F6726;
		border-radius: 6px;
		padding: 10px;
		text-align: center;
		white-space: nowrap;
		/* 强制文字不换行 */
		overflow: hidden;
		/* 隐藏溢出的文字 */
		text-overflow: ellipsis;

		/* 溢出部分显示省略号 */
		&.active {
			background: #8F6726;
			color: #fff;
		}

		/* margin-top: 20px; */
	}

	.card-btn3 {
		width: calc(100% /3.5);
		white-space: nowrap;
		/* 强制文字不换行 */
		overflow: hidden;
		/* 隐藏溢出的文字 */
		text-overflow: ellipsis;
		/* 溢出部分显示省略号 */
	}

	.card-btn {
		// flex:1;
		width: calc(100% / 3.5);
		color: #8F6726;
		font-size: 20px;
		border: 1px solid #8F6726;
		border-radius: 6px;
		padding: 10px;
		text-align: center;
		white-space: nowrap;
		/* 强制文字不换行 */
		overflow: hidden;
		/* 隐藏溢出的文字 */
		text-overflow: ellipsis;
		/* 溢出部分显示省略号 */

		&.active {
			background: #8F6726;
			color: #fff;
		}
	}

	.form-item {
		display: flex;
		align-items: center;
		margin-top: 20px;
	}

	.form-item2 {
		display: flex;
		justify-content: space-between;
		margin-top: 20px;
	}

	.form-item3 {
		display: flex;
		align-items: flex-start;
		flex-direction: column;
	}

	.x-f {
		display: flex;
		align-items: center;
		width: 48%;
	}

	.x-c {
		display: flex;
		align-items: center;
		width: 30%;
	}

	.label {
		font-family: PingFang SC, PingFang SC;
		font-weight: 500;
		font-size: 20px;
		color: #222;
	}

	.form-input {
		flex: 1;
		height: 47px;
		line-height: 47px;
		padding: 0px 15px;
		box-sizing: border-box;
		border: 1px solid #E9DDCD;
		border-radius: 6px;
		font-size: 18px;
	}

	.other-input {
		width: 100%;
		margin-top: 20px;
		height: 47px;
		line-height: 47px;
		box-sizing: border-box;
		padding: 0 15px;
		border: 1px solid #E9DDCD;
		border-radius: 6px;
		font-size: 18px;
	}

	.text-input {
		color: #ccc;
	}

	.r-box {
		flex: 1;
		display: flex;
		align-items: center;
		// justify-content: space-between;
	}

	.option-text {
		font-size: 18px;
		color: #333;
	}

	.uni-label-pointer {
		display: flex;
		align-items: center;
	}

	/* 弹窗底部 */
	.popup-footer {
		display: flex;
		padding: 20upx 30upx;
		border-top: 1px solid #eee;
	}

	.btn2 {
		flex: 1;
		height: 53px;
		line-height: 53px;
		text-align: center;
		border-radius: 12px;
		font-size: 20px;
		margin: 0 10px;
	}

	.cancel-btn2 {
		background-color: #f5f5f5;
		color: #666;
	}

	.confirm-btn2 {
		background-color: #8F6726;
		color: #fff;
	}
</style>