<template>
	<view class="container">
		<image class="home_top_bg" src="@/static/image/hall/home_top_bg.png" mode="widthFix"></image>
		<view class="tabbox">
			<view ref="tabbar" class="tabbar">
				<view :id="index" :class="activeTab == index ? 'active tabbar-item':'tabbar-item'"
					 v-for="(tab,index) in tabList" :key="tab.id" @click="handleTab(index)">{{tab.name}}</view>
			</view>
			<view ref="underline" class="tabbar-tabline tabbar-tabline-animation" :style="{left: indicatorLineLeft + 'px', width: indicatorLineWidth + 'px'}">
				<image class="tabbar-tabline-image" src="@/static/image/hall/hall_on_icon.png" mode="aspectFill"></image>
			</view>
		</view>
		
		<!-- 新手指引  -->
		<view class="guidebox" v-if="showGuide" @touchmove.stop.prevent @click="closeGuide('mask')">
			<view class="guide" :style="guideStyle" @click.stop.prevent>
				<!-- 学习中心新手指引 -->
				<!-- <view class="guide-step-tips" :style="tipPosition" v-if="activeTab == 1">
					<image class="Frame2612" src="@/static/images/guide/Frame2612.png" mode="aspectFill"></image>
					你可以在这里查询在学课程、学习笔记、收藏课程，对你学习进度进行跟踪。
				</view> -->
				<!-- 名医讲堂新手指引 -->
				<view class="guide3-step-tips2" :style="tipPosition" v-if="activeTab == 0">
					<view class="guide3-toptip">
						<view class="guide3-toptip-head">
							<image class="Frame2611" src="@/static/images/guide/Frame2611.png" mode="aspectFill"></image>
							<text>知名中医大师、达人亲自授课</text>
							<image class="guide3-toptip-headbg" src="@/static/images/guide/Frame2614.png" mode="widthFix"></image>
						</view>
						<view>分享他们在各自专业领域的丰富经验和独到见解。 </view>
					</view>
					<view :style="tipsCenter"></view>
					<view class="guide3-btn" @click="closeGuide()">我知道啦</view>
				</view>
			</view>
			
			<!-- 名医讲堂新手指引(图片模式) -->
			<!-- <view class="guide" v-if="activeTab != 1" @click.stop.prevent>
				<view class="guide3-step-tips">
					<view class="guide3-step-tipsbox">
						<view class="guide3-toptip">
							<view class="guide3-toptip-head">
								<image class="Frame2611" src="@/static/images/guide/Frame2611.png" mode="aspectFill"></image>
								<text>知名中医大师、达人亲自授课</text>
								<image class="guide3-toptip-headbg" src="@/static/images/guide/Frame2614.png" mode="widthFix"></image>
							</view>
							<view>分享他们在各自专业领域的丰富经验和独到见解。 </view>
						</view>
						<image class="Frame2291" src="@/static/images/guide/Frame2291.png" mode="widthFix"></image>
					</view>
					<view class="guide3-btn" @click="closeGuide()">我知道啦</view>
				</view>
			</view> -->
			
		</view>
		
	    <!-- 内容 -->
		<swiper :current="activeTab" @change="onSwiperChange" :style="'height:' + clientHeight + 'px;'">
			<swiper-item>
				<scroll-view scroll-y="true" :style="'height:' + clientHeight + 'px;'" :scroll-top="scrollTopHall" @scroll="scroll($event,'scrollTopHall')">
					<studyCenter ref="studyCenter"/>
				</scroll-view>
			</swiper-item>
			<swiper-item>
				<scroll-view scroll-y="true" :style="'height:' + clientHeight + 'px;'" :scroll-top="scrollTopStudy" @scroll="scroll($event,'scrollTopStudy')">
					<doctorHall ref="doctorHall" :swiperAutoplay="swiperAutoplay" @loadFamousCourse="loadFamousCourse(0)"/>
				</scroll-view>
			</swiper-item>
		</swiper>
		<!-- 新用户72h内弹免费领礼品弹窗 -->
		<giftPopup ref="giftPopup"></giftPopup>
	</view>
</template>

<script>
    import doctorHall from './components/doctorHall.vue';
    import studyCenter from './components/studyCenter.vue';
	import giftPopup from './components/giftPopup.vue';
	import MescrollMixin from "@/uni_modules/mescroll-uni/components/mescroll-uni/mescroll-mixins.js";
	import mescrollBody from "@/uni_modules/mescroll-uni/components/mescroll-body/mescroll-body.vue";
	import { getDictByKey } from '@/api/common'
	import { getCourseCate,getCourseList } from '@/api/course'
	import { getAdvList} from '@/api/adv.js'
	import { isCreateAd } from '@/api/user.js'
	
	export default {
		mixins: [MescrollMixin], // 使用mixin
		components: {
		    mescrollBody,
			doctorHall,
			studyCenter,
			giftPopup
		 },
		data() {
			return {
				headerHeight:44,
				statusBarBG:"none",
				headerIndex:98,
				downOption: {   //下拉刷新
				 	auto: true // 不自动加载 (mixin已处理第一个tab触发downCallback)
				},
				upOption: {   //上拉加载
				 	auto: false, // 不自动加载
				 	page: {
				 		num: 0, // 当前页码,默认0,回调之前会加1,即callback(page)会从1开始
				 		size: 10 // 每页数据的数量
				 	},
				 	noMoreSize: 5, //如果列表已无数据,可设置列表的总数量要大于半页才显示无更多数据;避免列表数据过少(比如只有一条数据),显示无更多数据会不好看; 默认5
				 	empty: {
				 		tip: '~ 空空如也 ~' // 提示
				 		// btnText: '去看看'
				 	}
				},
				//imageList:["../../static/image/home/banner.png"],
				imageList:[],
				advs:[],
				mtabs:[],
				tabIndex: 0, // 当前tab的下标
				fixedTop: false, 
				top:0,
				cateId:0,
				isBest:false,
				dataList:[],
				recommendList:[],
				swHeightArr:{},
				swHeight: "400px",
				keyWord:"",
				dataItem:{},
			    swiperAutoplay:true,
				famousItemHei:0,
				scrollTopHall: 0,
				scrollTopStudy: 0,
				old: {
					scrollTopStudy: 0,
					scrollTopHall: 0,
				},
				activeTab: 0,
				indicatorLineLeft: 0,
				indicatorLineWidth: 0,
				tabList: [
					{
					  id: "tab01",
					  name: '学习中心'
					}, {
					  id: "tab02",
					  name: '明医讲堂'
					}
				],
				clientHeight:0,
				scrollViewId:'scrollView0',
				showGuide: false, // 是否显示引导
				guideStyle: "",
				tipPosition: "",
				tipsCenter: "",
				isShowGiftPopup: false
			}
		},
		
		onPageScroll(e) {
			this.top=e.scrollTop;
		},
		computed: {
			// 计算属性的 getter
			headerBG:function() {
				var top=this.top/88;
				return 'rgba(255,92,3, ' + top + ')';
			},
		},
		onReady() {
			uni.getSystemInfo({
				success: (res) => {
					this.clientHeight = res.windowHeight - uni.upx2px(120) - res.statusBarHeight;
				}
			})
			this.tabListSize = {};
			this.selectorQuery();
		},
		onShow(){
			if(!this.$isLogin()){
				uni.navigateTo({
					url: '/pages/auth/loginIndex'
				})
				return;
			}
			this.$updateMsgDot()
		   this.swiperAutoplay=true;
		   this.getCreateAd()
		   if(this.activeTab == 1) {
			    this.$nextTick(()=>{
					this.$refs['studyCenter'].onShowFun()
				});
		   }
		},
		onHide() {
		   this.swiperAutoplay=false;
		},
		onLoad(){
		    // #ifdef APP-PLUS
				   if(plus.runtime.isAgreePrivacy()) {
					   if(plus.runtime.channel=="baidu"){  //获取渠道标识
					       let bdCmdType=uni.getStorageSync("bdCmdType");
						   console.log("qxj bdCmdType:"+bdCmdType);
					       if(this.$isEmpty(bdCmdType)){
					       	    this.$registerIdCode("activate",0,0);
					       }
					   }
				   }
		    // #endif
			uni.$on('loginOut', function() {
					uni.setStorageSync("AppToken",null);
					uni.removeStorageSync("onLaunch")
					uni.removeStorageSync("imUnread")
					uni.$emit("refreshUserInfo");
					let pages = getCurrentPages();
					let url = pages[ pages.length - 1]; //当前页页面实例
					//如果登录界面已打开,自动关闭
					if(url!=undefined&&url.route=="pages/auth/loginIndex"){
						return;
					}
					uni.navigateTo({
						url: '/pages/auth/loginIndex'
					});
			});
		},
		mounted() {
			try {
				const system = uni.getSystemInfoSync();
				let itemWid=(system.windowWidth-40-32)*0.5*0.95;
				let tempHei=itemWid*0.5;
				tempHei=uni.upx2px(tempHei)+30;
				this.famousItemHei=tempHei;
			} catch (e) {
				
			}
		},
		methods: {
			scroll(e,type) {
				this.old[type] = e.detail.scrollTop
			},
			handleTab(activeTab) {
				this.activeTab = activeTab
				this.changeGuide(activeTab);
				this.$nextTick(()=>{
					this.selectorQuery()
				})
			},
			loadFamousCourse(val){
				this.changeGuide(val);
			},
			updateIndicator(left, width) {
			   this.indicatorLineLeft = left;
			   this.indicatorLineWidth = width;
			},
			selectorQuery() {
				uni.createSelectorQuery().in(this).selectAll('.tabbar-item').boundingClientRect((rects) => {
				  rects.forEach((rect) => {
					this.tabListSize[rect.id] = rect;
				  })
				  this.updateIndicator(this.tabListSize[this.activeTab].left, this.tabListSize[this.activeTab].width);
				}).exec();
			},
			// swiper划动
			onSwiperChange(e){
				this.changeIdx(e.detail.current);
			},
			// 更新当前页
			changeIdx(index){
				if(this.activeTab === index) return;
				this.activeTab = index;
				this.scrollViewId = 'scrollView'+this.activeTab;
				this.$nextTick(()=>{
					this.selectorQuery()
				});
			},
			/*下拉刷新的回调 */
			downCallback() {
				this.mescroll.resetUpScroll(true);
				var that=this;
				this.requestData();
			},
			/*上拉加载的回调*/
			upCallback(page) { 
				this.mescroll.endByPage(1, 1); 
			},
			requestData(){
				//this.getCourseCate();
			},
			getCourseCate:function(){
				let that=this;
				getCourseCate().then(res => {
						if(res.code==200){
							this.mtabs=res.data;  
							let findIdx=this.mtabs.findIndex(item=>item.dictLabel=='精选');
							// console.log("qxj findIdx:"+findIdx);
							if(findIdx==-1){
								let dictItem={"dictValue":0,"dictLabel": "精选"};
								this.mtabs.unshift(dictItem);
							}
							this.isBest=true;
							if(this.mtabs.length>0){
								 this.cateId=this.mtabs[0].dictValue;
								 for (let i = 0; i < this.mtabs.length; i++) {
									 if(i<=4){
										 this.tabChange(i); 
									 }
								 }
								 //this.tabIndex=0;
								 //this.dataItem=this.dataList[this.tabIndex.toString()]
								 this.tabChange(0);
							}
						}
					},
					rej => {}
				);
			},
			getFamousCourseList:function(index){
				let that=this;
				let params={};
				if(this.isBest){
					params={"isBest":1};
				}else{
					params={"cateId":this.cateId};
				}
				if(this.dataList.hasOwnProperty(index+"")){
					 this.updateSwiperHeight(index);
				     return;
				}
				getCourseList(params,1,6).then(res => {
						if(res.code==200){
							this.dataList[index+""]=res.data.list;  
						    //this.$nextTick(() => {
						         this.updateSwiperHeight(index);
						    //}); 
						}
					},
					rej => {}
				);
			},
			getRecommendList:function(){
				let that=this;
				const params={"isTui":1};
				getCourseList(params,1,10).then(res => {
						if(res.code==200){
							this.recommendList=res.data.list;  
						}
					},
					rej => {}
				);
			},
			swiperChange(e){
				// console.log("qxj swiperChange");
				this.tabIndex = e.detail.current;
				this.tabChange(this.tabIndex);
			},
			tabChange(index){
				// console.log("qxj tabChange index:"+index);
				this.tabIndex=index;
				const item=this.mtabs[index];
				if(item){
					if(item.dictLabel=='精选'){
						this.isBest=true;
					}else{
						this.isBest=false;
					}
					this.cateId=item.dictValue;
					this.getFamousCourseList(index);
				}
			},
			onTransition(){
			},
			animationfinish(){
				this.updateSwiperHeight();
			},
			onSwiperResize() {
				 //console.log("qxj onSwiperResize");
		    },
			updateSwiperHeight() {
				 let dataArr=this.dataList[this.tabIndex.toString()];
				 if(dataArr==undefined ||  dataArr.length==0){
					 this.swHeight=150;
				 }else{
					 uni.createSelectorQuery().in(this).select('#swiper-content').boundingClientRect(rect => {
						  //console.log("qxj swHeight:"+this.swHeight);
						  if(rect!=null){
							  this.swHeight = rect.height+20;
						  }
						  if(this.swHeight<=100){
							     //所以(total + pagesize -1) / pagesize就得到总页数
							     // console.log("qxj famousItemHei:"+this.famousItemHei);
							     this.swHeight=(dataArr.length+1)/2*this.famousItemHei;
							     return;
						  }
					 }).exec();
				 }
			 },
			
			getAdvList() {
				//联网加载数据
				var that = this;
				var data = { advType:12,status:1}
				getAdvList(data).then(res => {
					if(res.code==200){
						that.imageList=[];
						that.advs=[];
						res.data.forEach(function(element) {
							if(element.imageUrl!=null&&element.imageUrl!=""){
								that.advs.push(element);
								that.imageList.push(element.imageUrl);
							}
						});
						
					}else{
						uni.showToast({icon:'none',title: "请求失败"});
					}
				});
			},
			goToMsg(){
				if(!this.$isLogin()){
					this.$showLoginPage();
					return;
				}else{
					let registrationID=uni.getStorageSync("registrationID");
					let token = uni.getStorageSync('AppToken');
				}
			},
			// 页面跳转
			navTo(url) {
				console.log("qxj url:"+url);
				uni.navigateTo({
					url: url
				});
			},
			loginNavTo(url){
				if(!this.$isLogin()){
					this.$showLoginPage();
					return;
				}
				this.$navTo(url);
			},
			changeImg(){
				
			},
			handleAdvClick(index){
				var ad=this.advs[index];
				if(ad.showType==1){
					uni.setStorageSync('url',ad.appAdvUrl);
					uni.navigateTo({
						url:"h5"
					});
				}
				else if(ad.showType==2){
					// console.log(ad.appAdvUrl);
					uni.navigateTo({
						url:ad.appAdvUrl
					});
				}
				else if(ad.showType==3){
					 uni.setStorageSync('content',ad.content);
					 uni.navigateTo({url:"content"});
				}
			},
			changeGuide(val){
				let guide = ''
				let ele = ""
				if(val == 1) {
					// guide = uni.getStorageSync("studyCenterGuide");
					// ele = "#guide4"
				} 
				else {
					guide = uni.getStorageSync("doctorHallGuide");
					ele = "#guide3"
				}
				if ((guide!=undefined && !guide) &&ele) {
					setTimeout(e=>{
						this.showGuide = true;
						this.getGuideInfo(ele);
					},val==0?1000:500);
				} else {
					this.showGuide = false;
				}
			},
		    getGuideInfo(el) {
		    	const refname = this.activeTab == 1 ? 'studyCenter' : 'doctorHall'
		    	const query = uni.createSelectorQuery().in(this.$refs[refname]);
		    	this.$nextTick(function() {
		    		query.select(el).boundingClientRect()
		    		let _this = this;
		    		query.exec(function(res) {
		    			if(!res) return
		    			const {
		    				width,
		    				height,
		    				left,
		    				top,
		    				style = 'border-radius: 12rpx;margin: 0'
		    			} = res[0]
		    			if(el == '#guide3') {
							// 滑动至顶部（减去导航栏高度）
		    				_this.scrollTopHall = uni.upx2px(100) - 44
		    				_this.getGuide3item(res[0])
		    			} else {
		    				_this.scrollTopStudy = _this.old.scrollTopStudy
		    				_this.$nextTick(()=> {
		    					_this.scrollTopStudy = 0
		    				});
		    				// 减去我的评价宽度
		    				const relwidth = width 
		    				let newstyle = "width:" + relwidth + "px;";
		    				newstyle += "height:" + height + "px;";
		    				newstyle += "left:" + uni.upx2px(24) + "px;";
		    				newstyle += "top:" + top + "px;";
		    				newstyle += style;
		    				_this.guideStyle = newstyle
		    				let tipsTop = height + uni.upx2px(20);
		    				_this.tipPosition = "top:" + tipsTop + 'px;left:' + uni.upx2px(88) + "px;";
		    			}
		    		})
		    	});
		    },
		    getGuide3item(res) {
		    	const {
		    		width,
		    		height,
		    		left,
		    		top,
		    		style = 'border-radius: 12rpx;margin: 0'
		    	} = res
		    	const refname = this.activeTab == 1 ? 'studyCenter' : 'doctorHall'
		    	const query = uni.createSelectorQuery().in(this.$refs[refname]);
		    	let _this = this;
				
		    	query.select(".guide3item").boundingClientRect((data) => {
		    		if(!data) return
		    		const relwidth = width + uni.upx2px(24)
		    		const relheight = height + data.height + uni.upx2px(30)
					console.log("qxj getGuide3item top:"+top+" scrollTopHall:"+ _this.scrollTopHall);
					// const reltop = top;
		    		const reltop = top - _this.scrollTopHall
		    		let newstyle = "width:" + relwidth + "px;";
		    		newstyle += "height:" + relheight + "px;";
		    		newstyle += "left:" + uni.upx2px(14) + "px;";
		    		newstyle += "top:" + reltop + "px;";
		    		newstyle += style;
					console.log("qxj guide3Style:"+JSON.stringify(newstyle));
		    		_this.guideStyle = newstyle
		    		const tipsCenter = relheight + uni.upx2px(50)
		    		_this.tipsCenter = "height:" + tipsCenter +"px";
		    		let tipsTop = - uni.upx2px(180);
		    		_this.tipPosition = "top:" + tipsTop + 'px;left:' + uni.upx2px(66) + "px;";
		    	}).exec();
		    },
		    closeGuide(type) {
		    	if(type == 'mask' && this.activeTab==0) {
		    		return
		    	}
		    	this.showGuide = false;
		    	if(this.activeTab == 1) {
		    		uni.setStorageSync("studyCenterGuide", true);
					// setTimeout(e=>{
					// 	uni.switchTab({url: '/pages/course/video/living-app' });
					// },500);
		    	}else {
		    		uni.setStorageSync("doctorHallGuide", true);
					// this.handleTab(1);
					setTimeout(e=>{
						uni.switchTab({
							url: '/pages/course/video/living-app',
							complete: () => {
								this.getCreateAd()
							}
						});
					},500);
		    	}
		    	this.scrollTopHall = this.old.scrollTopHall
		    	this.scrollTopStudy = this.old.scrollTopStudy
		    	this.$nextTick(()=> {
		    		this.scrollTopHall = 0
		    		this.scrollTopStudy = 0
		    	});
		    },
			// 礼品弹窗
			getCreateAd() {
				// #ifdef APP-PLUS
				if(plus.runtime.isAgreePrivacy()) {
					if(plus.runtime.channel=="yyb" || plus.runtime.channel=="yybadv" || plus.runtime.channel=="yybadv1"){
					    let guide = uni.getStorageSync("doctorHallGuide");
					    let ele = "#guide3"
					    if (guide && ele) {
					    	isCreateAd().then(res=>{
					    		if(res.code == 200 && res.isCreate) {
					    			this.$nextTick(()=>{
					    				this.$refs.giftPopup.openPop()
					    			})
					    		} else {
					    			this.$nextTick(()=>{
					    				this.$refs.giftPopup.closePop()
					    			})
					    		}
					    	})
					    }
					}
				}
				// #endif
			}
		}
	}
</script>

<style scoped lang="scss">
	@mixin u-flex($flexD, $alignI, $justifyC) {
		display: flex;
		flex-direction: $flexD;
		align-items: $alignI;
		justify-content: $justifyC;
	}
	
	.guidebox {
		position: fixed;
		left: 0;
		top: 0;
		width: 100%;
		height: 100%;
		z-index: 1000;
		.guide {
			position: absolute;
			z-index: 10001;
			box-shadow: rgb(33 33 33 / 80%) 0px 0px 0px 0px, rgb(33 33 33 / 50%) 0px 0px 0px 5000px;
		}
		.guide-step-tips {
			position: absolute;
			top: 0;
			left: 0;
			z-index: 10001;
			padding: 18rpx 18rpx 18rpx 90rpx;
			box-sizing: border-box;
			border-radius: 24rpx;
			font-family: PingFang SC, PingFang SC;
			font-weight: 400;
			font-size: 26rpx;
			color: #FFFFFF;
			line-height: 40rpx;
			background: linear-gradient(90deg, #FCAC34, #F9622F);
		}
		.Frame2612 {
			height: 158rpx;
			width: 158rpx;
			position: absolute;
			left: -66rpx;
			top: -102rpx;
		}
		.guide3-step-tips2 {
			display: flex;
			flex-direction: column;
			align-items: center;
			justify-content: center;
			position: absolute;
		}
		.guide3-step-tips {
			width: 100vw;
			display: flex;
			flex-direction: column;
			align-items: center;
			justify-content: center;
			height: 100vh;
			position: absolute;
		}
		.guide3-step-tipsbox {
			display: flex;
			flex-direction: column;
			align-items: flex-end;
		}
		.guide3-btn{
			width: 272rpx;
			height: 84rpx;
			margin: 0 auto;
			background: #FF5C03;
			border-radius: 42rpx 42rpx 42rpx 42rpx;
			font-family: PingFang SC, PingFang SC;
			font-weight: 500;
			font-size: 32rpx;
			color: #FFFFFF;
			line-height: 84rpx;
			text-align: center;
		}
		.guide3-toptip {
			width: 640rpx;
			height: 160rpx;
			padding: 26rpx;
			box-sizing: border-box;
			position: relative;
			font-family: PingFang SC, PingFang SC;
			font-weight: 400;
			font-size: 26rpx;
			color: #FFFFFF;
			line-height: 30rpx;
		}
		.guide3-toptip-head {
			// position: relative;
			margin-bottom: 8rpx;
			font-family: PingFang SC, PingFang SC;
			font-weight: 600;
			font-size: 34rpx;
			color: #FFFFFF;
			line-height: 40rpx;
		}
		.guide3-toptip-headbg {
			width: 640rpx;
			height: 160rpx;
			position: absolute;
			top: 0;
			left: 0;
			z-index: -1;
		}
		.Frame2611 {
			width: 188rpx;
			height: 184rpx;
			position: absolute;
			top: -90rpx;
			right: 0;
		}
		.Frame2291 {
			width: 702rpx;
			// height: 684rpx;
			margin: 24rpx 0 40rpx 0;
		}
	}
	
	.container {
		font-family: PingFang SC, PingFang SC;
		padding-top: var(--status-bar-height);
		position: relative;
		z-index: 2;
	}
	.home_top_bg {
		width: 100%;
		height: auto;
		position: absolute;
		top: 0;
		left: 0;
		z-index: -1;
	}
	.tabbox {
		position: relative;
		margin-bottom: 22rpx;
		position: relative;
		.tabbar {
			height: 88rpx;
			@include u-flex(row,center,center);
			font-weight: 600;
			font-size: 32rpx;
			color: #222222;
			line-height: 88rpx;
			position: relative;
			.tabbar-item {
				margin: 0 24rpx;
			}
			.active {
				font-weight: 600;
				font-size: 40rpx;
				color: #FF5C03;
				position: relative;
			}
		}
		.tabbar-tabline-image {
			width: 36rpx;
			height: 12rpx;
		}
		.tabbar-tabline {
		  position: absolute;
		  bottom: 0;
		  width: 0;
		  height: 12rpx;
		  display: flex;
		  align-items: center;
		  justify-content: center;
		}
		.tabbar-tabline-animation {
		  transition-duration: 0.2s;
		  transition-property: left;
		}
	}
  

</style>
