<template>
	<view>
		<Nav v-if="showindex == 'index'" />
		<view class="content" v-if="showindex == 'index'">
			<!-- 轮播图 -->
			<swipers :carousel="hometoplist.bannerList"></swipers>
			<!-- 广告 -->
			<advertisement :bannervo="hometoplist.freeBannerList" :itemStyle="advertisementStyle" ref="refbannervo">
			</advertisement>
			<!-- 金刚区 -->
			<diamond :district="hometoplist.district"></diamond>
			<!-- 今日上线 -->
			<todaylist :todayList="hometoplist.todayProInfo" :salesList="hometoplist.hotRanking"></todaylist>
			<!-- 类目 -->
			<!-- <view :style="{'top':store.height+'px'}" class="fourcontent" id="fourcontent">
				<view class="flex-between" style="flex-wrap: inherit;">
					<view class="fourcontent_item flex-start" v-for="(item,index) in hometoplist.menuList" :key="index"
						@click="viewHistory(item,index)"
						:class="!item.isChild && viewHistoryindex == index ? 'fourcontent_itemactev':''">
						<text style="margin-right: 10rpx;">{{item.name}}</text>
						<up-icon v-if="item.isChild" style="margin-left: 10rpx;"
							:name="showproductlist && viewHistoryindex == index  ?'arrow-up-fill':'arrow-down-fill'"
							color="#333333" size="12"></up-icon>
					</view>
				</view>
				<view class="componentsclass" v-if="showproductlist">
					<AreaSelect v-if="viewHistoryindex == 0" @updateValue="openproductlist" />
					<grouping v-if="viewHistoryindex == 1 || viewHistoryindex == 2 || viewHistoryindex == 3"
						@grouping="openproductlist" />
				</view>
			</view> -->
			<!-- 首页抢购区域 -->
			<!-- 	<view class="fivecontent">
				<view class="fivecontent_item" v-for="(item,index) in formhomelist.list" :key="index"
					@click="fivecontentclick(item)">
					<view class="fivecontent_item_nav flex-start">
						<image :src="item.shopImage" mode="aspectFill"></image>
						<view class="fivecontent_item_nav_left">
							<view class="fivecontent_item_nav_lefttop flex-between">
								<view>
									{{item.shopName}}
								</view>
								<view>
									{{item.districts}}&nbsp;{{item.distances}}
								</view>
							</view>
							<view class="fivecontent_item_nav_lefttopstart flex-start">
								<view class="fivecontent_item_nav_leftlang flex-start"
									v-for="(s,index1) in item.shopTag" :key="index1"
									:style="{'background':s.backColor,'color':s.backColor}">
									<image class="fivecontent_item_nav_leftlangimage" v-if="s.shareImg"
										:src="s.shareImg" mode="aspectFill"></image>
									<text class="fivecontent_item_nav_leftlangtext">{{s.name}}</text>
								</view>
							</view>
						</view>
					</view>
					<view class="fivecontent_item_box">
						<view class="fivecontent_item_boxitem flex-between">
							<image :src="`${item.image}?x-oss-process=image/resize,m_lfit,w_192,h_192`"
								mode="aspectFill"></image>
							<view class="fivecontent_item_boxitemleft flex-colum-start">
								<view class="fivecontent_item_boxitemleftone flex-between"
									style="display: flex;justify-content: space-between;align-items: center;">
									<view>
										{{item.productName.length>7?item.productName.substring(0,7)+'...':item.productName}}
									</view>
									<text>已抢{{item.realSalesNumber}}份</text>
								</view>
								<view class="flex-start flexstartboxfttow">
									<view class="fivecontent_item_boxitemlefttow flex-start"
										v-for="(c,index2) in item.proTag" :key="index2"
										:style="{'background':c.backColor,'color':c.backColor}">
										<image class="fivecontent_item_boxitemlefttowimage" v-if="c.shareImg"
											:src="c.shareImg" mode="aspectFill"></image>
										<text class="fivecontent_item_boxitemlefttowtext">{{c.name || ''}}</text>
									</view>
								</view>
								<view class="indexboxitemleftthere flex-colum-start">
									<view class="indexboxitemleftthereabsolute">
										马上抢
									</view>
									<view class="indexboxitemlefttheretext flex-start">
										<view class="fivecontent_item_boxitemlefthere_one flex-start">
											<text class="flex_startone">到手</text>
											<text class="flex_starttow">¥{{item.salePrice}}</text>
										</view>
										<view class="fivecontent_item_boxitemlefthere_tow">
											{{item.discount || ''}}折
										</view>
										<view class="fivecontent_item_boxitemlefthere_there">
											¥{{item.originPrice}}
										</view>
									</view>
									<view class="indexboxitemleftthere_countdown flex-between">
										<text class="indexboxitemleftthere_countdowntext">共省{{item.save}}元</text>
										<view class="indexboxitemleftthere_countdowntexts">
											<up-count-down
												:time="item.end_times.d * item.end_times.h * item.end_times.m *item.end_times.s"
												format="HH:mm:ss" autoStart millisecond @change="onChange">
												<view class="time">
													<view class="time__custom">
														<text
															class="time__custom__item">{{ timeData.hours>10?timeData.hours:'0'+timeData.hours}}</text>
													</view>
													<text class="time__doc">:</text>
													<view class="time__custom">
														<text
															class="time__custom__item">{{ timeData.minutes>10?timeData.minutes:'0'+timeData.minutes }}</text>
													</view>
													<text class="time__doc">:</text>
													<view class="time__custom">
														<text
															class="time__custom__item">{{ timeData.seconds>10?timeData.seconds:'0'+timeData.seconds }}</text>
													</view>
												</view>
											</up-count-down>
										</view>
									</view>
								</view>
							</view>

						</view>
					</view>
				</view>
				<up-loadmore :status="formhomelist.status" fontSize="14" color="#999" iconSize="14" />
			</view> -->
		</view>
		<indexs ref="indexsRef" v-if="showindex == 'shopIndex'" :shopExtend="orderVIP.shopExtendList"></indexs>
		<!-- <CouponModal></CouponModal> -->
		<!-- 页面加载动画 -->
		<pageLoading v-if="showPageLoading" />
		
	</view>
</template>

<script setup>
	import CouponModal from '@/components/coupon-modal.vue';
	import {
		ref,
		computed,
		onMounted,
		reactive,
		onBeforeUnmount,
		watch,
		getCurrentInstance,
		nextTick
	} from 'vue';
	import {
		onLoad,
		onReady,
		onShow,
		onReachBottom,
		onPageScroll
	} from '@dcloudio/uni-app';
	// 获取全局属性
	const {
		proxy
	} = getCurrentInstance();
	import pageLoading from './components/pageLoading.vue';
	import swipers from './components/swiper.vue'; //引入轮播
	import advertisement from './components/advertisement.vue'; //广告
	import diamond from './components/diamond.vue'; //金刚区
	import todaylist from './components/todaylist.vue'; //今日上线
	import indexs from './indexs.vue';
	import AreaSelect from './components/AreaSelect.vue'; //城市联动
	import grouping from './components/grouping.vue'; //其他
	import Nav from '@/components/indexnav.vue'; //导航栏
	import {
		APIhomehomePageUp,
		APIhome
	} from '@/common/api/index/index.js';
	import {
		APIgeocodelocation
	} from '@/common/api/api.js';
	import {
		useNavbarStore
	} from '@/stores/navbarStore';
	import {
		productStore
	} from '@/stores/user.js';
	import {
		getUnReadCountReq
	} from '../../common/api/account/message';
	const store = useNavbarStore();
	const storeuser = productStore();
	store.updateNavbarConfig({
		showBack: true, //左边返回键
		rightText: '', //右边文字
		showSearch: true, //true是标题其他事文字
		title: '我的页面',
		isTransparent: false,
		hasPlaceholder: false //是否要占位符
	});
	// 显示
	const showindex = ref('index');
	//计算广告图片的重合尺寸是位移
	const getStyle = (e) => {
		if (e > hometoplist.freeBannerList.length / 2) {
			var right = hometoplist.freeBannerList.length - e;
			return {
				transform: 'scale(' + 1 + ') translate(-' + right * 20 + '%,0px)',
				zIndex: 9999 - right,
				opacity: 1
			};
		} else {
			return {
				transform: 'scale(' + 1 + ') translate(' + e * 20 + '%,0px)',
				zIndex: 9999 - e,
				opacity: 1
			};
		}
	};
	const advertisementStyle = ref([]);
	const refbannervo = ref(null);
	//数据
	const hometoplist = reactive({});
	// 首页上面数据
	const hometop = async () => {
		try {
			let res = await APIhomehomePageUp();
			Object.assign(hometoplist, res);
			hometoplist.freeBannerList.forEach((item, index) => {
				advertisementStyle.value.push(getStyle(index));
			});
			// 数据加载完后获取dom 高度
			setTimeout(() => {
				const query = uni.createSelectorQuery().select('#fourcontent');
				query
					.boundingClientRect((rect) => {
						if (rect) {
							elementTop.value = rect.top - store.height;
						}
					})
					.exec();
			}, 500);
		} catch (e) {}
	};
	// 下面初始数据
	const formhomelist = reactive({
		//筛选
		address: '', //地址
		categoryId: '1', //品类
		orderType: '1', //1.理我最近 2.销量优先 3.价格优先
		distanceType: '1000', //附近1KM 1选中 0不选中
		page: 1, //页数
		size: 10, //页容量
		status: 'loadmore',
		name: '1',
		list: []
	});
	// 使用 reactive 创建响应式对象
	const timeData = ref({});

	// 定义 onChange 方法
	const onChange = (e) => {
		timeData.value = e;
	};
	const onLoadhome = async () => {
		try {
			let res = await APIhome(formhomelist);
			var dates = new Date().getTime();
			res.records.forEach((item, index) => {
				var leftTime = item.endTime - dates; //计算两日期之间相差的毫秒数
				if (leftTime >= 0) {
					let d = Math.floor(leftTime / 1000 / 60 / 60 / 24);
					let h = Math.floor((leftTime / 1000 / 60 / 60) % 24);
					let m = Math.floor((leftTime / 1000 / 60) % 60);
					let s = Math.floor((leftTime / 1000) % 60);
					item.end_times = {
						d: d,
						h: h,
						m: m,
						s: s
					};
				} else {
					item.end_times = 0;
				}
			});
			if ((res.totalPage == 0 || res.totalPage == 1) && res.totalRow <= 10) {
				console.log(res);
				formhomelist.status = 'nomore';
				formhomelist.list = res.records;
				if (formhomelist.page == 1 && res.records.length == 0) {
					formhomelist.list = [];
				}
				return false;
			} else {
				formhomelist.status = 'loading';
				if (formhomelist.page == 1) {
					formhomelist.list = res.records;
				} else {
					formhomelist.list = [...formhomelist.list, ...res.records];
				}
				formhomelist.page = ++formhomelist.page;
				if (formhomelist.page > res.totalPage) {
					formhomelist.status = 'nomore';
				} else {
					formhomelist.status = 'loading';
				}
			}
		} catch (e) {}
	};
	// /筛选数据处理
	const init_fn = async () => {
		formhomelist.list = [];
		Object.assign(formhomelist, {
			address: uni.cache.get('getLocationstorage').address, //地址
			lng: uni.cache.get('getLocationstorage').lng,
			lat: uni.cache.get('getLocationstorage').lat,
			type: '', //品类
			// orderBy: 0, //1.理我最近 2.销量优先 3.价格优先
			other: '', //附近1KM 1选中 0不选中
			page: 1, //页数
			size: 10, //页容量
			status: 'loadmore'
		});
		onLoadhome();
	};

	const orderVIP = ref({
		shopExtendList: ''
	});

	// 弹出层处理
	const showproductlist = ref(false);
	// 定义方法
	const openproductlist = (e) => {
		hometoplist.menuList[viewHistoryindex.value].name = e; //下标更改name
		showproductlist.value = !showproductlist.value;
	};

	// 存储每个元素距离顶部的距离
	const elementTop = ref(0);
	// 存储是否吸顶的状态
	const isSticky = ref(true);
	//下标
	const viewHistoryindex = ref(null);
	// 点击滑动元素
	const viewHistory = async (item, index) => {
		if (isSticky) {
			uni.pageScrollTo({
				scrollTop: elementTop.value,
				duration: 300
			});
		}
		// 是否有弹出层
		if (item.isChild) {
			showproductlist.value = showproductlist.value ? (viewHistoryindex.value == index ? false : true) : !
				showproductlist.value;
		}
		viewHistoryindex.value = index;
	};
	// 滑动
	onPageScroll((res) => {
		isSticky.value = res.scrollTop > elementTop.value ? true : false;
		uni.$u.debounce((store.scrollTop = res.scrollTop), 500);
	});

	const indexsRef = ref(null);
	const shopId = ref(null)
	const shopInfo = ref(null)
	onShow(async () => {
		if (!storeuser.isHasLogin) {
			await handleMixinOnLoad(options)
			console.log('shopInfo', uni.cache.get('shopInfo'));
			console.log('【页面】开始处理自身业务逻辑');
			
			onPageShow()
		} else {
			onPageShow()
		}
		setTimeout(() => {
			showPageLoading.value = false;
			getUnReadMsgCount();
		}, 800);
	});

	async function onPageShow() {
		try {
			await storeuser.getLocation();
			console.log('shopId.value',shopId.value);
			proxy.$isResolve();
			shopId.value = uni.cache.get('shopId');
			if (shopId.value) {
				indexsRef.value.updateData();
			}
		} catch (error) {}
		await proxy.$onLaunched;
		console.log('shopId.value',shopId.value);
		if (shopId.value) {
			showindex.value = 'shopIndex';
			await storeuser.actionsproductqueryProduct();
			await nextTick();
			orderVIP.value = uni.cache.get('orderVIP');
		} else {
			showindex.value = 'index';
			hometop();
			init_fn();
			// 获取初始定位高度
		}

		shopInfo.value = uni.cache.get('shopInfo');
	}

	const showPageLoading = ref(true);

	const getUnReadMsgCount = async () => {
		let res = await getUnReadCountReq()

		let badge = Number(res)
		if (badge > 0) {
			uni.setTabBarBadge({
				index: 2,
				text: badge.toString()
			})
		} else {
			uni.removeTabBarBadge({
				index: 2
			})
		}
	}



	onReachBottom(() => {
		onLoadhome();
	});

	import {
		shareMixin,
		handleMixinOnLoad
	} from '@/utils/share.js'


	watch(() => shopId.value, (newval) => {
		if (newval) {
			uni.showShareMenu({
				withShareTicket: true, // 可选：是否返回分享票据
				menus: ['shareAppMessage', 'shareTimeline'] // 显示「分享好友」和「分享朋友圈」
			});
		} else {
			uni.hideShareMenu();
		}
	}, {
		immediate: true
	})


	defineOptions({
		mixins: [shareMixin],
	});


	const options = reactive({})

	onLoad(async (opt) => {
		Object.assign(options, opt)
		// await handleMixinOnLoad(options)
		// console.log('shopInfo', uni.cache.get('shopInfo'));
		// console.log('【页面】开始处理自身业务逻辑');
		// setTimeout(() => {
		// 	showPageLoading.value = false;
		// 	getUnReadMsgCount();
		// }, 800);
	})
	


	// 页面离开时清除定时器
	// onBeforeUnmount(() => {
	// 	if (refbannervo.value) {
	// 		refbannervo.value.clearTimer(); 
	// 	}
	// });
</script>

<style lang="scss" scoped>
	.content {
		background: #f9f9f9;

		.fourcontent {
			position: sticky;
			padding: 32rpx 0;
			overflow-x: auto;
			flex-wrap: nowrap;
			background: #f9f9f9;
			z-index: 99;
			left: 0;

			.flex-between {
				margin: 0 32rpx;
			}

			.componentsclass {
				margin-top: 32rpx;
				left: 0;
				position: relative;
				width: 100%;
				height: 100vh;
				transition-duration: 350ms;
				transition-timing-function: ease-out;
				z-index: 10075;
				background-color: rgba(0, 0, 0, 0.5);
			}

			.fourcontent_item {
				flex-wrap: nowrap;
				margin-left: 20rpx;
				padding: 10rpx 24rpx;
				background: #ffffff;
				border-radius: 8rpx 8rpx 8rpx 8rpx;

				text {
					width: max-content;
				}
			}

			.fourcontent_itemactev {
				background: #fee06a;
			}

			// .fourcontent_item:nth-child(1) {
			// 	margin-left: 0;
			// }
		}

		.fivecontent {
			padding: 0 28rpx;
			height: 100vh;

			.fivecontent_item:nth-child(1) {
				margin-top: 0;
			}

			.fivecontent_item {
				margin-top: 32rpx;
				padding: 24rpx 32rpx;
				width: 100%;
				background: #ffffff;
				border-radius: 18rpx 18rpx 18rpx 18rpx;

				.fivecontent_item_nav {
					image {
						width: 60rpx;
						height: 60rpx;
						border-radius: 8rpx;
					}

					.fivecontent_item_nav_left {
						flex: auto;
						margin-left: 12rpx;

						.fivecontent_item_nav_lefttop {
							font-family: Source Han Sans CN, Source Han Sans CN;
							font-weight: 400;
							font-size: 24rpx;
							color: #666666;
						}

						.fivecontent_item_nav_lefttopstart {
							margin-top: 8rpx;

							.fivecontent_item_nav_leftlang {
								margin-left: 12rpx;
								width: max-content;
								padding: 4rpx 10rpx;
								background: #fff9e1;
								border-radius: 4rpx 4rpx 4rpx 4rpx;

								.fivecontent_item_nav_leftlangtext {
									margin-left: 6rpx;
									font-family: Source Han Sans CN, Source Han Sans CN;
									font-weight: 400;
									font-size: 16rpx;
									color: #f9a511;
								}

								.fivecontent_item_nav_leftlangimage {
									width: 10.82rpx;
									height: 14.06rpx;
								}
							}

							.fivecontent_item_nav_leftlang:nth-child(1) {
								margin-left: 0;
							}
						}
					}
				}

				.fivecontent_item_box {
					margin-top: 20rpx;
					border-top: 2rpx solid #e5e5e5;
					padding-top: 14rpx;

					.fivecontent_item_boxitem {
						image {
							width: 192rpx;
							height: 192rpx;
							border-radius: 12rpx;
						}

						.fivecontent_item_boxitemleft {
							margin-left: 24rpx;
							flex: 1;

							.fivecontent_item_boxitemleftone {
								width: 100%;

								text {
									font-family: Source Han Sans CN, Source Han Sans CN;
									// font-weight: 700;
									font-size: 24rpx;
									color: #999999;
								}

								view {
									// width: 300rpx;
									overflow: hidden;
									text-overflow: ellipsis;
									white-space: nowrap; //溢出不换行white-space:nowrap; //溢出不换行
									font-family: Source Han Sans CN, Source Han Sans CN;
									font-weight: 500;
									font-size: 32rpx;
									color: #333333;
								}
							}

							.flexstartboxfttow {
								.fivecontent_item_boxitemlefttow {
									margin-left: 16rpx;
									margin-top: 8rpx;
									width: max-content;
									padding: 4rpx 10rpx;
									background: #fff9e1;
									border-radius: 4rpx 4rpx 4rpx 4rpx;

									.fivecontent_item_boxitemlefttowtext {
										margin-left: 6rpx;
										font-family: Source Han Sans CN, Source Han Sans CN;
										font-weight: 400;
										font-size: 16rpx;
										color: #f9a511;
									}

									.fivecontent_item_boxitemlefttowimage {
										width: 10.82rpx;
										height: 14.06rpx;
									}
								}

								.fivecontent_item_boxitemlefttow:nth-child(1) {
									margin-left: 0;
									background: #ffd6d7;
									border-radius: 4rpx 4rpx 4rpx 4rpx;
								}
							}

							.indexboxitemleftthere {
								position: relative;
								margin-top: 30rpx;
								padding-left: 16rpx;
								width: 100%;
								background: url(https://czg-qr-order.oss-cn-beijing.aliyuncs.com/index/qinggou.png) no-repeat;
								background-size: 100% 100%;

								.indexboxitemleftthereabsolute {
									position: absolute;
									top: 14rpx;
									right: 12rpx;
									font-family: Source Han Sans CN, Source Han Sans CN;
									font-weight: bold;
									font-size: 24rpx;
									color: #ffffff;
								}

								.indexboxitemlefttheretext {
									// width: 100%;
									margin-top: 12rpx;

									display: flex;
									justify-content: center;
									align-items: center;

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

										.flex_startone {
											font-family: Source Han Sans CN, Source Han Sans CN;
											font-weight: 500;
											font-size: 16rpx;
											color: #ff7127;
										}

										.flex_starttow {
											font-family: Source Han Sans CN, Source Han Sans CN;
											font-weight: 500;
											font-size: 24rpx;
											color: #ff7127;
										}
									}

									.fivecontent_item_boxitemlefthere_tow {
										margin-left: 4rpx;
										padding: 2rpx 10rpx;
										border-radius: 4rpx 4rpx 4rpx 4rpx;
										border: 2rpx solid #ff7127;
										font-family: Source Han Sans CN, Source Han Sans CN;
										font-weight: 500;
										font-size: 16rpx;
										color: #ff7127;
									}

									.fivecontent_item_boxitemlefthere_there {
										margin-left: 6rpx;
										line-height: 24rpx;
										font-family: Source Han Sans CN, Source Han Sans CN;
										font-weight: 400;
										font-size: 16rpx;
										color: #999999;
										text-decoration-line: line-through;
									}
								}

								.indexboxitemleftthere_countdown {
									width: 100%;
									padding-right: 7rpx;
									margin-top: 2rpx;

									.indexboxitemleftthere_countdowntext {
										font-family: Source Han Sans CN, Source Han Sans CN;
										font-weight: 400;
										font-size: 24rpx;
										color: #999999;
										padding-bottom: 8rpx;
									}

									.indexboxitemleftthere_countdowntexts {
										font-family: Roboto, Roboto;
										font-weight: 400;
										color: #333333;
										font-family: Source Han Sans CN, Source Han Sans CN;
										font-weight: bold;
										font-size: 16rpx;
										color: #ffffff;

										.time {
											@include flex;
											align-items: center;

											&__custom {
												margin-top: 4rpx;
												width: 22rpx;
												height: 22rpx;
												border-radius: 4rpx;
												/* #ifndef APP-NVUE */
												display: flex;
												/* #endif */
												justify-content: center;
												align-items: center;

												&__item {
													color: #fff;
													font-size: 14rpx;
													text-align: center;
												}
											}

											&__doc {
												color: #fff;
												padding: 0px 4rpx;
											}

											&__item {
												color: #606266;
												font-size: 15rpx;
												margin-right: 4rpx;
											}
										}
									}
								}
							}
						}
					}
				}
			}
		}
	}
</style>