<template>
	<view style="height: 100vh;">
		<scroll-view :bounces="false" scroll-y="true" style="height: 100vh;" @scroll="handleScroll">
			<view v-if="showStart == true" style="width: 100vw; height: 100vh">
				<image :src="startData.PicUrl" mode="aspectFit" style="width: 100%; height: 100%; position: relative">
					<view class="Startbtn" :style="{ top: pagePaddingBottom }" @click="startb">
						跳过
					</view>
				</image>
			</view>
			<view v-if="myPageData.home_pages" class="safe-top" v-show="showStart == false"
				:style="[myPageData.home_pages.navs[active].templateBg]">
				<view class="content" :style="{
		      'padding-bottom':(pageId==0?'calc(57px + env(safe-area-inset-bottom))':'0px'),
		    }">
					<view :style="{opacity:`${pageId!=0?100:(scrollTop-20)}%`}">
						<view class="index-title" :class="{ MainTopLeft: pageTitleStr.length > 10 }" :style="[
					myPageData.home_pages.navs[active].templateBg,
					titleStyle,
					{
					  color: myPageData.home_pages.navs[active].templateBg
						? myPageData.home_pages.navs[active].templateBg.titleColor
						: '',
					}]">
							<text v-if="isNavPosition == 0">{{ pageTitleStr }}</text>
							<view v-if="pageId!=0" class="back-arrow row items-center" @click="goback">
								<u-icon name="home_1" custom-prefix="tffont" color="#111" size="38"
									style="font-weight: bolder;"></u-icon>
							</view>
						</view>
					</view>
					<u-tabs v-if="myPageData.home_pages && myPageData.home_pages.navs.length > 1" name="name"
						:list="myPageData.home_pages.navs" :is-scroll="true" :active-color="mainColor" :current="active"
						:bar-width="80" :font-size="32" :bold="false" @change="changeHandler"></u-tabs>
					<template v-for="(item, i) in myPageData.home_pages.navs">
						<view :key="i" v-if="active == i">
							<template v-for="(d, di) in item.template.data">
								<search v-if="d.id == 'search' && isNavPosition == 0" :style-str="d.data" :key="di">
								</search>
								<swiper v-if="d.id == 'banner'" :swipers="d.data" :key="di"></swiper>
								<empty v-if="d.id == 'empty'" :block="d.data" :key="di"></empty>
								<rubik v-if="d.id == 'rubik'" :ad="d.data" :key="di"></rubik>
								<goods v-if="d.id == 'goods'" :goods="d.data" :key="di"></goods>
								<notice v-if="d.id == 'notice'" :notice="d.data" :key="di"></notice>
								<gridnav v-if="d.id == 'nav'" :navs="d.data" :key="di"></gridnav>
								<pagetitle v-if="d.id == 'link'" :ts="d.data" :key="di"></pagetitle>
								<videopage v-if="d.id == 'video'" :video="d.data" :key="di"></videopage>
								<copyright v-if="d.id == 'copyright'" :cop="d.data" :key="di"></copyright>
								<checkin v-if="d.id == 'check-in'" :check="d.data" :key="di"></checkin>
								<userbox v-if="d.id == 'user-info'" :ts="d.data" :key="di"></userbox>
								<userorder v-if="d.id == 'user-order'" :uo="d.data" :key="di"></userorder>
								<checkform v-if="d.id == 'form'" :forms="d.data" :key="di"></checkform>
								<addialog v-if="d.id == 'modal' && d.data.opened" :ads="d.data" :key="di"></addialog>
								<quicknav v-if="d.id == 'quick-nav' && d.data.navSwitch == 1" :navs="d.data" :key="di">
								</quicknav>
								<shopinfo v-if="d.id == 'shop-info'" :ad="d.data" :key="di" ref="son"></shopinfo>
							</template>
						</view>
					</template>
					<coupon v-if="showCoupons" :coupon-message="couponMessage" :cform="ComeFrom"
						@goLook="()=>showCoupons = false" @closeBtn="()=>showCoupons = false"></coupon>
					<auth v-if="showAuth&&is_show_auth" @changeuserinfo="reloadUserinfo" @gbAuth="gbAuth"></auth>
					<official-account></official-account>
				</view>
			</view>
		</scroll-view>
		<view v-if="showtabs && myPageData.home_pages">
			<tabbar></tabbar>
		</view>
	</view>
</template>

<script>
	import tabbar from "@/components/tabbar/index";
	import search from "@/components/search/index";
	import swiper from "@/components/swiper/index";
	import empty from "@/components/empty/index";
	import rubik from "@/components/rubik/index";
	import goods from "@/components/goods/index";
	import notice from "@/components/notice/index";
	import gridnav from "@/components/gridnav/index";
	import pagetitle from "@/components/pagetitle/index";
	import videopage from "@/components/videopage/index";
	import copyright from "@/components/copyright/index";
	import checkin from "@/components/checkin/index";
	import userbox from "@/components/userbox/index";
	import userorder from "@/components/userorder/index";
	import checkform from "@/components/checkform/index";
	import addialog from "@/components/addialog/index";
	import quicknav from "@/components/quicknav/index";
	import coupon from "@/components/coupons/coupons";
	import shopinfo from "@/components/shopinfo/shopinfo";
	import auth from "@/components/auth/index.vue";

	const innerAudioContext = uni.createInnerAudioContext();
	export default {
		data() {
			return {
				myPageData: {},
				mainColor: "",
				active: 0,
				pageId: 0,
				setting: {},
				showtabs: true,
				showCoupons: false,
				couponMessage: "",
				pageTitleStr: "",
				titleStyle: "",
				pagePaddingBottom: "0px",
				showAuth: false,
				u: {},
				showStart: false,
				startData: {},
				ComeFrom: "",
				safeTop: 0,
				isNavPosition: 0,
				scrollTop: 0,
				is_show_auth: 0,
			};
		},
		components: {
			tabbar,
			search,
			swiper,
			empty,
			rubik,
			goods,
			notice,
			gridnav,
			pagetitle,
			videopage,
			copyright,
			checkin,
			userbox,
			userorder,
			checkform,
			addialog,
			quicknav,
			coupon,
			shopinfo,
			auth
		},
		onLoad(options) {
			let that = this;
			let c = this.$uiConfig.is_bang ? 78 : 50;
			this.contentHeight = this.$utils.calcContentHeight(c);
			if (options && options.page_id) {
				this.pageId = options.page_id;
				let queryString = "";
				for (var k in options) {
					queryString += `&${k}=${options[k]}`;
				}
				if (queryString != "") {
					queryString =
						"/pages/index/index?" + queryString.substring(1, queryString.length);
				}
				if (options && options.scene) {
					//兼容之前小程序的调转
					this.getjump(options.scene);
				}

			}
			this.tokenIsExpire()
			this.init()
			uni.showNavigationBarLoading();
			if (uni.getStorageSync('coupons')) {
				this.showCoupons = true;
				this.couponMessage = uni.getStorageSync('coupons');
			}
		},
		mounted() {
			const that = this
			uni.getSystemInfo({
				success(res) {
					that.titleStyle = {
						height: "45px",
						paddingTop: `${res.statusBarHeight}px`,
					};
					that.safeTop = res.statusBarHeight
				}
			});
		},
		// #ifdef MP-WEIXIN
		onShareTimeline() {
			let uid = uni.getStorageSync("mall_UserInfo") ?
				uni.getStorageSync("mall_UserInfo").UserId :
				0;
			let title = this.setting.share_title ?
				this.setting.share_title :
				uni.getStorageSync("basedata").mall.name;

			return {
				title: title,
				query: "user_id=" + uid + this.$uiConfig.DIRECT_PARAMETER,
				imageUrl: "",
			};
		},
		onShareAppMessage(res) {
			let uid = uni.getStorageSync("mall_UserInfo") ?
				uni.getStorageSync("mall_UserInfo").UserId :
				0;
			let title = this.setting.share_title ?
				this.setting.share_title :
				uni.getStorageSync("basedata").mall.name;

			return {
				title: title,
				path: "/pages/index/index?user_id=" + uid + this.$uiConfig.DIRECT_PARAMETER,
				imageUrl: "",
			};
		},
		// #endif
		onShow() {
			setTimeout(() => {
				uni.hideNavigationBarLoading();
			}, 500);
			this.mainColor = this.$uiConfig.mainColor;
			this.$utils.VersionUpdate()

			const mu = uni.getStorageSync('mall_UserInfo')
			const bu = uni.getStorageSync('b2b_user')

			if (!mu || !bu) this.showAuth = true
		},

		methods: {
			tokenIsExpire(){
				this.apipost('b2b_post_CheckMiniAppToken',{},
				(res)=>{
					if(res.resultCode==1){}
				})
			},
			startb() {
				this.showStart = false;
				if (innerAudioContext != undefined) {
					innerAudioContext.stop();
				}
			},
			getunilogin(res) {
				let that = this;
				uni.login({
					provider: "weixin",
					success: (info) => {
						let obj = {
							Name: res.userInfo.nickName,
							Photo: res.userInfo.avatarUrl,
							code: info.code,
						};
						that.getCode(obj);
					}
				});
			},
			getCode(obj) {
				var that = this;
				that.request2({
						url: "/api/mall/GetWeChatOpenId",
						data: {
							Code: obj.code,
						},
					},
					(res) => {
						if (res.resultCode == 1) {
							obj.OpenId = res.data;
							that.getLogin(obj);
						}
					}
				);
			},
			getLogin(obj) {
				var that = this;
				that.request2({
						url: "/api/AppletLogin/Login",
						data: {
							Source: 1,
							OpenId: obj.OpenId,
							Name: obj.Name,
							Photo: obj.Photo,
							Moblie: "",
						},
					},
					(res) => {
						if (res.resultCode == 1) {
							uni.setStorageSync("mall_UserInfo", res.data);
							that.u = res.data;
							that.init();
						}
					}
				);
			},
			goback() {
				uni.redirectTo({
					url: '/pages/index/index'
				})
			},
			init() {
				const parameter = {VipCusType:1,page_id: this.pageId}
				// #ifdef MP-DI
				parameter.VipCusType = 2
				// #endif
				this.request2({
						url: "/api/Mall/GetHome",
						data: parameter,
					},
					(res) => {
						this.myPageData = res.data;
						if(this.pageId==0){
							uni.setStorageSync('navs',this.myPageData.navbar.navs)
						}
						uni.setStorageSync("basedata", res.data);
						if (res.data && res.data.mall && res.data.mall.setting) {
							this.setting = res.data.mall.setting;
							//判断后台是否开启自动授权
							if (this.setting && this.setting.is_show_auth ==1) {
								this.is_show_auth = 1;
							}
						}
						this.formatBg();
						if (this.pageId == 0) {
							this.pageTitleStr = res.data.home_pages.title;
						} else {
							this.pageTitleStr = res.data.home_pages.navs[0].name;
						}
					}
				);
			},
			formatBg() {
				this.myPageData.home_pages.navs.forEach((y) => {
					y.template.data.forEach((x) => {
						if (x.id == "background") {
							y.templateBg = {};
							if (x.data.showImg) {
								y.templateBg.backgroundColor = x.data.backgroundColor;
								y.templateBg.backgroundImage = `url('${x.data.backgroundPicUrl}')`;
								y.templateBg.backgroundPosition = x.data.positionText;
								y.templateBg.backgroundRepeat = "no-repeat";
								y.templateBg.backgroundSize = "auto auto";
							} else {
								y.templateBg.background = x.data.backgroundColor;
								y.templateBg.titleColor = "#000 !important";
							}
							y.templateBg.overflowY = "auto";
							y.templateBg.height = this.contentHeight + "px";
							y.templateBg.paddingTop = `${this.safeTop}px`
						}
					});
					if (!y.templateBg) {
						y.templateBg = {
							titleColor: "#000"
						};
					}
				});
			},
			changeHandler(i) {
				this.active = i;
			},
			reloadUserinfo() { 
				this.u = uni.getStorageSync("mall_UserInfo");
				this.init();
				setTimeout(() => {
					uni.removeStorageSync("LoginState")
				}, 1000);
			},
			gbAuth() {
				this.showAuth = false;
			},
			handleScroll(val) {
				this.scrollTop = val.target.scrollTop
			},
			getjump(scene) {
				let a = "YZnsGuRojCKBkb1siP3VwkhkPFvh-D"; //测试数据
				this.request({
						url: "",
						data: {
							r: "api/default/qr-code-parameter",
							token: scene,
						},
					},
					(res) => {
						uni.setStorageSync("pid", {
							pid: res.data.detail.user_id ? res.data.detail.user_id : 0,
						}); //存储上级的id
						let objurl = this.ObjectToUrl(res.data.detail.data);
						uni.navigateTo({
							url: "/" + res.data.detail.path + "?" + objurl,
						});
					}
				);
			},
			ObjectToUrl(e, t) {
				var n = "";
				for (var i in e)
					n += "&" + i + "=" + (t ? encodeURIComponent(e[i]) : e[i]);
				return n.substr(1);
			},
		},
	};
</script>

<style>
	.content {
		display: flex;
		flex-direction: column;
		width: 100%;
		overflow-x: hidden;
	}

	.index-title {
		line-height: 45px !important;
		font-size: 16px;
		text-align: center;
		position: fixed;
		left: 0;
		top: 0;
		width: 100%;
		color: #fff;
		box-sizing: content-box;
		z-index: 999999;
		background-color: #FFF;
	}

	.back-arrow {
		position: absolute;
		left: 5px;
		bottom: 10px;
		width: 60rpx;
		height: 60rpx;
		border-radius: 60rpx;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.Startbtn {
		position: absolute;
		top: 10px;
		right: 15px;
		width: 50px;
		height: 20px;
		background: rgba(45, 45, 45, 0.5);
		border-radius: 4px;
		display: flex;
		align-items: center;
		justify-content: center;
		color: #fff;
	}

	.MainTopLeft {
		text-align: left !important;
		padding-left: 10px;
	}

	.safe-top {
		height: unset !important;
		padding-bottom: 0rpx !important;
	}
</style>