<template>
	<view class="content">
		<view class="top-content">
			<view class="status_bar" :style="{height: statusBarHeight}"></view>
			<!-- 这里是状态栏 -->
			<view class="top-title">
				<u-icon name="arrow-left" color="#fff" size="24" @click="navback()"></u-icon>
				<view class="search-cont">
					<view class="inner">
						<image class="icon-search" src="https://bjyjb-1362704775.cos.ap-chongqing.myqcloud.com/shop/image/icon_search.png" mode=""></image>
						<input type="text" disabled   confirm-type="搜索" @click="toSearch" placeholder="查找店内药品" placeholder-style="font-size:28rpx;color:#BBBBBB;font-family: PingFang SC;" />
					</view>
				</view>
			</view>
			<view class="storebox x-bc">
				<view class="x-f">
					<image class="logo" :src="storeInfo.logoUrl" mode="aspectFill"></image>
					<view class="storebox-r" @click="goStoreDetail">
						<view class="storename ellipsis2">{{storeInfo.storeName}}</view>
						<!-- <view class="storedesc">24小时营业  销售{{storeInfo.salesCount|| 0}}</view> -->
					</view>
				</view>
				<!-- <view class="storebox-btn" @click="goStoreDetail">详情</view> -->
			</view>
			<view class="top-fixed x-ac" style="background-color: #fff;">
				 <view>
					 <u-tabs
					  :scrollable="false"
					  :list="tabs"  
					  lineColor="#2583EB"
					  :current="current"
					   @change="tabChange">
					 </u-tabs>
				 </view>
			</view>
		</view>
			<view v-show="current!=1"  :style="{paddingTop: mescrollTop+'px'}">
				<tuiStoreProduct ref="tuiStoreProduct" :top="mescrollTop" :storeId="storeId" @refreshElementTop="getElementTop"></tuiStoreProduct>
				<view class="evaluate">
					<view class="title">店内商品评价({{evaluateTotal}})</view>
					<evaluateItem v-for="(item,index) in evaluate" :key="index" :item="item"></evaluateItem>
					<view class="footer-desc" v-if="evaluate&&evaluate.length>0"> 
						<text @click="moreEvaluate">查看更多评价</text>
						<image src="https://bjyjb-1362704775.cos.ap-chongqing.myqcloud.com/shop/image/arrow_gray.png"></image>
					</view>
				</view>
				<detail class="store-detail" ref="getStoreInfo" :storeInfo="storeInfo"></detail>
			</view>
			<view v-if="current==1" class="medic-box">
				<scroll-view :scroll-y="true" class="cate-list" :style="{top: mescrollTop+'px',height:divHeight}">
					<view 
						v-for="(item,index) in cates" 
						:key="index" 
						:class="cateSelect == item.dictValue?'item active':'item'" 
						@click="choseCate(item)"
					>{{item.dictLabel }}</view>
				</scroll-view>
				<view class="medic">
					<mescroll-body :top="mescrollTop+'px'" @init="mescrollInit" @down="downCallback" @up="upCallback" :down="downOption" :up="upOption">
					<view  style="padding: 0 24rpx 0 0;">
						<medicineItem v-for="(item, index) in dataList" :key="index" :item="item" :storeId="storeId"></medicineItem>
						<!-- <medicineVerticalItem v-for="(item, index) in dataList" :key="index" :item="item" :storeId="storeId"></medicineVerticalItem> -->
					</view>
					</mescroll-body>
					<!-- 轮播图 -->
					<!-- <view class="banner-box">
						<swiper
							class="swiper" 
							:indicator-dots="true" 
							:circular="true" 
							:autoplay="true" 
							:interval="3000" 
							:duration="1000"
							indicator-color="rgba(255, 255, 255, 0.6)"
							indicator-active-color="#ffffff"
						>
							<swiper-item class="swiper-item" v-for="(item,index) in advs" :key="index" @click="handleAdvClick(item)">
								<image :src="item.imageUrl" mode=""></image>
							</swiper-item>
						</swiper>
					</view> -->
				</view>
			</view>
	</view>
</template>

<script>
	import {getDicts} from '@/api/common.js'
	import MescrollMixin from "@/uni_modules/mescroll-uni/components/mescroll-uni/mescroll-mixins.js";
	import tuiStoreProduct from './components/tuiStoreProduct.vue'
	import qualifications from './components/qualifications.vue'
	import {getProductCate,storeDetail,getProducts} from '@/api/index.js'
	import medicineVerticalItem from "@/components/medicineVerticalItem";
	import medicineItem from "@/components/medicineItem";
	import evaluateItem from "@/components/evaluateItem";
	import detail from '@/components/storeDetail.vue'
	import {selectCommentByUser} from '@/api/myStoreOrder.js'
	// import {getAdv} from '@/api/adv'
	export default {
		mixins: [MescrollMixin], // 使用mixin
		components: {
			tuiStoreProduct,
			qualifications,
			medicineVerticalItem,
			medicineItem,
			evaluateItem,
			detail
		},
		data() {
			return {
				divHeight:'0px',
				allCates:[],
				cates:[],
				subCates:[],
				// 状态栏的高度
				statusBarHeight: uni.getStorageSync('menuInfo').statusBarHeight,
				// 选中药品分类
				cateSelect: 0,
				// 轮播图
				advs: [],
				tabs:[
					{
						id:1,
						name:'推荐'
					},
					{
						id:2,
						name:'药品'
					},
					{
						id:3,
						name:'评价'
					},
					{
						id:4,
						name:'详情'
					}
				],
				current:0,
				storeInfo: {},
				storeId:'',
				mescroll:null,
				downOption: {   //下拉刷新
				 	use:true,
					auto: false // 不自动加载 (mixin已处理第一个tab触发downCallback)
				},
				// 上拉加载的配置
				upOption: {
					onScroll:true,
					use: true, // 是否启用上拉加载; 默认true
					// auto: false,
					page: {
						num: 0, // 当前页码,默认0,回调之前会加1,即callback(page)会从1开始
						size: 10 // 每页数据的数量,默认10
					},
					noMoreSize: 10, // 配置列表的总数量要大于等于5条才显示'-- END --'的提示
					empty: {
						icon:'https://bjyjb-1362704775.cos.ap-chongqing.myqcloud.com/app/newImages/empty_icon.png',
						tip: '暂无数据'
					},
					textNoMore:"已经到底了",
				},
				// 列表数据
				dataList: [],
				form:{
					defaultOrder:'desc',
					newOrder:null,
					priceOrder:null,
					salesOrder:null,
					productName:"",
					storeId: "",
					cateId:'',
					productType:'',
					pid:'',
					storeId: ''
				},
				mescrollTop: 200,
				evaluate: [],
				evaluateTotal: 0,
				isScrollUpdating: false, // 标志位
				evaluateTop: 0,
				storeDetailTop: 0
			};
		},
		onLoad(option) {
			this.storeId = option.storeId
			this.form.storeId = option.storeId || ''
			uni.showShareMenu({
				withShareTicket:true,
				//小程序的原生菜单中显示分享按钮，才能够让发送给朋友与分享到朋友圈两个按钮可以点击
				menus:["shareAppMessage","shareTimeline"] //不设置默认发送给朋友
			})
			this.getProductType();
			this.getStoreInfo();
			this.getCommentByUser();
		},
		onReady() {
			this.$refs.tuiStoreProduct.getProducts(this.storeId)
		},
		onShow() {
			var that=this;
			setTimeout(function(){
				let info = uni.createSelectorQuery().select(".top-content");
		　　　  info.boundingClientRect(function(data) { //data - 各种参数
		// 　　　  　 	console.log(data.height)  // 获取元素宽度
					// console.log(uni.upx2px(10)) 
					that.divHeight="calc(100% - "+data.height+"px)"
					that.mescrollTop = data.height
		　　    }).exec()
			},500);
		},
		onPageScroll(e) {
			if (this.isScrollUpdating) return;
		    const scrollTop = e.scrollTop;
		
		    if (this.evaluateTop && this.storeDetailTop) {
		        if (scrollTop >= this.storeDetailTop) {
		            this.current = 3;
		        } else if (scrollTop >= this.evaluateTop) {
		            this.current = 2;
		        } else {
		            this.current = 0; // 或其他默认值
		        }
		    }
		},
		methods:{
			getElementTop(type) {
				this.$nextTick(() => {
					const query = uni.createSelectorQuery().in(this);
					query.select('.evaluate').boundingClientRect();
					query.select('.store-detail').boundingClientRect(); // 注意：ref 不能直接用于 select，需要加 class
					query.exec(res => {
						this.evaluateTop = res[0]?.top - this.mescrollTop || 0;
						this.storeDetailTop = res[1]?.top - this.mescrollTop || 0;
					});
				});
			},
			getStoreInfo() {
				storeDetail(this.storeId).then(res=>{
					if(res.code==200) {
						this.storeInfo =res.data || {}
						// if (this.storeInfo.doctorList && this.storeInfo.doctorList.length > 0) {
						//  this.storeInfo.doctorList = this.storeInfo.doctorList.map(doctor => {
						//     if (doctor.images) {
						//       doctor.practiseImages = doctor.practiseImages.split(',').map(img => img.trim());
						//     }
						//     return doctor;
						//   });
						// }
						this.storeInfo.doctorList = this.storeInfo.doctorList.map(doctor => {
							return {
							  ...doctor,
							  // 假设images字段是逗号分隔的图片字符串
							  imagesArray: doctor.practiseImages ? 
								doctor.practiseImages.split(',').map(img => img.trim()).filter(img => img) : []
							};
						  });
						  
						console.log(this.storeInfo.doctorList)
					}
					this.getElementTop('storeDetailTop');
				})
			},
			navback() {
				const pages = getCurrentPages(); // 获取当前页面栈
				if (pages.length > 1) {
				  uni.navigateBack({ delta: 1 }); // 有上一页才返回
				} else {
				  // 如果是首页，跳转到某个默认页面（如首页）
				  uni.switchTab({ url: 'pages/index/index' });
				}
			},
			tabChange(item) {
				this.current=item.index
				this.isScrollUpdating = true; 
				if ([0, 2, 3].includes(this.current)) {
				    const scrollMap = {
				        0: 0,
				        2: this.evaluateTop,
				        3: this.storeDetailTop
				    };
				    setTimeout(()=>{
						uni.pageScrollTo({
							scrollTop: scrollMap[this.current] || 0 ,
							duration: 0,
							complete: () => {
								this.isScrollUpdating = false;
							}
						});
					},100)
				}
			},
			toSearch() {
				uni.navigateTo({
					url: '/pages_shopping/home/productSearch?storeId='+this.storeId
				})
			},
			handleAdvClick(item){
				if(item.showType==1){
					uni.setStorageSync('url',item.advUrl);
					uni.navigateTo({
						url:"/pages_shopping/home/h5"
					})
				}
				else if(item.showType==2){
					 uni.navigateTo({
					 	url:item.advUrl
					 })
				}
				else if(item.showType==3){
					 uni.setStorageSync('content',item.content);
					 uni.navigateTo({
					 	url:"/pages_shopping/home/content"
					 })
				}
				
			},
			getAdv(){
				let data = {advType:2};
				getAdv(data).then(
					res => {
						if(res.code==200){
							this.advs=res.data;
						}
					},
					rej => {}
				);
			},
			getProductCate(){
				let data = {
					// storeId: this.storeId
				};
				getProductCate(data).then(
					res => {
						if(res.code==200){
							this.allCates=res.data;
							this.cates = this.allCates.filter(function (item) {
							     return item.pid==0
							});
							if(this.cates!=null&&this.cates.length>0){
								this.cateSelect=this.cates[0].cateId;
								this.form.cateId = this.cates[0].cateId;
								// this.form.pid = this.cates[0].pid;
								this.mescroll&&this.mescroll.resetUpScroll()
							}
						}else{
							uni.showToast({
								icon:'none',
								title: "请求失败",
							});
						}
					},
					rej => {}
				);
			},
			getProductType(){
				let data = {};
				getDicts(data).then(
					res => {
						if(res.code==200){
							uni.setStorageSync('dicts', JSON.stringify(res));
							const key = 'storeProductType'
							let dict=Array.isArray(key) ? key : res[key];
							this.cates=dict;
							if(this.cates!=null&&this.cates.length>0){
								this.cateSelect=this.cates[0].dictValue;
								this.form.productType = this.cates[0].dictValue;
								this.mescroll&&this.mescroll.resetUpScroll()
							}
						}else{
							uni.showToast({
								icon:'none',
								title: "请求失败",
							});
						}
					},
					rej => {}
				);
			},
			// 药品分类选择
			choseCate(item) {
				this.cateSelect = item.dictValue;
				this.form.productType = item.dictValue;
				this.mescroll.resetUpScroll()
				
			},
			getSubCate(){
				var that=this;
				this.subCates = this.allCates.filter(function (item) {
					// let subList = that.allCates.filter(child => {
					// 	//返回每一项的子级数组
					// 	return child.pid === item.cateId
					// });
					// subList.length > 0 ? item.children = subList : [];
				    return item.pid==that.cateSelect
				});
				 
			},
			// 查看药品详情
			showProductList(item) {
				uni.navigateTo({
					url: '/pages_shopping/productList?productType='+item.productType+"&pid="+item.pid+'&storeId='+this.storeId
				})
			},
			goSearch(e) {
				if(e.detail.value!=null&&e.detail.value!=""){
					this.$addHisSearch(e.detail.value);
				}
				uni.navigateTo({
					url: '/pages_shopping/home/productList?storeId='+this.storeId+'&searchValue=' + e.detail.value
				})
			},
			goStoreDetail() {
				uni.navigateTo({
					url: '/pages_store/storeDetail?storeId='+this.storeId
				})
			},
			mescrollInit(mescroll) {
				this.mescroll = mescroll;
			},
			/*下拉刷新的回调 */
			downCallback(mescroll) {
				mescroll.resetUpScroll()
			},
			upCallback(page) {
				//联网加载数据
				var that = this;
				this.form.page=page.num;
				this.form.pageSize=page.size;
				getProducts(this.form).then(res => {
					if(res.code==200){
						//设置列表数据
						if (page.num == 1) {
							that.dataList = res.data.list; 
							
						} else {
							that.dataList = that.dataList.concat(res.data.list);
							 
						}
						that.mescroll.endBySize(res.data.list.length, res.data.total);
						
					}else{
						uni.showToast({
							icon:'none',
							title: "请求失败",
						});
						that.dataList = null;
						that.mescroll.endErr();
					}
				});
			},
			moreEvaluate() {
				uni.navigateTo({
					url: '/pages_shopping/evaluate?storeId='+this.storeId,
				})
			},
			getCommentByUser(){
				const param = {
					page: 1,
					pageSize: 2,
					storeId:this.storeId,
					orderId: null,
					productIds:null,
					userId: uni.getStorageSync('userId') || null,
					showSelf: 0
				}
				selectCommentByUser(param).then(res=>{
					if(res.code==200) {
						this.evaluate = res.data.list
						this.evaluateTotal = res.data.total
					} else {
						this.evaluate = []
						this.evaluateTotal = 0
					}
					this.getElementTop('evaluate');
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
	.evaluate {
		padding: 30rpx 30rpx 0 30rpx;
		background-color: #FFFFFF;
		margin-bottom: 24rpx;
		.title {
			font-family: PingFang SC, PingFang SC;
			font-weight: 600;
			font-size: 30rpx;
			color: #222222;
			padding-bottom: 24rpx;
		}
		.footer-desc {
			text-align: center;
			padding: 0 32rpx 24rpx 0;
			font-size: 28rpx;
			color: #999;
			image{
				margin-left: 10rpx;
				width:15rpx;
				height:20rpx;
			}
		}
	}
	.storebox {
		padding: 26rpx 32rpx;
		font-family: PingFang SC, PingFang SC;
		color: #FFFFFF;
		.logo {
			width: 104rpx;
			height: 104rpx;
			background: #FFFFFF;
			border-radius: 16rpx 16rpx 16rpx 16rpx;
			margin-right: 26rpx;
		}
		.storename {
			font-weight: 500;
			font-size: 32rpx;
		}
		.storedesc {
			margin-top: 12rpx;
			font-weight: 400;
			font-size: 22rpx;
		}
		.storebox-r {
			flex: 1;
			overflow: hidden;
		}
		.storebox-btn {
			flex-shrink: 0;
			padding: 10rpx 16rpx;
			background: rgba(46, 218, 212, 0.50);
			font-size: 28rpx;
			border-radius: 8rpx 8rpx 8rpx 8rpx;
		}
	}
	.content{
		height: 100%;
		display: flex;
		flex-direction: column;
		.top-content{
			position: fixed;
			left: 0;
			top: 0;
			width: 100%;
			z-index: 10;
			background-repeat: no-repeat;
			background-image: url('https://bjyjb-1362704775.cos.ap-chongqing.myqcloud.com/app/image/index_img/home_top_bg.png');
			background-size: 100% 100%;
			.top-title{
				height: 88upx;
				line-height: 88upx;
				font-size: 42upx;
				font-family: Source Han Sans CN;
				font-weight: bold;
				color: #222222;
				padding-left: 41upx;
				background-color: transparent;
				display: flex;
				align-items: center;
			}
			.search-cont{
				padding: 6upx 30upx;
				.inner{
					box-sizing: border-box;
					width: 70%;
					height: 72upx;
					background: #FFFFFF;
					border-radius: 36upx;
					display: flex;
					align-items: center;
					padding: 0 30upx;
					.icon-search{
						width: 28upx;
						height: 28upx;
						margin-right: 20upx;
					}
					input{
						height: 60upx;
						line-height: 60upx;
						flex: 1;
					}
				}
			}
		}
		.medic-box{
			display: flex;
			background: #fff;
			::v-deep{
				.mescroll-body, .mescroll-body{
					padding-left: 204rpx;
				}
			}
			.cate-list{
				position: fixed;
				left: 0;
				z-index: 999;
				box-sizing: border-box;
				width: 180upx;
				background: #F2F5F9;
				display: flex;
				flex-direction: column;
				padding: 20upx 0;
				overflow-y: scroll;
				.item{
					height: 100upx;
					line-height: 100upx;
					padding-left: 20upx;
					font-size: 28upx;
					font-family: PingFang SC;
					font-weight: 500;
					color: #333333;
					position: relative;
					overflow: hidden;
					white-space: nowrap;
					text-overflow: ellipsis;
					&.active{
						color: #2583EB;
						&::after{
							content: "";
							width: 8upx;
							height: 50upx;
							background: #2583EB;
							position: absolute;
							top: 25upx;
							left: 0;
						}
					}
				}
			}
			.medic{
				overflow: hidden;
				box-sizing: border-box;
				.banner-box{
					margin-top: 30rpx;
					width: 100%;
					height: 160upx;
					border-radius: 10upx;
					overflow: hidden;
					.swiper,
					.swiper-item,
					.swiper-item image{
						width: 100%;
						height: 100%;
					}
				}
			}
		}
		
	}
	
</style>
