<template>
	<view class="add-postnatal">
		<!-- 产检时间 -->
		<view class="add-postnatal-time style1">
			<view class="time-l">
				<image :src="`${$baseUrl}chanjianTool/1001/icon7.png`" />
				产检时间
			</view>
			<view class="time-r" @click="onChangeTime">
				{{ time }}
				<image :src="`${$baseUrl}chanjianTool/1001/icon13.png`" />
			</view>
		</view>
		<!-- 产检项目 -->
		<view class="add-postnatal-project">
			<view class="project-info style1">
				<view class="time-l">
					<image :src="`${$baseUrl}chanjianTool/1001/icon8.png`" />
					产检项目
				</view>
				<view class="project-r" @click="onAdd">
					<image :src="`${$baseUrl}chanjianTool/1001/icon10.png`" />
					添加
				</view>
			</view>

			<!-- 添加的产品项目 -->
			<view class="project-list" v-if="listData.length > 0">
				<view class="list-item" v-for="({ itemName, id }, index) in listData" :key="index">
					<view class="item-name">
						{{ itemName }}
					</view>
					<image @click="onDelete(id)" class="item-img" :src="`${$baseUrl}chanjianTool/1001/delete.png`"></image>
				</view>
			</view>
		</view>

		<!-- 报告单 -->
		<view class="add-postnatal-bgd">
			<view class="style1">
				<view class="time-l">
					<image :src="`${$baseUrl}chanjianTool/1001/icon9.png`" />
					本次报告单
				</view>
				<view class="time-r" @click="onSeeBtn">
					查看全部
					<image :src="`${$baseUrl}chanjianTool/1001/icon13.png`" />
				</view>
			</view>
			<view class="img-list">
				<view class="upload-image" @click="onUpload">
					<image :src="`${$baseUrl}chanjianTool/1001/icon11.png`"></image>
				</view>
				<view class="img-list-item" v-for="(item, index) in bgdImgList" :key="index">

					<view class="item-image" @click="onPreviewImage(item)">
						<image class="img1" :src="item" mode="aspectFill"></image>
					</view>
					<image @click="onImageDel(item)" class="img" :src="`${$baseUrl}chanjianTool/1001/icon14.png`"></image>
				</view>
			</view>
		</view>
		<!-- 上传报告单 -->

		<button class="form-btn" @click="onSave">
			保存
		</button>
		<!-- 产检选择时间 -->
		<!-- 使用封装后的日期选择器组件 -->
		<DatePicker v-model:visible="visible" :default-date="time" @confirm="handleDateConfirm" />
		<!-- 产检项目底部弹窗 -->
		<uni-popup ref="popup" type="bottom" :mask-click="false" background-color="#f6f8fa"
			border-radius="32rpx 32rpx 0 0">
			<view class="popup container">
				<view class="popup-close" @click="onPopupClose">
					<image :src="`${$baseUrl}chanjianTool/1001/icon15.png`"></image>
				</view>
				<!-- 项目列表 -->
				<view  class="airport-list">
					<view v-for="group in examinationList" :key="group.groupName" class="letter-group">
						<view class="letter-title">{{ group.groupName }}</view>
						<view class="box">
							<view v-for="item in group.list" :key="item.id" class="airport-item">
								<view class="airport-item-radio" @click="toggleSelect(item)">
									
									<image class="image-1" v-if="isSelected(item.id)"
										:src="`${$baseUrl}chanjianTool/1001/icon17.png`" mode=""></image> 
									<image class="image-2" v-else :src="`${$baseUrl}chanjianTool/1001/icon18.png`"></image>
									<view class="image-3">
										{{ item.itemName }}
									</view>
									
								</view>
								<view class="airport-item-image" @click.stop="onView(item)">
									<image :src="`${$baseUrl}chanjianTool/1001/icon16.png`"></image>
								</view>

							</view>
						</view>

					</view>
				</view>
				<!-- 底部操作栏 -->
				<button class="action-bar" @click="saveSelection">确认</button>

			</view>
		</uni-popup>
		<!-- 项目介绍 -->
		<uni-popup ref="popupText" type="bottom" :mask-click="true" background-color="#FFFFFF"
			border-radius="32rpx 32rpx 0 0">
			<view class="container2">
				<view class="text-t">
					<view class="t-1">
						{{ popupTextObj.itemName }}
					</view>
					<image @click="onPopupClose2" :src="`${$baseUrl}chanjianTool/1001/icon15.png`" mode=""></image>
				</view>
				<view class="text-c">
					{{ popupTextObj.introduction }}
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script setup>
import {
	ref
} from 'vue'
import {
	dateFormatter,
	throttleTap,
	showLoading,
	hideLoading
} from '@/utils/index.js';
import { onLoad } from '@dcloudio/uni-app'
import {
	uploadImage
} from "../../api/common.js";

import {
	getAdd,
	getExaminationItems
} from '../../api/obstetric.js';

// 导入日期选择器组件
import DatePicker from '@/components/DatePicker.vue'
import { useUserStore } from "@/stores/user";
import md from '../../md';

// 获取用户信息
const userStore = useUserStore();
const babyId = ref(userStore.babyInfo?.content?.id) 

// 默认产检时间
const time = ref('');

// 控制选择时间显示
const visible = ref(false)

// 产品项目底部弹窗
const popup = ref(null)

// 产品项目介绍底部弹窗
const popupText = ref(null)

// 存储查看项目介绍内容
const popupTextObj = ref({})

// 模拟项目列表
const examinationList = ref([])

// 已选项目（存储ID和name）
const selectedAirports = ref([]);

// 添加的产品列表
const listData = ref([]);

// 报告单图片
const bgdImgList = ref([])

// 查看项目介绍
const onView = (item) => {
	console.log(item)
	popupTextObj.value = item
	popupText.value.open()
}
// 关闭项目介绍弹窗
const onPopupClose2 = () => {
	popupText.value.close()
}
// 修改时间
const onChangeTime = () => {
	md.sensorLogTake({
		xcxClick: "小程序页面点击事件",
		pageName: "新增产检页",
		buttonName: "产检时间选择",
	});
	visible.value = true;
}
// 选择日期回调确认
const handleDateConfirm = (date) => {
	console.log('选择的日期是：', date);
	time.value = date;

}
// 添加项目
const onAdd = () => {
	md.sensorLogTake({
		xcxClick: "小程序页面点击事件",
		pageName: "新增产检页",
		buttonName: "产检项目添加",
	});
	wx.setPageStyle({
		style: {
			overflow: 'hidden'
		}
	})
	popup.value.open()
	md.sensorComponentLogTake({
		xcxPopExposure: "true",
		toolName: "产检提醒",
		popName: "选择产检项目弹窗"
		
	});
	// 回显数据
	if (listData.value.length > 0) {
		// 回显数据 - 将 listData 中的数据同步到 selectedAirports
		selectedAirports.value = [...listData.value]
	}
}
// 关闭项目弹窗
const onPopupClose = (type) => {
	if (type !== 'nonePop') {
		md.sensorPopLogTake({
			xcxPopClick: "true",
			toolName: "产检提醒",
			popName: "选择产检项目弹窗",
			buttonName: "关闭"
		});
	}
	wx.setPageStyle({
		style: {
			overflow: 'auto'
		}
	})
	selectedAirports.value = []
	popup.value.close()
	
}
// 检查是否已选中
const isSelected = (id) => {
	return selectedAirports.value.some(item => item.id == id);
};

// 切换选择状态
const toggleSelect = (airport) => {
	const index = selectedAirports.value.findIndex(item => item.id == airport.id);
	if (index === -1) {
		selectedAirports.value.push({
			id: airport.id,
			itemName: airport.itemName
		});
		md.sensorComponentLogTake({
			xcxPopClick: "true",
			toolName: "产检提醒",
			popName: "选择产检项目弹窗",
			buttonName: airport.itemName
		});
	} else {
		selectedAirports.value.splice(index, 1);
	}
};

// 保存选择
const saveSelection = () => {
	console.log('已选项目ID:', selectedAirports.value);
	// 合并 selectedAirports.value 到 listData.value，并去重
	const combined = [...listData.value, ...selectedAirports.value];
	const uniqueMap = new Map();
	combined.forEach(item => uniqueMap.set(item.id, item));
	listData.value = Array.from(uniqueMap.values());
	onPopupClose("nonePop");
	md.sensorPopLogTake({
		xcxPopClick: "true",
		toolName: "产检提醒",
		popName: "选择产检项目弹窗",
		buttonName: "确认"
	});
};
// // 移除已选项目
// const removeSelected = (airport) => {
// 	const index = selectedAirports.value.findIndex(item => item.id === airport.id);
// 	if (index !== -1) {
// 		selectedAirports.value.splice(index, 1);
// 	}
// };
// 删除所选产品项目
const onDelete = (id) => {
	md.sensorLogTake({
		xcxClick: "小程序页面点击事件",
		pageName: "新增产检页",
		buttonName: "删除产检项目",
	});

	listData.value.filter((item, index) => {
		if (item.id == id) {
			listData.value.splice(index, 1)
		}
	})
}
// 图片预览
const onPreviewImage = (url) => {
	console.log(url)
	uni.previewImage({
		current: '1',
		urls: [url]
	})
}
// 删除上传图片
const onImageDel = (e) => {
	bgdImgList.value.filter((item, index) => {
		if (item === e) {
			bgdImgList.value.splice(index, 1)
		}
	})
}
// 上传图片
const onUpload = throttleTap(() => {
	md.sensorLogTake({
		xcxClick: "小程序页面点击事件",
		pageName: "新增产检页",
		buttonName: "上传报告单",
	});

	if (bgdImgList.value.length == 15) {
		uni.showToast({
			title: "最多上传15张图片",
			icon: "none",
		});
		return;
	}
	// 唤起图片选择器
	uni.chooseImage({
		count: 1,
		sizeType: ["original", "compressed"],
		sourceType: ["album", "camera"],
		success: async (res) => {
			showLoading();
			const tempFilePath = res.tempFilePaths[0];
			console.log(tempFilePath)
			const fs = uni.getFileSystemManager();
			console.log(fs)
			const base64 =
				"data:image/jpeg;base64," + fs.readFileSync(tempFilePath, "base64");

			const uploadRes = await uploadImage(base64);

			hideLoading();
			if (uploadRes.success) {
				console.log(uploadRes)
				bgdImgList.value.push(uploadRes.data.url)
			} else {
				uni.showToast({
					title: uploadRes.message,
					icon: "none",
				});
			}
		},
	});
})

// 保存
const onSave = throttleTap( async () => {
	md.sensorLogTake({
		xcxClick: "小程序页面点击事件",
		pageName: "新增产检页",
		buttonName: "保存",
	});
	if (listData.value.length == 0) {
		uni.showToast({
			title: '还没有添加产检项哦',
			icon: 'none'
		})
		return
	}
	if (bgdImgList.value.length == 0) {
		uni.showToast({
			title: '还没有上传报告单哦',
			icon: 'none'
		})
		return
	}
	const ids = listData.value.map(item => item.id).join(',');
	const param = {
		checkupDate: time.value,
		checkupItems: ids,
		reportImages: bgdImgList.value,
		babyId: babyId.value
	}
	console.log(param, '新增产检保存参数')
	showLoading();
	const {success, data } = await getAdd(param);
	hideLoading();
	if (success) {
		uni.showToast({
			title: "保存成功",
			icon: "success",
		});
		uni.navigateBack()
	} else {
		uni.showToast({
			title: message,
			icon: "none",
		});
	}
})

// 查看更多
const onSeeBtn = () => {
	md.sensorLogTake({
		xcxClick: "小程序页面点击事件",
		pageName: "新增产检页",
		buttonName: "查看全部",
	});

	// 跳转
	uni.navigateTo({
		url: '/pages/myReportCard/myReportCard'
	})
}

// 获取产检项目列表
const getList = async () => {
	const {success, data, message } = await getExaminationItems()
	console.log(success, data, message, '获取产检项目列表')
	if (success) {
		examinationList.value = data
	}
}
onLoad((options) => {
	md.sensorLogTake({
		xcxPage: "小程序页面浏览事件",
		pageName: "新增产检页"
	});
	if (Object.keys(options).length > 0 && options.time) {
		time.value = options.time
	} else {
		time.value = dateFormatter(new Date(), 'yyyy-MM-dd')
	}
	console.log(options, '新增页面')
	getList()
})
</script>

<style lang="less" scoped>
.add-postnatal {
	height: 100vh;
	background-color: #f7f8fa;
	padding: 25rpx 35rpx;

	.style1 {
		width: 680rpx;
		height: 115rpx;
		background: #ffffff;
		display: flex;
		align-items: center;
		justify-content: space-between;
		font-size: 30rpx;
		padding: 0 27rpx;
		box-sizing: border-box;

		.time-l,
		.time-r,
		.project-r {
			display: flex;
			align-items: center;
		}

		.time-l {
			color: #000000;
			font-weight: 600;

			image {
				width: 30rpx;
				height: 30rpx;
				margin-right: 10rpx;
			}
		}
	}

	&-time {
		margin-top: 22rpx;
		border-radius: 16rpx;

		.time-r {
			color: #1d1e26;

			image {
				width: 8rpx;
				height: 16rpx;
				margin-left: 12rpx;
			}
		}
	}

	&-project {
		width: 680rpx;
		border-radius: 16rpx;
		overflow: hidden;
		margin-top: 22rpx;
		background: #ffffff;

		.project-r {
			color: #b27c1e;

			image {
				width: 27rpx;
				height: 27rpx;
				margin-right: 5rpx;
			}
		}
	}

	&-bgd {
		width: 680rpx;
		border-radius: 16rpx;
		margin-top: 22rpx;
		background: #ffffff;

		.time-r {
			color: #1d1e26;

			image {
				width: 8rpx;
				height: 16rpx;
				margin-left: 12rpx;
			}
		}

		.img-list {
			display: flex;
			flex-wrap: wrap;
			justify-content: flex-start;
			padding: 0 27rpx;
			box-sizing: border-box;
			padding-bottom: 180rpx;

			.upload-image {
				width: 200rpx;
				height: 200rpx;
				border-radius: 10rpx;
				overflow: hidden;
				margin-right: 10rpx;

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

			.img-list-item {
				// margin-right: 10rpx;
				margin-bottom: 15rpx;
				position: relative;

				.item-image {
					width: 200rpx;
					height: 200rpx;
					border-radius: 10rpx;
					overflow: hidden;

					.img1 {
						width: 200rpx;
						height: 200rpx;
					}

				}

				.img {
					position: absolute;
					right: -12rpx;
					top: -12rpx;
					width: 25rpx;
					height: 25rpx;
				}
			}
		}
	}

	.project-list {
		.list-item {
			width: 680rpx;
			height: 115rpx;
			display: flex;
			align-items: center;
			justify-content: space-between;
			font-size: 30rpx;
			padding: 0 27rpx;
			border-top: 1rpx solid #e9e9e9;
			box-sizing: border-box;

			.item-name {
				width: 500rpx;
				overflow: hidden;
				text-overflow: ellipsis;
				white-space: nowrap;
				font-size: 30rpx;
				color: #000000;
				font-weight: 500;
			}

			.item-img {
				width: 31rpx;
				height: 31rpx;
			}
		}
	}

	.form-btn {
		width: 686rpx;
		height: 94rpx;
		border-radius: 46rpx;
		background-color: #d3a358;
		color: #ffffff;
		font-size: 32rpx;
		display: flex;
		align-items: center;
		justify-content: center;

		position: fixed;
		bottom: 60rpx;
		left: 50%;
		transform: translateX(-50%);
		z-index: 2;
	}

	// 索引栏
	.container {
		display: flex;
		flex-direction: column;
		height: 1200rpx;
		padding: 20rpx 35rpx 30rpx 35rpx;
		overflow: visible;
		background: #f6f8fa;
		position: relative;
		border-radius: 32rpx 32rpx 0 0;
		box-sizing: border-box;
	}

	.popup-close {
		// position: absolute;
		// right: 34rpx;
		// top: 45rpx;
		// z-index: 10;
		display: flex;
		justify-content: flex-end;
		align-items: center;
		height: 70rpx;
		padding-right: 5rpx;
		flex-shrink: 0;
		image {
			width: 38rpx;
			height: 39rpx;
		}
	}

	.airport-list {
		height: calc(100% - 180rpx);
		overflow-y: auto;
	
	}

	.letter-group {
		margin-top: 25rpx;
		margin-bottom: 30rpx;
	}

	.letter-title {
		padding: 0 38rpx;
		font-weight: bold;
		// position: sticky;
		// top: 0;
		z-index: 10;
		color: #000000;
		font-weight: 600;
		font-size: 34rpx;
		margin-bottom: 30rpx;
	}

	.box {
		width: 100%;
		overflow: hidden;
		border-radius: 16rpx;
		padding: 0 0 0 36rpx;
		box-sizing: border-box;
		background: #fff;
	}

	.airport-item {
		width: 100%;
		height: 115rpx;
		box-sizing: border-box;
		background-color: #ffffff;
		touch-action: none;
		font-size: 30rpx;
		display: flex;
		align-items: center;
		justify-content: space-between;
		border-bottom: 1rpx solid #e2e2e2;

		&:last-child {
			border: none;
		}

		.airport-item-image {
			width: 72rpx;
			text-align: center;
			height: 115rpx;
			line-height: 115rpx;

			image {
				width: 11rpx;
				height: 21rpx;
			}
		}
	}

	.airport-item-radio {
		flex: 1;
		display: flex;
		align-items: center;
		overflow: hidden;

		image {
			margin-right: 8rpx;
			margin-top: 5rpx;
		}

		.image-1 {
			width: 29rpx;
			height: 29rpx;
		}

		.image-2 {
			width: 29rpx;
			height: 29rpx;
		}
		.image-3{
			flex: 1;
            white-space: nowrap;
			overflow: hidden;
			text-overflow: ellipsis;
		}
	}

	.action-bar {
		flex-shrink: 0;
		width: 686rpx;
		height: 94rpx;
		border-radius: 46rpx;
		background-color: #d3a358;
		color: #ffffff;
		font-size: 32rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		// position: sticky;
		// bottom: 0;
		z-index: 10;
	}

	.selected-list {
		margin-top: 20rpx;
		padding: 20rpx;
		background-color: #f9f9f9;
		border-radius: 10rpx;
		max-height: 200rpx;
		overflow: auto;
		-webkit-overflow-scrolling: touch;
	}

	.title {
		font-weight: bold;
		margin-bottom: 15rpx;
		position: sticky;
		top: 0;
		background-color: #f9f9f9;
		z-index: 10;
	}

	.selected-items {
		display: flex;
		flex-wrap: wrap;
	}

	.selected-item {
		position: relative;
		background-color: #e6f7ff;
		color: #1890ff;
		padding: 10rpx 20rpx;
		margin: 0 15rpx 15rpx 0;
		border-radius: 30rpx;
		touch-action: none;
	}

	.remove {
		margin-left: 10rpx;
		color: #ff4d4f;
		cursor: pointer;
	}

	.container2 {
		height: 595rpx;
		padding: 50rpx 35rpx 30rpx 35rpx;
		overflow: hidden;
		background: #ffffff;
		border-radius: 32rpx 32rpx 0 0;
		color: #000000;
		display: flex;
		flex-direction: column;

		.text-t {
			flex-shrink: 0;
			position: relative;

			.t-1 {
				flex: 1;
				font-size: 34rpx;
				font-weight: 700;
				margin-right: 37rpx;
			}

			image {
				position: absolute;
				top: 9.5rpx;
				right: 0rpx;
				width: 32rpx;
				height: 33rpx;
			}

		}

		.text-c {
			flex: 1;
			overflow: auto;
			margin-top: 22rpx;
			font-weight: 500;
		}
	}

}
</style>