<template>
	<view>
		<Nav v-if="showindex == 'index'" />
		<view class="content" v-if="showindex == 'index'">
			<!-- 轮播图 -->
			<swipers :carousel='hometoplist.carousel'></swipers>
			<!-- 广告 -->
			<advertisement :bannervo='hometoplist.bannervo' :itemStyle='advertisementStyle' ref="refbannervo">
			</advertisement>
			<!-- 金刚区 -->
			<diamond :district='hometoplist.district'></diamond>
			<!-- 今日上线 -->
			<todaylist :todayList='hometoplist.todayList' :salesList='hometoplist.salesList'></todaylist>
			<!-- 类目 -->
			<!-- #ifdef MP-WEIXIN -->
			<!-- 只有小程序需要加height -->
			<up-sticky :offset-top="store.height">
			<!-- #endif -->
				<!-- #ifndef MP-WEIXIN -->
				<up-sticky>
				<!-- #endif -->
					<view class="fourcontent" id="fourcontent">
						<view class="flex-between" style="flex-wrap: inherit;">
							<view class="fourcontent_item flex-start" v-for="(item,index) in hometoplist.menu"
								: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>

				</up-sticky>

				<!-- 首页抢购区域 -->
				<view class="fivecontent">
					<view class="fivecontent_item" v-for="(item,index) in homelist" :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 height='40' :status="formhomelist.status" iconSize='16' fontSize='16' />
				</view>
		</view>
		<indexs v-if="showindex == 'shopIndex'"></indexs>
	</view>
</template>

<script setup>
	import {
		ref,
		computed,
		onMounted,
		reactive,
		onBeforeUnmount,
		watch,
		getCurrentInstance
	} from "vue";
	import {
		onLoad,
		onReady,
		onShow,
		onReachBottom,
		onPageScroll
	} from '@dcloudio/uni-app'
	// 获取全局属性
	const {
		proxy
	} = getCurrentInstance();
	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,
		APIshopUserInfo
	} from "@/common/api/index/index.js"
	import {
		useNavbarStore
	} from '@/stores/navbarStore';
	const store = useNavbarStore();
	// 动态更新导航栏配置
	store.updateNavbarConfig({
		showBack: true, //左边返回键
		rightText: '', //右边文字
		showSearch: true, //true是标题其他事文字
		title: '我的页面',
		isTransparent: false,
		hasPlaceholder: false //是否要占位符
	});
	// 显示
	const showindex = ref('index')
	//计算广告图片的重合尺寸是位移
	const getStyle = (e) => {
		if (e > hometoplist.bannervo.counponsInfo.length / 2) {
			var right = hometoplist.bannervo.counponsInfo.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({
		bannervo: {
			counponsInfo: [],
			coupons: ''
		}
	})
	// 首页上面数据
	const hometop = async () => {
		try {
			let res = await APIhomehomePageUp()
			Object.assign(hometoplist, res.data)
			if (hometoplist.bannervo.counponsInfo) {
				hometoplist.bannervo.counponsInfo.forEach((item, index) => {
					advertisementStyle.value.push(getStyle(index))
				})
			}
		} catch (e) {}
	}
	// 下面初始数据
	const formhomelist = reactive({ //筛选
		address: '', //地址
		type: '', //品类
		orderBy: '', //1.理我最近 2.销量优先 3.价格优先
		other: '', //附近1KM 1选中 0不选中
		page: 1, //页数
		size: 10, //页容量
		status: 'loadmore'
	})
	// 使用 reactive 创建响应式对象  
	const timeData = ref({});

	// 定义 onChange 方法  
	const onChange = (e) => {
		timeData.value = e;
	};
	const homelist = ref([]) //接收数据
	const onLoadhome = async () => {
		try {
			let res = await APIhome(formhomelist)
			var dates = new Date().getTime();
			res.data.list.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.data.pages < formhomelist.page) {
				formhomelist.status = 'nomore'
				if (form.page == 1 && res.data.list.length == 0) {

				}
				return false;
			} else {
				formhomelist.status = 'loading';
				formhomelist.page = ++formhomelist.page;
				setTimeout(() => {
					homelist.value = [...homelist.value, ...res.data.list];
					formhomelist.status = 'loading';
					if (res.data.pageNum == res.data.pages) {
						formhomelist.status = 'nomore';
					} else {
						formhomelist.status = 'loading';
					}
				}, 500)
			}
		} catch (e) {}
	}
	// /筛选数据处理
	const init_fn = async () => {
		homelist.value = []
		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 showproductlist = ref(false);
	// 定义方法  
	const openproductlist = (e) => {
		hometoplist.menu[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)
	});
	onShow(() => {})
	onMounted(async () => {
		await proxy.$onLaunched;
		console.log(uni.cache.get('shopId'))
		if (uni.cache.get('shopId') && uni.cache.get('token')) {
			showindex.value = 'shopIndex'
			let res = await APIshopUserInfo({
				"shopId": uni.cache.get('shopId'),
				"userId": uni.getStorageSync('userInfo').id,
			})
			if (res.code == 0) {
				//商家信息
				uni.cache.set('shopUserInfo', res.data)
			}
		} else {
			hometop()
			init_fn()
			showindex.value = 'index'
			// 获取初始定位高度
			setTimeout(() => {
				const query = uni.createSelectorQuery().select('#fourcontent');
				query.boundingClientRect((rect) => {
					elementTop.value = rect.top - store.height
				}).exec();
			}, 500)
		}
	});

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

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

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

		.fourcontent {
			padding: 32rpx 0;
			overflow-x: auto;
			flex-wrap: nowrap;
			background: #f9f9f9;
			margin: 0 32rpx;

			.componentsclass {
				margin-top: 32rpx;
				left: 0;
				position: absolute;
				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>