<template>
	<view class="container">
		<!-- 上半部分：轮播图区域 -->
		<view class="top-section">
			<swiper class="swiper" :indicator-dots="true" :autoplay="true" :interval="3000" :duration="1000"
				:circular="true" indicator-active-color="#1B64F0" indicator-color="rgba(255, 255, 255, 0.6)"
				indicator-class="swiper-indicator" active-class="swiper-indicator-active">
				<swiper-item v-for="(item, index) in swiperList" :key="index" @click="handleBannerClick(item)">
					<view class="swiper-item">
						<image class="swiper-img" :src="item.imageUrl" mode="aspectFill" />
					</view>
				</swiper-item>
			</swiper>
		</view>

		<view class="search-section">
			<view class="search-input-wrapper">
				<image class="search-icon" src="@/static/img/search.png" />
				<input class="search-input" placeholder="请输入要查询的运单号" placeholder-class="placeholder-style"
					@focus="onInputFocus" @blur="onInputBlur" v-model="trackingNumber" />
				<view class="search-btn" @click="handleSearch">
					搜索
				</view>
			</view>
		</view>

		<view class="btn-container">
			<view class="btn-item" @click="handleExpress('1')">
				<image class="button-icon" src="/static/img/index-un-time.png" />
				<view class="button-right">
					<view class="button-title">瑞鲸速达(京东)</view>
					<view class="button-desc">下单当日取件</view>
				</view>
			</view>

			<view class="btn-item" @click="showExpressDialog">
				<image class="button-icon" src="/static/img/index-personal.png" />
				<view class="button-right">
					<view class="button-title">个人寄件</view>
					<view class="button-desc">支持顺丰和京东</view>
				</view>
			</view>
		</view>

		<!-- 使用 u-popup 弹框组件（个人寄件） -->
		<PersonalExpressDialog :visible="showDialog" @update:visible="showDialog = $event"
			@select="handleExpressSelect" />

		<!-- ========== 新增：隐私协议弹框 ========== -->
		<u-popup :show="showPrivacyDialog" mode="center" :round="10" :closeable="false" :safeAreaInsetBottom="false">
			<view class="privacy-dialog">
				<view class="title">温馨提示</view>
				<view class="content">
					欢迎使用本小程序。在使用我们的服务前，请您仔细阅读并同意以下协议：
				</view>
				<view class="protocol-links">
					<text class="link" @click="goToProtocol('user')">《用户协议》</text>
					<text class="and">与</text>
					<text class="link" @click="goToProtocol('privacy')">《隐私协议》</text>
				</view>
				<view class="content">
					点击“同意”即表示您已阅读并同意上述协议的全部条款。
				</view>
				<view class="btn-group">
					<button class="btn reject" @click="onReject">拒绝</button>
					<button class="btn agree" @click="onAgree">同意</button>
				</view>
			</view>
		</u-popup>
		<!-- ========== 新增结束 ========== -->
	</view>
</template>

<script setup>
	import {
		ref,
		onMounted
	} from 'vue'
	import {
		onShow
	} from '@dcloudio/uni-app'
	// 导入 u-popup 弹框组件
	import PersonalExpressDialog from './components/PersonalExpressDialog.vue'
	import {
		bannerList
	} from '../../api/user'
	import {
		checkLoginShowModal,
		quickLogin
	} from "@/utils/util.js";

	// ========== 新增：隐私协议相关常量和方法 ==========
	// 协议远程地址（请替换为实际线上地址）
	const USER_PROTOCOL_URL = 'https://rjsd.mychery.com/user_agreement.html'
	const PRIVACY_PROTOCOL_URL = 'https://rjsd.mychery.com/privacy_policy.html'

	// 控制协议弹框显示
	const showPrivacyDialog = ref(false)

	/**
	 * 显示协议弹框
	 */
	function showPrivacyModal() {
		showPrivacyDialog.value = true
	}

	/**
	 * 关闭弹框
	 */
	function closeDialog() {
		showPrivacyDialog.value = false
	}

	/**
	 * 跳转到协议详情页（使用 WebView）
	 * @param {string} type 'user' 或 'privacy'
	 */
	function goToProtocol(type) {
		const url = type === 'user' ? USER_PROTOCOL_URL : PRIVACY_PROTOCOL_URL
		uni.navigateTo({
			url: `/pages/webView/webView?url=${encodeURIComponent(url)}`
		})
	}

	/**
	 * 用户点击“同意”
	 */
	function onAgree() {
		try {
			uni.setStorageSync('privacyAgreed', true)
			closeDialog()
		} catch (e) {
			console.error('存储失败', e)
			uni.showToast({ title: '操作失败，请重试', icon: 'none' })
		}
	}

	/**
	 * 用户点击“拒绝”
	 */
	function onReject() {
		closeDialog()
		uni.exitMiniProgram({
			success: function() {
				console.log('退出小程序成功');
			},
			fail: function(err) {
				console.log('退出小程序失败', err);
				uni.showToast({
					title: '无法退出，请同意协议',
					icon: 'none'
				})
				// 重新弹出协议框
				setTimeout(() => {
					showPrivacyModal()
				}, 300)
			}
		})
	
	}
	// ========== 新增结束 ==========

	const showDialog = ref(false)

	// 轮播图数据
	const swiperList = ref([])
	
	
	const trackingNumber = ref('')
	const isInputFocused = ref(false)

	onShow(() => {
		getBannerList()

		// ========== 新增：每次显示首页时检查协议状态 ==========
		try {
			const agreed = uni.getStorageSync('privacyAgreed')
			if (!agreed) {
				// 首次使用或未同意，显示协议弹框
				showPrivacyModal()
			}
		} catch (error) {
			console.error('读取存储失败', error)
			showPrivacyModal()
		}
		// ========== 新增结束 ==========
	})

	const getBannerList = () => {
		bannerList().then(res => {
			if (res.code == 200) {
				swiperList.value = res.data
			}
		}, {})
	}

	const showExpressDialog = () => {
		console.log('显示个人寄件弹框')
		showDialog.value = true
	}

	const handleExpressSelect = (company) => {
		// uni.showToast({
		// 	title: `已选择${company}物流`,
		// 	icon: 'success',
		// 	duration: 1500
		// })
	}

	const handleExpress = async (company) => {
		if (!await checkLoginShowModal()) return;
		uni.navigateTo({
			url: `/pages/order/create_order?product=${company}`
		})
	}

	const handleBannerClick = (item) => {
		//  if (!item.linkUrl) {
		//    // uni.showToast({ title: '暂无跳转链接', icon: 'none' });
		//    return;
		//  }
		// if (item.linkUrl.startsWith('http://') || item.linkUrl.startsWith('https://')) {
		// uni.navigateTo({
		//   url: `/pages/webView/webView?url=${encodeURIComponent(item.linkUrl)}`
		// })
		//  } else {
		// uni.showToast({ title: '链接格式不支持', icon: 'none' })
		//  }
	};
	
	
	const onInputFocus = () => {
		isInputFocused.value = true
	}
	
	const onInputBlur = () => {
		isInputFocused.value = false
	}
	
	const handleSearch = async () => {
		if (!await checkLoginShowModal()) return;
		if (!trackingNumber.value.trim()) {
			uni.showToast({
				title: '请输入运单号',
				icon: 'none'
			})
			return
		}
		uni.navigateTo({
			url:'/pages/logistics/index?orderNo=' + trackingNumber.value.trim()
		})
		return
	}
	
</script>

<style lang="scss" scoped>
	.container {
		display: flex;
		flex-direction: column;
		height: 100vh;
		background-color: #F5F7FA;
	}

	.top-section {
		height: 563rpx;
		position: relative;
	}

	.swiper {
		width: 100%;
		height: 100%;
		position: relative;
	}

	.swiper-item {
		width: 100%;
		height: 100%;
		position: relative;
	}

	.swiper-img {
		width: 100%;
		height: 100%;
		object-fit: cover;
	}

	/* 自定义指示点样式 - 通过定位调整位置 */
	/* 方法一：调整整个指示器容器的位置 */
	/* 注意：在不同平台可能需要使用不同的选择器 */
	/* 微信小程序 */
	::v-deep .wx-swiper-dots {
		bottom: 80rpx !important;
		/* 调整指示器容器的位置 */
		display: flex !important;
		justify-content: center !important;
		align-items: center !important;
	}

	/* H5平台 */
	::v-deep .uni-swiper-dots {
		bottom: 80rpx !important;
		/* 调整指示器容器的位置 */
		display: flex !important;
		justify-content: center !important;
		align-items: center !important;
	}

	/* 方法二：直接修改指示点样式，通过调整父容器样式 */
	.swiper-indicator {
		width: 8rpx !important;
		height: 8rpx !important;
		border-radius: 50% !important;
		background: rgba(255, 255, 255, 0.6) !important;
		margin: 0 4rpx !important;
	}

	.swiper-indicator-active {
		width: 32rpx !important;
		height: 8rpx !important;
		background: #1B64F0 !important;
		border-radius: 4rpx !important;
	}

	/* 方法三：如果上述方法都不生效，可以使用绝对定位自定义指示器 */
	.custom-indicator {
		position: absolute;
		left: 0;
		right: 0;
		bottom: 80rpx;
		/* 调整指示器的垂直位置 */
		z-index: 10;
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.custom-indicator-dot {
		width: 8rpx;
		height: 8rpx;
		border-radius: 50%;
		background: rgba(255, 255, 255, 0.6);
		margin: 0 4rpx;
		transition: all 0.3s ease;
	}

	.custom-indicator-dot.active {
		width: 32rpx;
		height: 8rpx;
		background: #1B64F0;
		border-radius: 4rpx;
	}


	/* 搜索区域 */
	.search-section {
		position: relative;
		top: -40rpx;
		width: 100%;
		padding: 0 20rpx;
		display: flex;
		flex-direction: column;
		align-items: center;

		.search-input-wrapper {
			width: 100%;
			height: 88rpx;
			background: #FFFFFF;
			border-radius: 44rpx;
			font-size: 28rpx;
			color: #333;
			border: 4rpx solid #1B64F0;
			padding: 6rpx;
			display: flex;
			justify-content: center;
			justify-items: center;
			align-items: center;

			.search-icon {
				width: 40rpx;
				height: 40rpx;
				margin-left: 18rpx;
			}

			.search-input {
				flex: 1;
				margin-left: 8rpx;
				margin-right: 8rpx;
			}


			.placeholder-style {
				color: #999999;
			}

			.search-btn {
				width: 160rpx;
				height: 76rpx;
				background: #1B64F0;
				border-radius: 38rpx;
				font-weight: 400;
				font-size: 32rpx;
				color: #FFFFFF;
				line-height: 76rpx;
				text-align: center;
				font-style: normal;
			}

		}

	}

	.btn-container {
		display: flex;
		flex-wrap: wrap;
		justify-content: space-between;
		padding: 0rpx 20rpx;

		.btn-item {
			width: 339rpx;
			height: 172rpx;
			background: #FFFFFF;
			box-shadow: 0rpx 4rpx 16rpx 0rpx rgba(27, 100, 240, 0.08), 0rpx 0rpx 8rpx 0rpx rgba(27, 100, 240, 0.08);
			border-radius: 32rpx;
			border: 2rpx solid #FFFFFF;
			display: flex;
			justify-content: center;
			align-items: center;
			padding: 20rpx 0rpx 20rpx 20rpx;
			margin-bottom: 32rpx;

			.button-icon {
				width: 88rpx;
				height: 88rpx;
			}

			.button-right {
				display: flex;
				flex-direction: column;
				flex: 1;
				margin-left: 16rpx;

				.button-title {
					height: 48rpx;
					line-height: 48rpx;
					font-size: 28rpx;
					font-weight: bold;
					color: #333;
					flex-shrink: 0;
				}

				.button-desc {
					height: 44rpx;
					line-height: 44rpx;
					font-size: 24rpx;
					color: #666;
					margin-top: 8rpx;
				}
			}
		}


	}

	.privacy-dialog {
		width: 600rpx;
		padding: 40rpx 30rpx;
		background-color: #fff;
		border-radius: 20rpx;
		box-sizing: border-box;

		.title {
			font-size: 36rpx;
			font-weight: bold;
			text-align: center;
			margin-bottom: 30rpx;
			color: #333;
		}

		.content {
			font-size: 28rpx;
			color: #666;
			line-height: 1.6;
			margin-bottom: 20rpx;
		}

		.protocol-links {
			display: flex;
			align-items: center;
			justify-content: center;
			margin: 20rpx 0;
			font-size: 30rpx;

			.link {
				color: #1B64F0;
				// text-decoration: underline;
				padding: 0 10rpx;
			}

			.and {
				color: #666;
			}
		}

		.btn-group {
			display: flex;
			justify-content: space-between;
			margin-top: 40rpx;

			.btn {
				flex: 1;
				height: 80rpx;
				line-height: 80rpx;
				text-align: center;
				border-radius: 40rpx;
				font-size: 30rpx;
				margin: 0 15rpx;

				&.reject {
					background-color: #f5f5f5;
					color: #999;
					border: 1px solid #ddd;
				}

				&.agree {
					background-color: #1B64F0;
					color: #fff;
					border: none;
				}
			}
		}
	}
</style>