<template>
	<!-- <page-meta :page-font-size="`${this.scaleFontSize}px`"  :root-font-size="`${this.scaleFontSize}px`"></page-meta> -->
	<view class="content">
		<image class="bg-img" v-show="template=='homeIndex'" src="@/static/images/pages_watch/images/home_top_bg.png"></image>
		<image class="bg-img" v-show="template=='watchIndex'" src="@/static/images/pages_watch/images/home_top_bg.png"></image>

		<view class="grace-page-header" :style="{ background:headerBG }">
			<image class="bg-img" v-show="template=='watchIndex'" src="@/static/images/pages_watch/images/home_top_bg.png"></image>
			
			<!-- 沉浸式状态栏 -->
			<view class="content-header"  id="gracePageHeader" :style="{minHeight:headerHeight+'px', height:headerHeight+'px', overflow:'hidden'}">
				<view class="content-header-l">
					<!-- <image class="address" src="@/static/image/home1/address_icon.png" mode="aspectFill"></image> -->
					<text  :class="template=='homeIndex'?'es-c-white':'es-c-33'">{{locCity}}</text>
					<!-- <image class="arrow_down" src="@/static/image/home1/arrow_down_icon.png" mode="aspectFill"></image> -->
				</view>
				<indexSubsection ref="indexSubsection" @onChange="changeTemplate" />
				<view class="content-header-r">
				<!-- 	<view @click="showQidai()">
						<image src="@/static/image/home1/weixin_icon.png" mode="aspectFill"></image>
						<text>分享</text>
					</view> -->
<!-- 					<view @click="goToMsg()">
						<image v-show="template=='homeIndex'" src="@/static/image/home1/new_icon.png" mode="aspectFill"></image>
						<image v-show="template=='watchIndex'" src="@/static/image/home/message1.png" mode="aspectFill"></image>
						<text :class="template=='homeIndex'?'es-c-white':'es-c-33'">消息</text>
					</view> -->
					<view class="x-ac" style="height: auto;display: block;">
						<image v-show="template=='homeIndex'" style="margin-right: 10px;" src="@/static/image/home1/scancode.png" mode="aspectFill" @click="handleScan()"></image>
						<image v-show="template=='homeIndex'" src="@/static/images/service_center_icon_white.png" mode="aspectFill" @click="goToWXMsg()"></image>
						<image v-show="template=='watchIndex'" style="margin-left: 50rpx;" src="@/static/images/service_center_icon_white.png" mode="aspectFill" @click="goToWXMsg()"></image>
					</view>
				</view>
			</view>
		        </view>

		<!-- 新手指引 -->
		<template v-if="template=='homeIndex'">
			<myGuide ref="myGuide" :step="step"></myGuide>
		</template>

		<!-- homeIndex -->
		<!-- pages_watch -->
		<view v-show="template=='homeIndex'">
			<homeIndex ref="homeIndex"/>
		</view>
		<view v-show="template=='watchIndex'">
			<watchIndex ref="watchIndex"/>
		</view>
		
	</view>
</template>

<script>
	import store from "@/store";
	import indexSubsection from '@/components/indexSubsection/indexSubsection'
	import homeIndex from "./components/homeIndex.vue"
	import watchIndex from "./components/watchIndex.vue"
	import { getLocation } from '@/api/index.js'
	
	// #ifdef APP-PLUS
	import permision1 from "@/utils/permission.js"
	import { premissionCheck } from "@/js_sdk/wa-permission/permission.js"
	const idCode = uni.requireNativePlugin('Ba-IdCode')
	// #endif
	// const idCode = uni.requireNativePlugin('Ba-IdCode')
	export default {
		components: {
			indexSubsection,
			homeIndex,
			watchIndex
		},
		data() {
			return {
				template: 'homeIndex', // homeIndex:首页 ， watchIndex: 腕表页面
				option: "",
				top:0,
				statusBarBG:"none",
				headerHeight:44,
				locCity:"",
				// locCity:"云联商城",
				scaleFontSize:uni.getStorageSync("fontSize"),
				step: {
						name: 'indexguide',
						guideList: [{
							el: '',
							tips: '上下滑动，了解云联商城',
							next: '',
						}
						// ,{
						// 	el: '#indexguide1',
						// 	tips: '药膳、经络、疾病医学百科知识快速查询',
						// 	next: '下一步',
						// },{
						// 	el: '#indexguide2',
						// 	tips: '权威医生、药师实时在线咨询',
						// 	next: '下一步',
						// },{
						// 	el: '#indexguide3',
						// 	tips: '免费健康自测，了解自身健康情况',
						// 	next: '下一步',
						// },{
						// 	el: '#indexguide4',
						// 	childEl: ".indexguide4-child",
						// 	tips: '购买健康疗法享健康',
						// 	next: '完成',
						// },
						]
					}
				
			}
		},
		onPageScroll(e) {
			if(this.template=='homeIndex') {
				this.top=e.scrollTop;
			}
		},
		computed: {
			// 计算属性的 getter
			headerBG() {
				if(this.template=='homeIndex') {
					var top=this.top/88;
					return 'rgba(253,240,220, ' + top + ')';
				}
			},
		},
		onLoad(option) {
			// #ifdef APP-PLUS
				   if(plus.runtime.isAgreePrivacy()) {
						const guide = uni.getStorageSync(this.step.name);
						if(!!guide){
							//permision1.checkPush();
						}
						//this.doGetLocation();
				   }
			// #endif
			
			let that=this;
			uni.setNavigationBarTitle({
				title: that.$qconfig.appName
			});
			uni.setStorageSync("indexTemplate",0)
			this.option = option;
			this.scaleFontSize=store.state.timStore.fontSize;
			// this.$nextTick(()=>{
			// 	  this.$refs[this.template].initLoad(this.option)
			// })
		},
		onReady() {
			this.$refs.indexSubsection.selectorQuery()
			this.$refs[this.template].initReady()
		},
		onShow() {
	        // #ifdef APP-PLUS
	        	   if(plus.runtime.isAgreePrivacy()) {
	        			if(plus.runtime.channel=="baidu"){ 
	        				let bdCmdType=uni.getStorageSync("bdCmdType");
	        				if(this.$isEmpty(bdCmdType)){
	        					this.$registerIdCode("activate",0,0);
	        				}
	        			}
	        	   }
	        // #endif
			if(!this.$isLogin()){
				uni.navigateTo({
					url: '/pages/auth/loginIndex'
				})
			} else {
				this.$updateMsgDot();
			}
			this.$nextTick(()=>{
				this.$refs[this.template].initShow()
			});
			
		},
		methods: {
		
			changeTemplate(e) {
				const tem = e == 1 ? 'watchIndex' : 'homeIndex'
				if(this.template == tem) return
				this.template = tem
				uni.pageScrollTo({
					scrollTop: 0,
					duration: 100
				});
				this.$nextTick(()=>{
					//this.$refs[this.template].initLoad(this.option)
					this.$refs[this.template].initReady()
					this.$refs[this.template].initShow()
				})
			},
			registerIdCode() { //注册，先注册再获取，注意APP合规性，若最终用户未同意隐私政策则不要调用
				idCode.register(res => {
					console.log(res);
				});
			},
			async getLocation() {
				   let status;
				// #ifdef APP-PLUS
					status = await this.checkPermission();
					if (status !== 1) {
						return;
					}
				// #endif
				// #ifdef MP-WEIXIN || MP-TOUTIAO || MP-QQ
					status = await this.getSetting();
					if (status === 2) {
						this.showConfirm();
						return;
					}
				// #endif
				this.doGetLocation();
			},
			doGetLocation() {
				getLocation().then(res => {
					this.locCity  =  res.city.replace(/市|区/g,  '');
				});		
			},
			getSetting: function() {
			    return new Promise((resolve, reject) => {
			        uni.getSetting({
			            success: (res) => {
			                if (res.authSetting['scope.userLocation'] === undefined) {
			                    resolve(0);
			                    return;
			                }
			                if (res.authSetting['scope.userLocation']) {
			                    resolve(1);
			                } else {
			                    resolve(2);
			                }
			            }
			        });
			    });
			},
			openSetting: function() {
			    this.hideConfirm();
			    uni.openSetting({
			        success: (res) => {
			            if (res.authSetting && res.authSetting['scope.userLocation']) {
			                this.doGetLocation();
			            }
			        },
			        fail: (err) => {}
			    })
			},
			async checkPermission() {
			    let status = permision1.isIOS ? await permision1.requestIOS('location') :
			        await permision1.requestAndroid('android.permission.ACCESS_FINE_LOCATION');
			    if (status === null || status === 1) {
			        status = 1;
			    } 
				else if (status === 2) {
			        uni.showModal({
			            content: "系统定位已关闭",
			            confirmText: "确定",
			            showCancel: false,
			            success: function(res) {
			            }
			        })
			    } else if (status.code) {
			        uni.showModal({
			            content: status.message
			        })
			    } else {
			        uni.showModal({
			            content: "需要定位权限",
			            confirmText: "设置",
			            success: function(res) {
			                if (res.confirm) {
			                    permision1.gotoAppSetting();
			                }
			            }
			        })
			    }
			    return status;
			},
			
			showQidai(){
				uni.showToast({title: "功能完善中,敬请期待...",icon:"none"});
			},
			goToMsg(){
				  uni.switchTab({
					  url: '/pages/TUIKit/TUIPages/TUIConversation/index' 
				  });
			},
			async goToWXMsg(){
				const url = getApp().globalData.kfurl //企业微信客服链接
				const corpId = getApp().globalData.corpId //企业id
				// #ifdef H5
					window.location.href = url
				 // #endif 
				 // #ifdef MP-WEIXIN
				 wx.openCustomerServiceChat({
				 	extInfo: {
				 		url
				 	},
				 	corpId,
				 	success(res) {
				 		console.log('成功');
				 	},
				 	fail(err) {
				 		console.log(err, '报错');
				 	}
				 })
				 // #endif 
				 			
				 // #ifdef APP-PLUS 
				let shares = await this.getAppShare().catch(err => {
					throw Error(err)
				});
				shares['weixin'].openCustomerServiceChat({
					corpid: corpId,
					url
				}, suc => {
					console.log("客服打开成功", JSON.stringify(res))
				}, err => {
					console.log("error", JSON.stringify(err))
				})
				 // #endif   
			},
			getAppShare() {
			   // #ifdef APP-PLUS
					return new Promise((re, rj) => {
						let shares = null;
						var pusher = plus.share.getServices(function(s) {
							shares = {};
							s.forEach(e => shares[e.id] = e);
							re(shares)
						}, function(e) {
							rj(e);
						});
					});
				// #endif 
			},
			getIdCodes() { //获取设备的各种标识码
				idCode.getIdCodes(res => {
					if (res.data) {
						//this.msgList.unshift(JSON.stringify(res.data));
						let ua=plus.navigator.getUserAgent();
						console.log("qxj ua:"+ua);
						console.log("qxj getIdCodes:"+JSON.stringify(res.data));
					}
				});

			 },
			 getOAID() { //异步获取 OAID
				idCode.getOAID(res => {
					if (res.data) {
						//this.msgList.unshift(JSON.stringify(res.data));
						console.log("qxj getOAID:"+JSON.stringify(res.data));
					}
				});
			},
			//扫码
			async handleScan() {
				// #ifdef APP-PLUS
					let status = await this.checkAppCamera()
					if(status == 1) {
						uni.navigateTo({
							url: '/pages_watch/healthMonitoring/scanCode?typeFun=getIndexScanCode'
						})
					}
				// #endif
				// #ifdef MP-WEIXIN
					this.checkWXCamera()
				// #endif
			},
			scanQRCode() {
				const that = this
			    uni.scanCode({
			        success(res) {
			            if (res.result) {
			                // 扫描成功，处理二维码内容
			                console.log('扫描结果：', res.result);
							const scanInfo = res.result
							if(scanInfo&&scanInfo.indexOf("https://userapp.his.cdwjyyh.com/bindcompanyuser")>-1){
								const companyUserId = this.getUrlParam(scanInfo).companyUserId
								 console.log('扫描结果公司码：', companyUserId);
								this.$handleBindCompanyFsUser(companyUserId)
							}
			            } else {
			                // 扫描失败
			                uni.showToast({
			                    title: '扫描失败',
			                    icon: 'none'
			                });
			            }
			        },
			        fail() {}
			    });
			},
			getUrlParam(url) {
				const queryStr = url.split('?')[1];
				if (!queryStr) {
				  return {};
				}
				const params = queryStr.split('&');
				const queryParams = {};
				params.forEach(param => {
				  const [key, value] = param.split('=');
				  queryParams[key] = value;
				});
				return queryParams;
			},
			async checkAppCamera() {
				let status = permision1.isIOS ? await permision1.requestIOS("camera") : await permision1.requestAndroid("android.permission.CAMERA")
				if(status === null || status == 1) {
					status == 1 
				} else if(status == 2) {
					uni.showModal({
						content: "相机权限已关闭",
						showCancel: false,
						success: () => {}
					})
				} else if(status.code) {
					uni.showModal({
						content: status.message
					})
				} else {
					uni.showModal({
						content: "为了使用相机功能，请点击设置开启相机权限",
						confirmText: "设置",
						success: (res) => {
							if(res.confirm) {
								permision1.gotoAppSetting()
							}
						}
					})
				}
				return status
			},
			checkWXCamera() {
				const that = this
				uni.getSetting({
					success(res) {
						// 判断是否拥有此权限进行拉起授权  和 重新授权功能
						if (!res.authSetting['scope.camera']) {
							// 未授权此项权限 拉起授界面
							uni.authorize({
								scope: 'scope.camera',
								success() {
									// 授权成功后 就可以执行 需要权限的  操作函数了
									// 使用已授权的功能
									that.scanQRCode();
								},
								fail(err) {
									/*
									 第一次拒绝授权后必须在 uni.authorize的fail中使用
									 uni.openSetting 才能进入设置界面打开授权按钮
									 */
									uni.showToast({
										title: '您拒绝了授权',
										icon: 'none'
									});
									// 这里必须经过一个confirm 不然也会出现问题（啥问题我也不知道）
									uni.showModal({
										title: '是否重新授权相机功能',
										success(res) {
											if (res.confirm) {
												uni.openSetting({
													success() {
														console.log('开启权限成功');
													},
													fail() {
														console.log('开启权限失败');
													}
												});
											} else if (res.cancel) {
												console.log('拒绝开启开启权限');
											}
										}
									});
								}
							});
						} else {
							that.scanQRCode()
						}
					}
				});
			}
		}
	}
</script>

<style lang="scss" scoped>
	@mixin u-flex($flexD, $alignI, $justifyC) {
		display: flex;
		flex-direction: $flexD;
		align-items: $alignI;
		justify-content: $justifyC;
	}
	.nav-bar {
		background-color: red;
		// background-image: url("@/static/image/home/home_top_bg.png");
		// background-repeat: no-repeat;
		// background-size: 100%;
		// background-color: #F4F7FA;
		// position: absolute;
		// width: 100%;
		// height: 524rpx;
	}
	.content {
		width: 100%;
		box-sizing: border-box;
		// overflow: hidden;
		// margin-top: var(--status-bar-height);
		// padding-top: 24rpx;
		font-family: PingFang SC, PingFang SC;
		font-weight: 400;
		font-size: 24rpx;
		color: #999999;
		// background-image: url("@/static/image/home/home_top_bg.png");
		background-repeat: no-repeat;
		background-size: 100%;
		
		// box-sizing: border-box;
		// padding-top: calc(var(--status-bar-height) + 24rpx);
		// padding-bottom: var(--window-bottom);
		// font-family: PingFang SC, PingFang SC;
		// font-weight: 400;
		// font-size: 24rpx;
		// color: #999999;
		position: relative;
		z-index: 2;
		.bg-img{
			position: absolute;
			width: 100%;
			height: 524rpx;
			top: 0;
			left: 0;
			right: 0;
			bottom: 0;
			z-index: 0;
		}
		.bgConent{
			background-image: url("@/static/image/home/home_top_bg.png");
			background-repeat: no-repeat;
			background-size: 100%;
			background-color: #F4F7FA;
			position: absolute;
			width: 100%;
			height: 524rpx;
			top: 0;
			left: 0;
			right: 0;
		    bottom: 0;
			z-index: 0;
		}
		.grace-page-header {
			position: fixed;
			width: 100%;
			left: 0;
			top: 0;
			z-index: 98;
			border-bottom: 0px solid #FFFFFF;
			padding-top: calc(var(--status-bar-height));
			box-sizing: border-box;
			overflow: hidden;
		}
		.content-header {
			height: 80rpx;
			padding: 0 24rpx;
			@include u-flex(row, center, space-between);
			position: relative;
			z-index: 2;
			&-l {
				font-family: PingFang SC, PingFang SC;
				font-weight: 500;
				font-size: 26rpx;
				color: #FFFFFF;
				line-height: 28rpx;
				@include u-flex(row, center, flex-start);
				.address {
					width: 38rpx;
					height: 38rpx;
					margin-right: 6rpx;
				}
				.arrow_down {
					width: 24rpx;
					height: 24rpx;
					margin-left: 8rpx;
				}
			}
			&-r {
				@include u-flex(row, center, flex-start);
				view {
					font-family: PingFang SC, PingFang SC;
					font-weight: 400;
					font-size: 22rpx;
					color: #FFFFFF;
					line-height: 24rpx;
					@include u-flex(column, center, space-between);
					// width: 80rpx;
					// height: 80rpx;
					padding-top:2rpx;
					padding-bottom: 6rpx;
					
				}
				image {
					width: 40rpx;
					height: 40rpx;
				}
			}
		}
	}
	.indexSubsection {
		position: fixed;
		top: calc(var(--status-bar-height) + 24rpx);
		left: 50%;
		transform: translateX(-50%);
		z-index: 9999;
		height: 88rpx;
		line-height: 88rpx;
		display: inline-flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
	}
</style>