<template>
	<view v-if="template">
		<s-layout title="首页" navbar="custom" tabbar="/pages/index/index" :bgStyle="template.style?.background"
			:navbarStyle="template.style?.navbar" onShareAppMessage :showFloatButton="true" bgColor="#fcc74e">


			<!-- 注册送优惠券列表 -->
			<su-popup :show="registerShow == true" type="center" round="10" :isMaskClick="false" backgroundColor="none"
				@close="registerShow = false" @open="registerShow = true">
				<view class="popup">
					<view class="registerBox">
						<view class="regListBox" v-for="(item, index) in registerList" :key="index">
							<view class="reItem">
								<view>
									<view style="font-size: 36rpx;font-weight: 900;color: #fff;line-height: 40rpx;">
										{{item.amount}}
									</view>
									<view style="font-size: 24rpx;color: #fff;line-height: 34rpx;margin-top: 10rpx;">
										{{ item.amount_text }}
									</view>
								</view>
								<view
									style="font-size: 26rpx;font-weight: bold;color: #fff;line-height: 36rpx;margin-left: 10rpx;">
									{{item.type_text}}
								</view>
							</view>
						</view>
					</view>

					<view class="texbut" @click="newReceiveCoupon()">

					</view>

					<view style="margin: 0 auto;position: absolute;bottom: -90rpx;">
						<image style="width: 50rpx;height: 50rpx;"
							src="https://mall.jiangxiaoxian.hschool.com.cn/registerCancel.png" mode="aspectFill"
							@click="registerShow = false"></image>
					</view>
				</view>
			</su-popup>

			<!-- 登录弹框 -->
			<su-popup :show="showLogin == true" type="center" round="10" @close="showLogin = false"
				@open="showLogin = true">
				<view class="popupLogin">

					<button class="texbut" open-type="getPhoneNumber" @getphonenumber="getPhoneNumber">
						<!-- <image style="width: 100%;height: 136rpx;" src="https://mall.jiangxiaoxian.hschool.com.cn/loginBtnTwo.png"></image> -->
						<!-- 授权登录 -->
					</button>
				</view>
				<view style="margin: 0 auto;position: absolute;bottom: -90rpx;width: 100%;text-align: center;">
					<image style="width: 50rpx;height: 50rpx;"
						src="https://mall.jiangxiaoxian.hschool.com.cn/registerCancel.png" mode="aspectFill"
						@click="showLogin = false"></image>
				</view>
			</su-popup>

		</s-layout>
	</view>
</template>

<script setup>
	import {
		computed,
		ref,
		reactive,
	} from 'vue';
	import {
		onLoad,
		onShow,
		onPageScroll,
		onPullDownRefresh
	} from '@dcloudio/uni-app';
	import sheep from '@/sheep';
	import $share from '@/sheep/platform/share';
	import {
		consignee,
		mobile,
		address,
		region
	} from '@/sheep/validate/form';
	import third from '@/sheep/api/third';

	const isLogin = computed(() => sheep.$store('user').isLogin);
	const showLogin = ref(false);
	const iv = ref('');
	const wxCode = ref('');
	const encryptedData = ref('');
	const urlE = ref('')

	// 打开登录的弹框
	// function toLogin() {
	// 	console.log('toLogin——打开登录的弹框：', showLogin.value);
	// 	showLogin.value = true;
	// 	console.log('showLogin', showLogin.value);
	// }
	// 关闭登录弹框
	function closeLogin() {
		console.log('closeLogin');
		showLogin.value = false;
	}
	// 打开登录的弹框
	function openLogin() {
		console.log('openLogin');
		showLogin.value = true;
	}
	// 使用微信手机号
	async function getPhoneNumber(e) {
		console.log('获取手机号', e, e.detail.errMsg);
		if (e.detail.errMsg !== 'getPhoneNumber:ok') {} else {
			encryptedData.value = e.detail.encryptedData // 用于解密
			iv.value = e.detail.iv // 用于解密
			getCode()
			//    let result = await sheep.$platform.useProvider().bindUserPhoneNumber(e.detail);
			// console.log('result', result);
			//    if (result) {
			//      sheep.$store('user').getInfo();
			//      // closeAuthModal();
			//   closeLogin();
			//    }
		}
	}
	// 获取code和sessionId
	function getCode() {
		uni.login({
			provider: 'weixin',
			success: (res) => {
				wxCode.value = res.code
				// loginResult.value = res
				// getSessionId();
				Login();
			}
		})
	}
	// 登录接口
	function Login() {
		const session_id = uni.getStorageSync('sessionId')
		console.log('session_id', session_id);
		return new Promise(async (resolve, reject) => {
			const {
				code
			} = await third.wechat.wxLogin({
				platform: 'miniProgram',
				payload: encodeURIComponent(
					JSON.stringify({
						sessionId: session_id,
						iv: iv.value,
						encryptedData: encryptedData.value,
						code: wxCode.code,
					}),
				),
			});
			if (code === 1) {
				resolve(true);
				showLogin.value = false;
				console.log('登录成功后的跳转路径_urlE:',urlE.value);
				// toPage(urlE.value);
				if(newCoupon.value == true) {
					newReceiveCoupon();
				}
			}
			resolve(false);
		});
	}


	function getAreaCity() {
		// if (_.isEmpty(uni.getStorageSync('areaCity'))) {
		sheep.$api.rent.getCity().then((res) => {
			if (res.code === 1) {
				uni.setStorageSync('areaCity', res.data);
			}
		});
		// }
	};

	function getTag() {
		// if (_.isEmpty(uni.getStorageSync('areaCity'))) {
		sheep.$api.rent.tagsList().then((res) => {
			if (res.code === 1) {
				uni.setStorageSync('tagList', res.data.list);
			}
		});
		// }
	};

	function getType() {
		// if (_.isEmpty(uni.getStorageSync('areaCity'))) {
		sheep.$api.rent.listType().then((res) => {
			if (res.code === 1) {
				uni.setStorageSync('typeList', res.data);
			}
		});
		// }
	};


	const template = computed(() => sheep.$store('app').template?.home);
	// const isLogin = computed(() => sheep.$store('user').isLogin);
	const qualification = ref(false);
	const registerShow = ref(false); //注册获取优惠券弹框
	const registerList = ref([]);
	const registerNum = ref(0);

	const state = reactive({
		showRegion: false,
		model: {
			consignee: '',
			mobile: '',
			address: '',
			is_default: false,
			region: '',
		},
		rules: {
			consignee,
			mobile,
			address,
			region,
		},
	});

	const getAreaData = () => {
		if (_.isEmpty(uni.getStorageSync('areaData'))) {
			sheep.$api.data.area().then((res) => {
				if (res.code === 1) {
					uni.setStorageSync('areaData', res.data);
				}
			});
		}
	};



	const proCity = ref('')

	const onRegionConfirm = (e) => {
		console.log('onRegionConfirm', e);

		state.model = {
			...state.model,
			...e,
		};

		if (state.model.province_name == state.model.city_name) {
			proCity.value = state.model.province_name
		} else {
			// proCity.value = state.model.province_name + " " + state.model.city_name
			proCity.value = state.model.province_name + state.model.city_name
		}

		// proCity.value = state.model.province_name + " " + state.model.city_name

		console.log('onRegionConfirm33', state.model, proCity.value);
		listQuery.value.province = state.model.province_id
		listQuery.value.city = state.model.city_id;
		listQuery.value.page = 1;
		rentList.value = [];
		getList()
		state.showRegion = false;
	};

	const listQuery = ref({
		page: 1,
		limit: 10,
		addrLatitude: null,
		addrLongitude: null,
		address: null,
		address1: null,
		categoryId: null,
		tags: '',
		cate_ids: '',
		area: null,
		city: null,
		province: null,
		district: null,
		keywords: null,

		// district: '',
	})



	onLoad((options) => {
		getAreaCity();
		
		getBanner();
		getScoreInfo();

		// #ifdef MP
		// 小程序识别二维码
		if (options.scene) {
			const sceneParams = decodeURIComponent(options.scene).split('=');
			options[sceneParams[0]] = sceneParams[1];
		}
		// #endif

		// 预览模板
		if (options.templateId) {
			sheep.$store('app').init(options.templateId);
		}

		// 解析分享信息
		if (options.spm) {
			$share.decryptSpm(options.spm);
		}

		// 进入指定页面(完整页面路径)
		if (options.page) {
			sheep.$router.go(decodeURIComponent(options.page));
		}
	});

	onShow(() => {
		getList();
		// getScoreInfo();
	})

	function getScoreInfo() {
		sheep.$api.coupon.registerCoupon().then((res) => {
			if (res.code == 1) {
				console.log('res-registerCoupon:', res);
				registerList.value = res.data.data;
				registerNum.value = res.data.total
				if (registerNum.value != 0) {
					registerShow.value = true;
					// if(registerNum.value > 3){
					// }else {
					// }
				} else {
					registerShow.value = false;
				}
				console.log('新用户', registerShow.value);
			} else {
				console.log('非新用户');
				sheep.$helper.toast(res.msg);
			}
		})
	}

	const newCoupon = ref(false);
	function newReceiveCoupon() {
		if (isLogin.value == true) {
			newCoupon.value = false;
			sheep.$api.coupon.registerCouponReceive().then((res) => {
				if (res.code == 1) {
					console.log('registerCouponReceive:', res);
					sheep.$helper.toast(res.msg);
					registerShow.value = false;
					setTimeout(function() {
						uni.switchTab({
							url: '/pages/index/category'
						})
					}, 500);
				} else {
					sheep.$helper.toast(res.msg);
					registerShow.value = false;
				}
			})
		} else {
			showLogin.value = true;
			newCoupon.value = true;
			// sheep.$helper.toast('请先登录');
			// setTimeout(function() {
			// 	uni.switchTab({
			// 		url: '/pages/index/user'
			// 	})
			// }, 1000);
		}


	}

	//轮播图跳转
	function swiperJump(item) {
		console.log('轮播图跳转事件：', item.url);
		const tabBarPages = [
			// '/pages/index/index',
			'/pages/index/cart',
			'/pages/index/category',
			'/pages/index/user'
		];
		console.log('tabbarsList：', tabBarPages);
		if (item.type == "in") {
			console.log('跳进内页');
			if (tabBarPages.includes(item.url)) {
				console.log('导航页');
				uni.switchTab({
					url: item.url,
				})
			} else {
				uni.navigateTo({
					url: item.url,
				})
			}
		}
	}

	// 下拉刷新
	onPullDownRefresh(() => {
		sheep.$store('app').init();
		setTimeout(function() {
			uni.stopPullDownRefresh();
		}, 800);
		rentList.value = [];
		state.model.city_name = '';
		state.model.province_name = '';
		state.currentCityIndex = [0, 0];
		getList();
	});

	onPageScroll(() => {});

	const bannerList = ref([])
	async function getBanner() {
		const res = await sheep.$api.home.homeBanner({});
		console.log('banner', res);
		if (res.code == 1) {
			bannerList.value = res.data.list
			console.log('bannerList', bannerList.value);
		}

	}


	const toPage = (e) => {
		uni.navigateTo({
			url: e
		})
		// if (isLogin.value == true) {
		// 	uni.navigateTo({
		// 		url: e
		// 	})
		// } else {
		// 	console.log('打开登录的弹框_showLogin：', showLogin.value,e);
		// 	showLogin.value = true;
		// 	urlE.value = e;
		// 	console.log('打开登录的弹框_urlE：', urlE.value);
		// }
	}

	const toTabb = (e) => {
		uni.switchTab({
			url: e,
		})
	}

	const rentList = ref([]);
	const rentCount = ref(0);
	const homrS = ref(false)
	//招租列表
	async function getList() {
		const res = await sheep.$api.rent.rentlist({
			keywords: listQuery.value.keywords,
			page: listQuery.value.page,
			limit: 10,
			cate_ids: listQuery.value.cate_ids,
			order: 'normal',
			status: 1,
			recommend: 1,
			province: listQuery.value.province,
			city: listQuery.value.city,

		});
		console.log('getList', res);

		if (res.data && res.data.list) {
			// rentList.value = res.data.list;
			// rentCount.value = res.data.count
			rentList.value = [...rentList.value, ...res.data.list];
			rentCount.value = res.data.count;

			// Safely process each item
			rentList.value = rentList.value.map(item => {
				// Create a new object with all properties from the original item
				const newItem = {
					...item
				};

				// Only process release_time_text if it exists
				if (newItem.release_time_text) {
					newItem.release_time_text = newItem.release_time_text.substring(0, 10);
				}

				return newItem;
			});
		} else {
			// Handle case where data is not in expected format
			rentList.value = [];
		}

		// rentList.value = res.data.list;
		// for(let i=0;i<rentList.value.length;i++){
		// 	rentList.value[i].release_time_text = rentList.value[i].release_time_text.substring(0, 10)
		// }
		console.log('getList', rentList.value);
	}

	//加载更多
	function onScrolltolower() {
		if (rentList.value.length < rentCount.value) {
			listQuery.value.page += 1;
			getList();
		}
	}
	//下拉刷新
	function onS() {
		homrS.value = true
		listQuery.value.keywords = '';
		listQuery.value.cate_ids = '';
		listQuery.value.province = '';
		state.model.city_name = '';
		listQuery.value.city = '';
		state.currentCityIndex = [0, 0];
		uni.showLoading({
			title: '加载中...'
		});
		resetLists();

		setTimeout(() => {
			homrS.value = false;
			uni.hideLoading();
			uni.stopPullDownRefresh();
		}, 2000)
	}
	// 重置列表
	function resetLists() {
		// listQuery.value.keywords = ''
		console.log('listQuery.value.keywords', listQuery.value.keywords);
		listQuery.value.page = 1;
		rentList.value = [];
		getList();
	}

	// 隐藏原生tabBar
	uni.hideTabBar({
		fail: () => {},
	});
</script>

<style lang="scss" scoped>
	.search-result {
		padding-top: 10px;
		padding-bottom: 20px;
		text-align: center;
	}

	.search-result-text {
		text-align: center;
		font-size: 14px;
		color: #666;
	}

	.example-body {
		/* #ifndef APP-NVUE */
		display: block;
		/* #endif */
		padding: 0px;
	}

	.uni-mt-10 {
		margin-top: 10px;
	}

	.title {
		color: #3d3d3d;
		font-size: 34rpx;
		font-weight: 800;
		line-height: 34rpx;
	}

	.intro {
		font-size: 24rpx;
		font-weight: 400;
		line-height: 24rpx;
	}

	.title2 {
		color: #3d3d3d;
		font-size: 32rpx;
		font-weight: 800;
		line-height: 48rpx;
		display: -webkit-box;
		-webkit-line-clamp: 2;
		-webkit-box-orient: vertical;
		overflow: hidden;
		text-overflow: ellipsis;
		
	}

	.title3 {
		font-size: 20rpx;
		font-weight: 400;
		color: #999999;
		line-height: 22rpx;
	}

	.scrollBox {
		// padding-bottom: constant(safe-area-inset-bottom);
		/* iOS 11.0 - 11.1 */
		// padding-bottom: env(safe-area-inset-bottom);
		/* iOS 11.2+ */
	}

	/* 对于没有安全区域的设备，设置默认值 */
	@supports not (padding-bottom: env(safe-area-inset-bottom)) {
		.scrollBox {
			padding-bottom: 0;
		}
	}

	.container {
		height: 100%;
		width: 100%;
		background-color: #f7f7f7;
		// display: grid;
		// background-color: linear-gradient(to bottom, #fcc74e 0%, #f7f7f7 50%);
		// background-size: 100% 100%;

		.top {
			height: 520rpx;
			background-image: url('https://mall.jiangxiaoxian.hschool.com.cn/topBack.png');
			background-size: 100%;
			padding: 30rpx;
			display: grid;

			.locTop {
				width: 100%;
				height: 70rpx;
				display: flex;
				justify-content: space-between;
				// align-items: center;

				.locTop-left {
					width: 430rpx;
					height: 70rpx;
					display: flex;
					align-items: center;
					justify-content: flex-start;

				}

				.locTop-right {
					width: 203rpx;
					height: 70rpx;
					background-color: #ff5900;
					color: #ffffff;
					font-size: 28rpx;
					font-weight: bold;
					line-height: 42rpx;
					display: flex;
					justify-content: center;
					align-items: center;
					border-radius: 104rpx;
					padding: 0rpx 10rpx;
				}
			}

			.navTop {
				margin-top: 30rpx;
				display: flex;
				justify-content: space-between;
				// align-items: center;

				.navTop-left {
					width: 330rpx;
					height: 390rpx;
					background-image: url('https://mall.jiangxiaoxian.hschool.com.cn/shoppingMall.png');
					background-size: 100% 100%;
					border-radius: 18rpx;
					// padding: 40rpx 30rpx 0rpx 30rpx;

				}

				.navTop-right {
					// display: grid;
					justify-content: center;
					align-items: center;
					width: 330rpx;

					.navRight1 {
						width: 330rpx;
						height: 180rpx;
						background-image: url('https://mall.jiangxiaoxian.hschool.com.cn/rent.png');
						background-size: 100%;
						border-radius: 18rpx;
						// padding: 40rpx 30rpx 0rpx 30rpx;
					}

					.navRight2 {
						margin-top: 30rpx;
						width: 330rpx;
						height: 180rpx;
						background-image: url('https://mall.jiangxiaoxian.hschool.com.cn/school.png');
						background-size: 100%;
						border-radius: 18rpx;
						// padding: 40rpx 30rpx 0rpx 30rpx;
					}
				}
			}


		}

		.swiper-box {
			width: 690rpx;
			padding: 0 30rpx;
			// display: grid;
			// justify-content: center;
			height: 280rpx;
			position: relative;

			.swiper_s {
				width: 100%;
				height: 100%;
				// display: grid;
				// justify-content: center;

				.swiper-image {
					width: 100%;
					height: 100%;
					border-radius: 36rpx;
					object-fit: contain;
				}
			}

		}

		.recommend-box {
			margin-top: 30rpx;
			padding: 20rpx 30rpx;
			height: 900rpx;

			.recom-titleBox {
				display: flex;
				justify-content: space-between;
				align-items: center;
				width: 690rpx;

				.cityBox {
					width: 222rpx;
					height: 60rpx;
					margin-left: 30rpx;
					border-radius: 132rpx 132rpx 132rpx 132rpx;
					border: 1rpx solid #999999;
					display: flex;
					align-items: center;
					justify-content: center;
					margin-top: 6rpx;
				}

				.title-more {
					display: flex;
					justify-content: center;
					align-items: center;
				}
			}

			.rrecommList {
				margin-top: 30rpx;
				// padding: 30rpx;

				.reListItem {
					background-color: #ffffff;
					width: 640rpx;
					height: 190rpx;
					padding: 30rpx;
					display: flex;
					justify-content: flex-start;
					align-items: center;
					border-radius: 18rpx;

					.listItem-images {
						display: grid;
						justify-content: flex-start;

						.iamges-mainImg {
							width: 190rpx;
							height: 190rpx;
							position: relative;
							right: 0rpx;
							bottom: 18rpx;
							z-index: 1;
							border-radius: 12rpx;
						}
					}

					.listItem-contents {
						margin-left: 20rpx;

						.score-box {
							display: flex;

							.cate {
								display: flex;
								justify-content: flex-start;
								align-items: center;

								.cate-e {

									.status-tag {
										padding: 5rpx 15rpx;
										border-radius: 5rpx;
										font-size: 22rpx;
										font-weight: 400;
										line-height: 22rpx;
										background-color: rgba(247, 97, 0, 0.2);

										// opacity: 0.2;
										color: #F76100;
										//flex-shrink: 0
									}
								}
							}



						}


						.cons-third {
							margin-top: 20rpx;
							width: 430rpx;
							display: flex;
							justify-content: space-between;
							align-items: center;
						}
					}
				}

			}

		}

		.viewCan {}



	}



	.popup {
		background-image: url('https://mall.jiangxiaoxian.hschool.com.cn/registerBackNine.png');
		background-size: 100%;
		width: 750rpx;
		height: 930rpx;
		display: flex;
		// padding: 100rpx 73rpx 0rpx 73rpx;
		flex-direction: column;
		align-items: center;
		justify-content: flex-start;
		position: relative;
		bottom: 36rpx;

		.registerBox {
			position: relative;
			top: 346rpx;
			right: 30rpx;
			// margin-top: 150rpx;
			// margin-left: 80rpx;
			width: 410rpx;
			;

			.regListBox {
				width: 420rpx;


				.reItem {
					background-image: url('https://mall.jiangxiaoxian.hschool.com.cn/registerCouBack.png');
					background-size: 100%;
					padding: 30rpx 20rpx 30rpx 30rpx;
					width: 420rpx;
					height: 69rpx;
					display: flex;
					justify-content: space-between;
					align-items: center;
					margin-bottom: 20rpx;
				}
			}

		}

		.texbut {
			width: 375rpx;
			height: 93rpx;
			border-radius: 16rpx;
			// background: #ffbd25;
			background-image: url('https://mall.jiangxiaoxian.hschool.com.cn/scoreBtn.png');
			background-size: 100%;
			font-size: 34rpx;
			color: #3d3d3d;
			font-weight: bold;
			display: flex;
			justify-content: center;
			align-items: center;
			position: absolute;
			bottom: 34rpx;
			right: 188rpx;
		}
	}
	
	.popupLogin {
		background-image: url('https://mall.jiangxiaoxian.hschool.com.cn/loginBack.png');
		background-size: 100%;
		width: 540rpx;
		height: 640rpx;
		display: flex;
		padding-bottom: 44rpx;
		flex-direction: column;
		align-items: baseline;
		justify-content: flex-end;
		padding-left: 73rpx;
		padding-right: 73rpx;
	
		.img_shouquan {
			position: absolute;
			width: 680rpx;
			height: 857rpx;
			left: -25rpx;
			top: -390rpx;
		}
	
	
		#txt2 {
			text-align: center;
			margin-top: 200rpx;
			font-size: 28rpx;
			color: #525252;
			margin-bottom: 60rpx;
			position: relative;
			font-weight: 500;
		}
	
		.texbut {
			width: 507rpx;
			height: 93rpx;
			border-radius: 16rpx;
			// background: #ffbd25;
			background-image: url('https://mall.jiangxiaoxian.hschool.com.cn/loginBtnTwo.png');
			background-size: 100%;
			font-size: 34rpx;
			color: #3d3d3d;
			font-weight: bold;
			display: flex;
			justify-content: center;
			align-items: center;
			margin-top: 30rpx;
			// margin: 0 auto;
		}
	}
</style>