<template>
	<view class="traceability-tour-container">
		<view class="top-box">
			<view class="nav-box">
				<image class="btnback" :src="$baseUrl + 'sign-up/backBtn.png'" mode="aspectFit" @click="handleGoBack" />
				<view class="page_title">{{ activityInfo?.activityTitle }}</view>
			</view>
		</view>
		<!-- 默认图 enable活动状态 -->
		<view v-if="!activityInfo.enable" class="content-image">
			<view v-for="(item, index) in activityInfo.defaultPicList" :key="index" class="img-box">
				<image :src="item" mode="widthFix" />
			</view>
		</view>
		<!-- 活动状态为其他 -->
		<view v-else>
			<!-- 须知 -->
			<image :src="$baseUrl + 'sign-up/notice.png'" alt="活动须知" class="rules" mode="aspectFit"
				@click="ruleClick" />
			<!-- 主图 -->
			<view class="content-image">
				<view v-for="(item, index) in activityInfo.mainPicList" :key="index" class="img-box">
					<image :src="item" mode="widthFix" />
				</view>
			</view>
			<!-- 底部按钮 立即报名 报名成功 立即升级-->
			<!-- signupState: 是否报过名
		gradeQualified: 等级是否满足 -->
			<!-- 用户未报名 -->
			<view v-if="!activityInfo.signupState">
				<!-- 报名未开始 -->
				<view v-if="Date.now() < new Date(activityInfo.signupStartTime).getTime()" class="footer">
					<view class="button-footer">
						<image class="image-bg" :src="$baseUrl + 'sign-up/signup.png'" mode="aspectFit" />
						<view class="text">
							{{ datePart }}报名开启
						</view>
					</view>
				</view>
				<!-- 报名已结束 -->
				<view v-else-if="Date.now() > new Date(activityInfo.signupEndTime).getTime()" class="footer">
					<view class="button-footer">
						<image class="image-bg" :src="$baseUrl + 'sign-up/signup.png'" mode="aspectFit" />
						<image class="image-gary" :src="$baseUrl + 'sign-up/gray.png'" mode="aspectFit" />
						<view class="text text-gray">
							已结束
						</view>
					</view>
				</view>
				<!-- 报名已开始 -->
				<view v-else>
					<!-- 用户等级符合“配置等级” -->
					<view v-if="activityInfo.gradeQualified" class="footer">
						<!-- 已“配置积分” -->
						<view v-if="activityInfo.costPoint">
							<!-- 用户积分符合“配置积分” -->
							<view v-if="activityInfo.hasEnoughPoints" class="footer">
								<view class="button-footer" @click="onClickButtonFooterJoin(1)">
									<image class="image-bg" :src="$baseUrl + 'sign-up/signup.png'" mode="aspectFit" />
									<view class="text">
										立即报名
									</view>
									<view class="tips">
										报名需消耗{{ activityInfo.costPoint }}积分
									</view>
								</view>
							</view>
							<!-- 用户积分不符合“配置积分” -->
							<view v-else class="footer">
								<view class="button-footer">
									<image class="image-bg" :src="$baseUrl + 'sign-up/signup.png'" mode="aspectFit" />
									<image class="image-gary" :src="$baseUrl + 'sign-up/gray.png'" mode="aspectFit" />
									<view class="text text-gray">
										会员积分不足
									</view>
									<view class="tips">
										报名需消耗{{ activityInfo.costPoint }}积分
									</view>
								</view>
							</view>
						</view>
						<!-- 没有“配置积分” -->
						<view v-else class="footer">
							<view class="button-footer" @click="onClickButtonFooterJoin(0)">
								<image class="image-bg" :src="$baseUrl + 'sign-up/signup.png'" mode="aspectFit" />
								<view class="text">
									立即报名
								</view>
							</view>
						</view>
					</view>
					<!-- 用户等级不符合“配置等级” -->
					<view v-else class="footer">
						<view class="button-footer">
							<image class="image-bg" :src="$baseUrl + 'sign-up/signup.png'" mode="aspectFit" />
							<image class="image-gary" :src="$baseUrl + 'sign-up/gray.png'" mode="aspectFit" />
							<view class="text text-gray">
								会员等级不足
							</view>
							<view class="tips">
								{{ activityInfo.gradeList.join('、') }}可报名
							</view>
						</view>
					</view>
				</view>
			</view>
			<!-- 用户已报名 -->
			<view v-else>
				<!-- 已到达（大于）配置“入选公布时间 -->
				<!-- <view v-if="Date.now() > new Date(activityInfo.announcementTime ).getTime()" class="footer"> -->
				<view v-if="activityInfo.prized !== -1" class="footer">
					<!-- 当前用户已入选 -->
					<view v-if="activityInfo.prized" class="footer">
						<view class="button-footer" @click="onClickButtonFooterView(0)">
							<image class="image-bg" :src="$baseUrl + 'sign-up/signup.png'" mode="aspectFit" />
							<view class="text">
								查看入选信息
							</view>
						</view>
					</view>
					<!-- 当前用户未入选 -->
					<view v-else class="footer">
						<view class="button-footer" @click="onClickButtonFooterView(1)">
							<image class="image-bg" :src="$baseUrl + 'sign-up/signup.png'" mode="aspectFit" />
							<view class="text">
								未入选
							</view>
						</view>
					</view>
				</view>
				<!-- 未到达（大于）配置“入选公布时间 -->
				<view v-else class="footer">
					<view class="button-footer" @click="onClickButtonFooterView(2)">
						<image class="image-bg" :src="$baseUrl + 'sign-up/signup.png'" mode="aspectFit" />
						<view class="text">
							已报名
						</view>
					</view>
				</view>
			</view>
		</view>
		<!-- 活动规则 -->
		<uni-popup ref="rulePopup" :mask-click="false" type="center" border-radius="38rpx" background-color="#FFFFFF">
			<view class="container">
				<view class="text-title">
					<view class="title">
						活动须知
					</view>
				</view>
				<view class="text-content">
					<p v-for="item in rulesList" :key="item">{{ item }}</p>
				</view>
				<image :src="$baseUrl + 'sign-up/close.png'" class="close" @click="closeClick" />
			</view>
		</uni-popup>

		<!-- 查询结果弹窗 -->
		<ResultDialog ref="resultDialogRef" :activityInfo="activityInfo" @go-to-sign="goToSign('view')"
			@go-to-more="goToMore" />
		<!-- 活动已结束，报名失败 -->
		<RegisterDialog ref="registerDialogRef" :textValue="textValue" :btnValue="btnValue" @go-to-more="goToMore" />
		<!-- 活动协议 -->
		<NoticeDialog ref="noticeDialogRef" :agreement="agreement" @go-to-sign="(val) => goToSign('add', val)" />
	</view>
</template>

<script setup>
import { ref, computed } from 'vue'
import { onLoad, onShow, onShareAppMessage } from '@dcloudio/uni-app'
import { activityDetailApi } from '@/api/momclub/index.js';
import NoticeDialog from './component/noticeDialog.vue'
import ResultDialog from './component/resultDialog.vue'
import RegisterDialog from './component/registerDialog.vue'
import md from "../../md.js";
import { useUserStore } from "@/stores/user";
const userStore = useUserStore();

//存储活动信息等
const activityInfo = ref({
	activityId: "",
	enable: false,
	activityTitle: "",
	defaultPicList: [],
	mainPicList: [],
	activityNotice: "",
	gradeList: [],
	gradeQualified: false, //是否符合等级
	costPoint: 0,
	hasEnoughPoints: false,
	contactQRCode: "",
	activityStartTime: "",
	activityEndTime: "",
	signupStartTime: "",
	signupEndTime: "",
	signupState: 0,
	announcementTime: "",//公布时间
	prized: -1,
	sharePic: "",
	shareTitle: "",
	addressList: []
})
//路由参数
const query = ref()
//规则弹窗状态
const rulePopup = ref(null)
// 已报名弹窗ref
const resultDialogRef = ref(null)
// 报名失败弹窗ref
const registerDialogRef = ref(null)
// 须知弹窗ref
const noticeDialogRef = ref(null)
const agreement = ref(false)
const isShowSignUp = ref(false)
//规则列
const rulesList = computed(() => {
	if (activityInfo.value.activityNotice) {
		return activityInfo.value.activityNotice?.split('\n')
	} else {
		return []
	}
})
const ruleClick = () => {
	rulePopup.value?.open()
}
// 返回上一页
const handleGoBack = () => {
	// 检查是否有上一页
	const pages = getCurrentPages()
	if (pages.length > 1) {
		// 有上一页，直接返回上一页（收藏状态已在更新时同步）
		uni.navigateBack()
	} else {
		// 没有上一页，跳转到集合页
		uni.redirectTo({
			url: `/subPackages/momclub/actList`
		})
	}
}
//立即报名
const onClickButtonFooterJoin = (type) => {
	md.sensorSignTake({
		signClick: "true",
		page_name: activityInfo.value.activityTitle || '',
		activity_code: activityInfo.value.activityId || '',
		button_name: type === 0 ? "立即报名" : `立即报名(报名需消耗${activityInfo.value.costPoint}积分)`,
		crmid: uni.getStorageSync('memberId'),
		click_time: new Date().getTime(),
	});
	noticeDialogRef.value?.open()
}
// 已报名
const onClickButtonFooterView = (type) => {
	md.sensorSignTake({
		signClick: "true",
		page_name: activityInfo.value.activityTitle || '',
		activity_code: activityInfo.value.activityId || '',
		button_name: type === 0 ? "查看入选信息" : type === 1 ? "未入选" : "已报名",
		crmid: uni.getStorageSync('memberId'),
		click_time: new Date().getTime()
	});
	resultDialogRef.value?.open()
}

const closeClick = () => {
	rulePopup.value.close()  //活动规则
}
//打开报名信息页面
const goToSign = (type, val) => {
	let urlStr = type === 'add' ? `&agreement=${val}` : `&isView=${1}`
	uni.navigateTo({
		url: `/subPackages/momclub/sign?&activityId=${query.value.activityId}${urlStr}`
	})
}
//查看更多其他活动
const goToMore = () => {
	// 检查是否有上一页
	const pages = getCurrentPages()
	if (pages.length > 1) {
		// 有上一页，直接返回上一页（收藏状态已在更新时同步）
		uni.navigateBack()
	} else {
		// 没有上一页，跳转到集合页
		uni.redirectTo({
			url: `/subPackages/momclub/actList`
		})
	}
}
const datePart = computed(() => {
	// 分割日期部分
	const dateStr = activityInfo.value.signupStartTime?.split(' ')[0]; // "2025-10-03"
	const [year, month, day] = dateStr?.split('-');

	const result = `${parseInt(month)}月${parseInt(day)}日`;
	return result; // 输出: 10月3日
})

const errorTip = () => {
	return uni.showToast({
		title: '缺少地址栏参数',
		icon: "none",
	});
}
const textValue = ref('')
const btnValue = ref('')
//获取活动信息并赋值
const getInfo = async () => {
	if (query.value.activityId) {
		try {
			const res = await activityDetailApi({ activityId: query.value.activityId })
			if (res.success) {
				activityInfo.value = res.data
				if (!activityInfo.value.enable) {
					// 活动已失效
					setTimeout(() => {
						console.log(registerDialogRef.value, '已失效----')
						textValue.value = "活动已结束"
						btnValue.value = "查看更多其他活动"
						registerDialogRef.value?.open()
					}, 50)
				}
				if (activityInfo.value.prized === 1 || (activityInfo.value.prized === -1 && isShowSignUp.value == true)) {
					// 成功入选
					setTimeout(() => {
						resultDialogRef.value?.open()
						isShowSignUp.value = false
					}, 50)
				}
			} else {
				console.log(res, 'ressss')
				if (res.code === "30002003") {
					//非会员 未登录，跳转到登录注册页面
					uni.navigateTo({
						url: `/pages/activity/register`
					})
				} else if (res.code === "30002002") {
					//活动不存在，请查看其它活动
					setTimeout(() => {
						textValue.value = "活动不存在"
						btnValue.value = "查看更多其他活动"
						registerDialogRef.value?.open()
					}, 50)
				} else if (res.code === "30003001") {
					//异常情况，未获取到活动资源
					uni.navigateTo({
						url: `/subPackages/momclub/error`
					})
				} else {
					return uni.showToast({
						title: res.message || '数据异常',
						icon: "none",
					});
				}
			}
		} catch (error) {
			console.log('err', error)
		}
	} else {
		errorTip()

	}
}
const init = () => {
	console.log(query.value.activityId,'query.value.activityId----')
	if (query.value.activityId) {
		getInfo()
	} else {
		errorTip()
	}
}
onLoad((options) => {
	md.sensorSignTake({
		bmhdPage: "true",
		page_name: activityInfo.value?.activityTitle || '',
		activity_code: options?.activityId || activityInfo.value?.activityId || '',
		page_view_time: new Date().getTime(),
		crmid: uni.getStorageSync('memberId')
	});
	// 启用分享菜单（仅限分享给好友，禁用朋友圈）
	uni.showShareMenu({
		withShareTicket: true,
		menus: ['shareAppMessage'] // 微信小程序支持分享到朋友圈
	});
	query.value = options
})

onShow(async()=> {
	console.log(query.value,'onShow')
	if (uni.getStorageSync('needRefresh')) {
	    uni.removeStorageSync('needRefresh');
		isShowSignUp.value = true
	}
	if(query.value.share == 'true'){
		await userStore.loadUserInfo()
		if (userStore.userInfo?.memberId !== "not_login") {
			//非会员 未登录，跳转到登录注册页面
			uni.navigateTo({
				url: `/pages/activity/register`
			})
			return
		}
	}
	init();
})
// 自定义分享内容
onShareAppMessage(() => {
	return {
		title: activityInfo.value.shareTitle || '星妈会活动',
		path: `/subPackages/momclub/index?activityId=${query.value.activityId}&share=true`, // 分享页面路径
		imageUrl: activityInfo.value.sharePic,  // 分享图片
		success: (res) => {
			console.log('分享成功', res);
			uni.showToast({
				title: '分享成功',
				icon: 'success'
			});
		},
		fail: (err) => {
			console.log('分享失败', err);
		}
	};
})
</script>

<style lang="less" scoped>
// @import "@/common.less";
.traceability-tour-container {
	min-height: 100vh;
	background-color: #f5f5f5;
	position: relative;
	overflow: scroll;

	.top-box {
		width: 100%;
		height: 177rpx;
		position: fixed;
		z-index: 999;
		background-color: #FFFFFF;

		.nav-box {
			width: 100%;
			position: fixed;
			top: 100rpx;
			left: 30rpx;
			display: flex;
			align-items: center;

			// 返回按钮样式
			.btnback {
				width: 20rpx;
				height: 34rpx;
			}

			.page_title {
				width: calc(100% - 150rpx);
				font-size: 32rpx;
				font-weight: 500;
				text-align: center;
				line-height: 60rpx;
			}
		}
	}

	.content-image {
		margin-top: 177rpx;
		width: 100%;
		height: 100%;
		text-align: center;
		position: absolute;

		.img-box {
			width: 100%;

			image {
				width: 100%;
				display: block;
			}
		}
	}

	.rules {
		position: fixed;
		top: 287rpx;
		right: 0rpx;
		width: 40rpx;
		height: 146rpx;
		z-index: 99;
	}

	.container {
		max-height: 840rpx;
		min-height: 320rpx;
		width: calc(100vw - 150rpx);
		padding: 40rpx 28rpx 70rpx;
		background: linear-gradient(180.16deg, #FFE9C5 -4.61%, #FFFFFF 26.4%);
		border-radius: 38rpx;
		position: relative;
		box-sizing: border-box;

		.text-title {
			.title {
				flex: 1;
				text-align: center;
				font-weight: 600;
				font-size: 36rpx;
				color: #D3A458;
			}
		}

		.text-content {
			font-size: 24rpx;
			overflow: auto;
			margin-top: 40rpx;
			text-align: justify;
			max-height: 655rpx;
		}

		.close {
			position: absolute;
			bottom: -134rpx;
			left: 50%;
			transform: translateX(-50%);
			width: 56rpx;
			height: 56rpx;
		}
	}


	.footer {
		.button-footer {
			width: 582rpx;
			height: 100rpx;
			position: fixed;
			bottom: 70rpx;
			left: 50%;
			transform: translateX(-50%);
			text-align: center;

			.image-bg {
				width: 100%;
				height: 132rpx;
			}

			.image-gary {
				width: 100%;
				height: 100%;
				position: absolute;
				left: 0;
			}

			.text {
				width: 100%;
				font-size: 38rpx;
				line-height: 100rpx;
				position: absolute;
				top: 0;
				left: 50%;
				transform: translateX(-50%);
				color: transparent;
				background-image: linear-gradient(180deg, #B27C1E 14%, #4C350D 90%);
				-webkit-background-clip: text;
				background-clip: text;
			}

			.text-gray {
				opacity: 0.4;
			}

			.tips {
				height: 36rpx;
				line-height: 36rpx;
				position: absolute;
				font-size: 24rpx;
				top: -20rpx;
				right: 0rpx;
				padding: 0rpx 13rpx;
				border-radius: 26rpx 22rpx 22rpx 7rpx;
				color: #FFFFFF;
				background: linear-gradient(90deg, #B27C1E 0%, #D3A358 100%);
				text-align: center;

			}
		}


	}
}
</style>
