<template>
	<view>
		<view class="postnatal">

			<!-- 自定义头部 -->
			<!-- <customize-navigation>
				<template v-slot:navbar-content>
					<view class="page-top">
						<image @tap="backHandler" class="btnback" :src="`${$baseUrl}chanjianTool/1001/back.png`">
						</image>
						<view class="page_title">产检提醒</view>
					</view>
				</template>
</customize-navigation> -->
			<view class="postnatal-con">
				<!-- 轮播图 -->
				<swiper class="banner-swiper" :autoplay="true" :circular="true" v-if="bannerList.length > 0">
					<swiper-item v-for="(item, index) in bannerList" :key="index">
						<image class="banner-img" :src="`${item.img}`" mode="aspectFill"
							@click="handleBannerClick(item, index)" />
					</swiper-item>
				</swiper>
				<!-- 孕期信息 -->
				<view class="postnatal-con-info">
					<view class="info-l">
						孕{{ homeInfo.gestationalWeeks }}周
					</view>
					<view class="info-c">
						<image class="info-img" :src="`${$baseUrl}chanjianTool/1001/line.png`"></image>
					</view>
					<view class="info-r">
						预产期：{{ homeInfo.dueDate }}
					</view>
				</view>
				<!-- 按钮 -->
				<!-- <button open-type="openSetting">提醒</button> -->
				<view class="postnatal-con-btn">
					<view class="btn-item" v-for="({ name, imageSrc, type }, index) in btnList" :key="index"
						@click="onBtn(type)">
						<image class="image1" :src="`${imageSrc}`"></image>
						<view class="btn-item-text">
							{{ name }}
						</view>
						<image class="image2" :src="`${$baseUrl}chanjianTool/1001/right.png`"></image>
					</view>
				</view>
				<!-- 产检记录 -->
				<scroll-view class="postnatal-con-record" scroll-y :scroll-top="scrollTop">
					<!-- <view class="postnatal-con-record"> -->
					<view :class="['record-item', `item-${index}`]"
						v-for="({ id, checkupDate, index, pregnancyWeek, status, examinationItems, type }, i) in homeInfo.checkupList"
						@click="onDetails(id, type)" :key="i">
						<image class="add-image" v-if="type === '1'" :src="`${$baseUrl}chanjianTool/1001/bs.png`">
						</image>
						<view class="item-t">
							<view class="item-t-l">
								第{{ index }}次产检
							</view>
							<view class="item-t-r" @click.stop="onEdit(id, checkupDate)">
								<view class="">
									产检时间：{{ checkupDate ? checkupDate : '---' }}
								</view>
								<image class="edit-img" :src="`${$baseUrl}chanjianTool/1001/edit.png`">
								</image>
							</view>
						</view>
						<view class="item-line">

						</view>
						<view class="item-c">
							<view class="item-c-l">
								孕期{{ pregnancyWeek }}周
							</view>
							<view class="">
								<image class="record-img" :src="getSrcUrl(status)"></image>
							</view>
						</view>
						<view class="item-b">
							重点：{{ getProject(examinationItems) }}
						</view>
					</view>
					<!-- </view> -->
				</scroll-view>
			</view>
			<!-- 新增产检 -->
			<view class="postnatal-add" @click="onAdd">
				<image :src="`${$baseUrl}chanjianTool/1001/add.png`"></image>
			</view>

			<!-- 选择提醒弹窗 -->
			<view>
				<!-- 底部弹窗遮罩层 -->
				<view v-if="showPicker" class="picker-layer-mask" @click="close"></view>
				<!-- 弹窗内容区 -->
				<view v-if="showPicker" class="picker-layer-popup">
					<view class="picker-layer-panel">

						<view class="picker-layer-title">
							设置提醒时间
						</view>
						<view class="picker-layer-content">
							<view class="content-item" v-for="(item, index) in options" :key="index"
								:class="{ 'item-active': pickerValue === index }" @click="handleChange(index)">
								{{ item.name }}
							</view>
						</view>

						<view class="picker-layer-bottom">
							<text class="bottom-close btn" @click="close">取消</text>
							<text class="bottom-confirm btn" @click="handleConfirm">确定</text>
						</view>
					</view>
				</view>
			</view>

			<!-- 提示弹窗 -->
			<popup-tip v-if="isTip" type="2" @statusChange="onBabyChange" @close="isTip = false"></popup-tip>

			<!-- 使用封装后的日期选择器组件 -->
			<DatePicker v-model:visible="visible" :default-date="time" @confirm="handleDateConfirm"
				/>
		</view>
	</view>
</template>

<script setup>
import {
	ref,
	getCurrentInstance,
	onMounted,
	nextTick,
	watch
} from 'vue'
import {
	onLoad,
	onShow
} from '@dcloudio/uni-app'
import {
	jump,
	JumpType,
	throttleTap
} from '@/utils/index.js';
import md from '../../md';
import { useUserStore } from "@/stores/user";
import {
	getInfo,
	getUpdate,
	postnatalJSON,
	getWxNotification
} from '../../api/obstetric.js';
// 导入日期选择器组件
import DatePicker from '@/components/DatePicker.vue'
const {
	proxy
} = getCurrentInstance();
const $baseUrl = proxy.$baseUrl;

// 用户信息
const userStore = useUserStore();
const babyId = ref('')

const back_btn = ref('')

const scrollTop = ref(0)

// 是否授权
const isWxNotification = ref(true)

// 提示弹窗
const isTip = ref(false)

// 弹窗控制
const showPicker = ref(false)
// 提醒时间选项
const pickerValue = ref(0) // 当前选中的索引
const selectedValue = ref(0) // 选中的值
const options = [
	{
		name: '每月1日',
		id: 1
	},
	{
		name: '每月15日',
		id: 15
	},
	{
		name: '每月28日',
		id: 28
	}
]

// 时间弹窗控制
const visible = ref(false)

// 时间
const time = ref('')

const isClickClose = ref(false)
// 保存要修改的id
const editId = ref(null)

// 轮播图
const bannerList = ref([])

// 首页信息
const homeInfo = ref({})

// 按钮列表
const btnList = ref([
	{
		name: '提醒',
		imageSrc: `${$baseUrl}chanjianTool/1001/icon1.png`,
		type: 0
	},
	{
		name: '报告单',
		imageSrc: `${$baseUrl}chanjianTool/1001/icon2.png`,
		type: 1
	},
	{
		name: '日历',
		imageSrc: `${$baseUrl}chanjianTool/1001/icon3.png`,
		type: 2
	}
])

// 跳转产检详情页面
const onDetails = (id, type) => {
	// 如果是新增的就不跳转
	if (type === '1') return
	uni.navigateTo({
		url: `/pages/productionDetails/productionDetails?id=${id}`
	})
}
// 拼接检查项目名称
const getProject = (projects) => {
	return projects.map(project => project.itemName).join('、');
}
// 根据状态返回图片
const getSrcUrl = (status) => {
	const imageMap = {
		'pending': `${$baseUrl}chanjianTool/1001/icon4.png`,
		'expired': `${$baseUrl}chanjianTool/1001/icon5.png`,
		'completed': `${$baseUrl}chanjianTool/1001/icon30.png`
	};
	return imageMap[status];

}
// 首页组件逻辑
const backHandler = () => {
	if (!back_btn) {
		uni.navigateBack();
	} else {
		jump({
			type: JumpType.INNER,
			url: `/pages/index/index`
		})
	}
}
// 点击轮播图事件
const handleBannerClick = (item, index) => {
	console.log(item)
	let buttonName = '';
	switch (index) {
		case 0:
			buttonName = '第一张焦点图';
			break;
		case 1:
			buttonName = '第二张焦点图';
			break;
		case 2:
			buttonName = '第三张焦点图';
			break;
		case 3:
			buttonName = '第四张焦点图';
			break;
	}
	md.sensorLogTake({
		xcxClick: "小程序页面点击事件",
		pageName: "产检提醒首页",
		buttonName: buttonName,
	});
	// 跳转
	if (item?.url != "") {
		jump({
			type: item.type,
			url: item.url
		})
	}


}
// 新增体检
const onAdd = () => {
	md.sensorLogTake({
		xcxClick: "小程序页面点击事件",
		pageName: "产检提醒首页",
		buttonName: '添加'
	});
	uni.navigateTo({
		url: '/pages/addPostnatal/addPostnatal'
	})
}
// 按钮点击
const onBtn = (type) => {
	// const items = JSON.stringify(homeInfo.value)
	// type 0 提醒 1  报告单 2 日历
	let buttonName = ''
	switch (type) {
		case 0:
			// 如果授权就不弹出提醒
			showPicker.value = isWxNotification.value ? true : false
			if (showPicker.value) {
				md.sensorPopLogTake({
					xcxPopExposure: "true",
					toolName: "产检提醒",
					popName: "设置提醒时间弹窗"
				});
			}
			buttonName = '提醒'

			break;
		case 1:
			uni.navigateTo({
				url: '/pages/myReportCard/myReportCard'
			})
			buttonName = '报告单'

			break;
		case 2:
			uni.navigateTo({
				url: `/pages/productionCalendar/productionCalendar`
			})
			buttonName = '日历'
			break;
		default:
			break;
	}
	md.sensorLogTake({
		xcxClick: "小程序页面点击事件",
		pageName: "产检提醒首页",
		buttonName: buttonName,
	});

}
// 提醒关闭
const close = (type) => {
	if (type !== 'nonePop') {
		md.sensorPopLogTake({
			xcxPopClick: "true",
			toolName: "产检提醒",
			popName: "设置提醒时间弹窗",
			buttonName: "取消"
		});
	}
	showPicker.value = false;
	
}
// 选择提醒事件
const handleChange = (e) => {
	pickerValue.value = e;
}
// 确认选择
const handleConfirm = () => {
	md.sensorPopLogTake({
		xcxPopClick: "true",
		toolName: "产检提醒",
		popName: "设置提醒时间弹窗",
		buttonName: "确认"
	});
	selectedValue.value = options[pickerValue.value].id;
	console.log(selectedValue.value, homeInfo.value.wxTemplateId, babyId.value)
	close("nonePop");
	// 订阅提醒
	uni.requestSubscribeMessage({
		tmplIds: [homeInfo.value.wxTemplateId],
		success(res) {
			console.log(res)
			getWxNotificationFn(selectedValue.value, homeInfo.value.wxTemplateId, babyId.value)
		},
		fail(res) {
			console.log(res)
		}
	})
}
watch(visible, (newVal) => {
	if (!newVal) {
		if (isClickClose.value) {
			return
		}
		md.sensorPopLogTake({
			xcxPopClick: "true",
			toolName: "产检提醒",
			popName: "选择产检时间弹窗",
			buttonName: "取消"
		});
	}
})
// 编辑时间
const onEdit = (id, newTime) => {
	md.sensorLogTake({
		xcxClick: "小程序页面点击事件",
		pageName: "产检提醒首页",
		buttonName: '选择时间',
	});

	console.log(id, newTime)
	time.value = newTime
	visible.value = true
	editId.value = id
	isClickClose.value = false
	md.sensorPopLogTake({
		xcxPopExposure: "true",
		toolName: "产检提醒",
		popName: "选择产检时间弹窗"
	});
}



// 选择日期回调确认
const handleDateConfirm = (date) => {
	console.log('选择的日期是：', date);
	time.value = date;
	console.log(editId.value, time.value)
	onEditTime()
	isClickClose.value = true
	md.sensorPopLogTake({
		xcxPopClick: "true",
		toolName: "产检提醒",
		popName: "选择产检时间弹窗",
		buttonName: "确认"
	});
}
// 添加计算滚动位置的方法
const scrollToCurrentWeek = async () => {
	// 确保数据已加载
	if (!homeInfo.value || !homeInfo.value.gestationalWeeks || !homeInfo.value.checkupList) return;

	// 找到当前孕周对应的产检项
	const currentItem = homeInfo.value.checkupList.find(
		item => item.pregnancyWeek == homeInfo.value.gestationalWeeks
	);

	if (!currentItem) return;

	// 等待DOM更新
	await nextTick();

	// 创建选择器查询
	const query = uni.createSelectorQuery().in(proxy);
	query.select(`.item-${currentItem.index}`).boundingClientRect();
	query.select('.postnatal-con-record').boundingClientRect();

	query.exec((rects) => {
		if (!rects[0] || !rects[1]) return;

		const [itemRect, containerRect] = rects;

		// 计算元素在容器内的相对位置
		const position = itemRect.top - containerRect.top;

		// 设置滚动位置（增加20px的缓冲距离）
		scrollTop.value = position + 20;
	});
};
// 保存订阅消息
const getWxNotificationFn = async (notificationDate, wxTemplateId, babyId) => {
	const params = {
		type: 1,
		notificationDate,
		wxTemplateId,
		babyId,
	}
	console.log('保存订阅消息参数：', params)
	const { code, message, data, success } = await getWxNotification(params)
	if (success) {
		uni.showToast({
			title: '保存成功',
			icon: 'success',
			duration: 2000
		})
	} else {
		uni.showToast({
			title: message,
			icon: 'none'
		})
	}
	// 获取用户授权信息
	getSettingFn()
}
// 修改产检时间
const onEditTime = async () => {
	const { code, success, message } = await getUpdate({ id: editId.value, checkupDate: time.value })
	if (success) {
		uni.showToast({
			title: '修改成功',
			icon: 'none'
		})
		// 重新获取信息
		getInfoFn()
	} else {
		uni.showToast({
			title: message,
			icon: 'none'
		})
	}
}
// 获取信息接口
const getInfoFn = async () => {
	// 获取信息
	const { code, success, message, data } = await getInfo({ babyId: babyId.value })
	console.log('产检提醒首页获取信息', code, success, message, data)
	if (success) {
		homeInfo.value = data
		uni.setStorageSync('dueDate', data.dueDate)

		// 新增：调用滚动方法
		scrollToCurrentWeek()
	} else {
		uni.showToast({
			title: message,
			icon: "none",
		});

	}


}

// 获取banner图
const postnatalJSONFn = async () => {
	const { success, data, message } = await postnatalJSON()
	if (success) {
		bannerList.value = data.bannerList
	} else {
		uni.showToast({
			title: message,
			icon: "none",
		});
	}
}
//  获取用户授权信息
const getSettingFn = () => {
	wx.getSetting({
		withSubscriptions: true,
		success(res) {
			// console.log(res.authSetting, '授权信息')
			console.log(res.subscriptionsSetting, '订阅信息')
			if (res.subscriptionsSetting.itemSettings) {
				isWxNotification.value = false
				console.log("🚀 ~ success ~ isWxNotification111:", isWxNotification.value)
			} else {
				isWxNotification.value = true
				console.log("🚀 ~ success ~ isWxNotification222:", isWxNotification.value)
			}
		}
	})
}
// 提示弹窗回调
const onBabyChange = () => {
	publicFn()
}
// 公共函数
const publicFn = () => {
	console.log("🚀 ~ onShow ~ userStore:", userStore.babyInfo)
	const babyInfo = userStore.babyInfo
	if (babyInfo && babyInfo.babyStage == 1) {
		isTip.value = false
		babyId.value = userStore.babyInfo?.content?.id
		getSettingFn()
		// 获取banner图
		postnatalJSONFn()
		// 获取信息
		getInfoFn()
	} else {
		isTip.value = true
	}
}
onShow(async () => {
	await userStore.loadBabyInfo()
	console.log('宝宝信息加载完成:', userStore.babyInfo)
	publicFn()
})
onMounted(() => {
	isClickClose.value = false
	md.sensorLogTake({
		xcxPage: "小程序页面浏览事件",
		pageName: "产检提醒首页"
	});
})
</script>

<style lang="less" scoped>
@import "@/common.less";

.postnatal {
	// position: absolute;
	width: 100%;
	height: 100vh;
	background-color: #fdf6eb;
	padding: 0 31rpx 31rpx 31rpx;
	box-sizing: border-box;

	&-con {
		display: flex;
		flex-direction: column;
		height: 100%;

		&-info {
			font-size: 24rpx;
			display: flex;
			align-items: center;
			margin-top: 50rpx;
			font-weight: 500;
			flex-shrink: 0;
			height: 32rpx;

			.info-c {
				width: 2rpx;
				height: 22rpx;
				margin: 0 16rpx;

				.info-img {
					display: block;
					width: 100%;
					height: 100%;
				}
			}
		}

		&-btn {
			height: 86rpx;
			margin-top: 55rpx;
			display: flex;
			justify-content: space-between;
			margin-bottom: 30rpx;
			flex-shrink: 0;

			.btn-item {
				display: flex;
				align-items: center;
				justify-content: center;
				width: 212rpx;
				height: 85rpx;
				background: #ffffff;
				border-radius: 16rpx;
				font-size: 28rpx;

				.image1 {
					width: 44rpx;
					height: 44rpx;
				}

				.btn-item-text {
					margin-left: 6rpx;
					margin-right: 34rpx;
				}

				.image2 {
					width: 9rpx;
					height: 17rpx;
				}
			}
		}

		&-record {
			flex: 1;
			// height: calc(100vh - 650rpx);
			overflow-x: hidden;
			overflow-y: auto;

			.record-item {
				width: 687rpx;
				background-color: #fff;
				margin-bottom: 30rpx;
				border-radius: 24rpx;
				box-sizing: border-box;
				padding: 40rpx 32rpx;
				position: relative;

				.add-image {
					position: absolute;
					left: 0;
					top: 0;
					width: 111rpx;
					height: 30rpx;
				}

				.item-t,
				.item-c {
					display: flex;
					align-items: center;
					justify-content: space-between;
				}

				.item-line {
					width: 100%;
					height: 2rpx;
					background-color: #fcf5ec;
					margin: 20rpx 0;
				}

				.item-t {
					font-size: 24rpx;
					font-weight: 500px;
					color: #000000;

					.item-t-r {
						display: flex;
						align-items: center;
					}
				}

				.edit-img {
					width: 21rpx;
					height: 21rpx;
					margin-left: 14rpx;
				}

				.record-img {
					width: 142rpx;
					height: 35rpx;
				}

				.item-c {
					&-l {
						font-size: 38rpx;
						color: @color-gold-cover;
					}

				}

				.item-b {
					width: 100%;
					white-space: nowrap;
					/* 禁止换行 */
					overflow: hidden;
					/* 超出部分隐藏 */
					text-overflow: ellipsis;
					/* 显示省略号 */
					margin-top: 20rpx;
					color: #6f6d67;
					font-size: 24rpx
				}
			}
		}
	}

	&-add {
		position: fixed;
		right: 31rpx;
		bottom: 230rpx;

		image {
			width: 112rpx;
			height: 113rpx;
		}
	}

	/* 遮罩层样式 */
	.picker-layer-mask {
		position: fixed;
		left: 0;
		right: 0;
		top: 0;
		bottom: 0;
		background: rgba(0, 0, 0, 0.5);
		z-index: 3999;
	}


	.picker-layer-popup {
		position: fixed;
		left: 0;
		right: 0;
		bottom: 0;
		z-index: 4000;
		display: flex;
		flex-direction: column;
		align-items: center;
		animation: picker-layer-up 0.3s;
	}

	@keyframes picker-layer-up {
		from {
			transform: translateY(100%);
		}

		to {
			transform: translateY(0);
		}
	}

	/* 弹窗容器样式 */
	.picker-layer-panel {
		width: 100vw;
		height: 745rpx;
		background: #f6f8fa;
		border-top-left-radius: 24rpx;
		border-top-right-radius: 24rpx;
		overflow: hidden;
		padding: 32rpx;
		box-sizing: border-box;
	}

	.picker-layer-title {
		font-size: 34rpx;
		color: #000000;
		font-weight: bold;
	}

	.picker-layer-content {
		margin-top: 40rpx;
		margin-bottom: 50rpx;

		.content-item {
			width: 100%;
			height: 126rpx;
			border-radius: 16rpx;
			font-size: 28rpx;
			display: flex;
			align-items: center;
			justify-content: center;
			border: 2rpx solid #fff;
			box-sizing: border-box;
			margin-bottom: 20rpx;
			background: #ffffff;
		}

		.item-active {
			background: #fffbed;
			border-color: #d3a358;
		}
	}

	.picker-layer-bottom {
		display: flex;
		justify-content: space-between;
		align-items: center;

		.btn {
			width: 334rpx;
			height: 97rpx;
			display: flex;
			align-items: center;
			justify-content: center;
			border-radius: 48.5rpx;
			font-size: 38rpx;
		}

		.bottom-close {
			color: #d3a358;
			background: #ffffff;
		}

		.bottom-confirm {
			color: #ffffff;
			background: #d3a358;
		}
	}
}

.banner-swiper {
	flex-shrink: 0;
	width: 687rpx;
	height: 177rpx;
	border-radius: 12rpx;
	overflow: hidden;

	.banner-img {
		width: 100%;
		height: 100%;
		// border-radius: 16rpx;
	}
}


.page-top {
	width: 100%;
	display: flex;
	align-items: center;
}

.btnback {
	width: 16rpx;
	height: 29rpx;
	// margin-top: 110rpx;
	// margin-left: 35rpx;
}

.page_title {
	width: 100%;
	font-size: 34rpx;
	font-weight: 500;
	text-align: center;
	color: #1d1e25;
	line-height: 36rpx;
	// margin-top: -46rpx;
	// margin-left: 0rpx;
}
</style>