<template>
	<view>
		<view @touchstart="touchStart" @touchmove="move" @touchend="end">
			<view class="cons" :style="'height:'+systems.windowHeights+'rpx;'">
				<view class="banner">
					<image :src="merchant.mainGraph" mode="aspectFill" :style="'height:'+(500+conTop) + 'rpx;'" :class="isPlay==1?'isPlay':isPlay==2?'isPlaasf':''"></image>
				</view>
				<!-- <view @click="saoma()" style="z-index: 999;position: relative;">扫码</view> -->
				<view class="con-ss" :style="'top:'+conTop+'rpx'">
					<view class="top">
						<view class="merchant ddflex" v-if="merchant">
							<image :src="merchant.logo" mode="aspectFill" class="m-logo"></image>
							<view class="fflex" v-if="merchant && merchant.title">
								<view class="m-name ddflex">
									<view  @click="jumpUrl('/topic/about/about?id='+merchant.id)">{{ getMerchantTitle() }}</view>
									<view class="change ddflex" @click="merchantFun()" v-if="config.Many_Store == 1">切换门店<image src="../../static/pages/images/change.png"></image></view>
								</view>
								<view class="m-bot ddflex" v-if="merchant.label">
									<view class="m-tag ddflex fflex">
										<text v-for="(it,idx) in merchant.label.split(',')" :key="index">{{it}}</text>
									</view>
									<!-- <image :src="picUrlss+'lvluo/gsjs_ico.png'" class="gsjs-ico" @click.stop="jumpUrl('/topic/about/about')"></image> -->
								</view>
							</view>
							<view class="fflex" v-else>
								<view class="m-name ddflex">
									绿萝云·私域诊所系统
									<image src="../../static/pages/images/change.png"></image>
								</view>
								<view class="m-bot ddflex">
									<view class="m-tag ddflex fflex">
										<text>医疗营业许可</text>
										<text>到店分期</text>
									</view>
									<image :src="picUrlss+'lvluo/gsjs_ico.png'" class="gsjs-ico" @click.stop="jumpUrl('/topic/about/about')"></image>
								</view>
							</view>
						</view>
						<view class="card" :style="'height:'+cardHeight+'rpx;'">
							<image :src="picUrlss+'lvluo/logo_lv.png'" class="logo"></image>
							<image :src="picUrlss+'lvluo/card_logo.png'" class="card-logo"></image>
							<view class="card-top">
								<view class="card-no">NO.{{userinfoVip.userCode?userinfoVip.userCode:'000000'}}</view>
								<view class="card-info ddflex">
									<view class="fflex">
										<view class="card-name">{{userinfoVip.levelName?userinfoVip.levelName:'家庭爱牙卡'}}</view>
										<view class="card-user">{{userinfoVip.realName?userinfoVip.realName:userinfoVip.nickName?userinfoVip.nickName:'代名'}}<text>{{userinfoVip.cardNo ? userinfoVip.cardNo:'8888**********8888'}}</text></view>
									</view>
									<image :src="picUrlss+'lvluo/card_ma.png'" class="card-ma" @click="jumpUrl('/mine/payCode/payCode')"></image>
								</view>
								<image :src="userinfoVip.icon" mode="heightFix" class="vip-img" v-if="userinfoVip.icon"></image>
							</view>
							<view class="card-bot">
								<view class="datas ddflex">
									<view class="li" @click="jumpUrl('/wallet/index/index')">
										<view class="numbers" v-if="isShowBalance">{{userInfo.balance ? userInfo.balance : 0}}</view>
										<view class="numbers" v-else>****</view>
										<view class="ddflex">余额<image :src="picUrlss+(isShowBalance?'lvluo/eye_shows.png':'lvluo/eye_hides.png')" class="card-eye" @click.stop="optBalance"></image></view>
									</view>
									<view class="li" @click="jumpUrl('/service/secondCard/secondCard')">
										<view class="numbers">{{cardCount?cardCount:0}}</view>
										<view>权益卡</view>
									</view>
									<view class="li" @click="jumpUrl('/mine/coupons/coupons')">
										<view class="numbers">{{userInfo.coupon?userInfo.coupon:0}}</view>
										<view>优惠券</view>
									</view>
								</view>
								<block v-if="doctor&&doctor.id">
								<view class="zhuanshu-t ddflex">
									<image :src="picUrlss+'lvluo/card_zhuanshu.png'"></image>
								</view>
								<view class="zhuanshu-info ddflex" @click="jumpUrl('/topic/teacherDet/teacherDet?id='+doctor.id)">
									<image :src="doctor.headUrl ? doctor.headUrl : picUrlss+'lvluo/zhuanshu_img.png'" mode="aspectFill" class="zhuanshu-img"></image>
									<view class="fflex">
										<view class="zhuanshu-name ddflex">{{doctor.username}}<text v-if="doctor.label"><block v-for="(it,idx) in doctor.label.split(',')" :key="idx" v-if="idx == 0">{{it}}</block></text></view>
										<view class="zhuanshu-mobile">{{doctor.mobile}}</view>
									</view>
									<image :src="picUrlss+'lvluo/zhuanshu_weixin.png'" class="zhuanshu-weixin"></image>
								</view>
								</block>
							</view>
							<button class="open-card ddflex" open-type="getPhoneNumber" @getphonenumber="getPhoneNumber" hover-class="none" v-if="!userinfoVip.levelGrade || (userinfoVip.levelGrade > 0 && userinfoVip.end)">
								<image :src="picUrlss+'lvluo/open_ico.png'"></image>
								<view>一键领取健康卡</view>
							</button>
						</view>
					</view>
					<view class="bottom">
						<view class="bot-name">湖南绿萝口腔集团有限公司</view>
						<view class="bot-xuke ddflex">医疗执业许可证<image :src="picUrlss+'lvluo/bot_xuke.png'" @click="scanCode()"></image></view>
					</view>
				</view>
			</view>
			<view class="coupon" @click="jumpUrl('/product/couponList/index')">
				<view class="coupon-img"><image :src="picUrlss+'lvluo/quan_img.png'"></image></view>
				<view class="coupon-text">领券中心</view>
			</view>
			<navigator :url="'/other/contact/index?id='+advisor.id" hover-class="none" class="contact" v-if="advisor&&advisor.id">
				<image :src="advisor.headUrl ? advisor.headUrl : picUrlss+'lvluo/fixed_img.png'" mode="aspectFill"></image>
				<view class="contact-text">{{advisor.realName}}<text>服务顾问</text></view>
			</navigator>
			<button open-type="contact" hover-class="none" class="contact" v-else>
				<image :src="picUrlss+'lvluo/fixed_img.png'"></image>
				<view class="contact-text">杨经理<text>服务顾问</text></view>
			</button>
		</view>
		<!-- <button open-type="contact" hover-class="none" class="contact" v-else>
			<image :src="picUrlss+'lvluo/fixed_img.png'"></image>
			<view class="contact-text">杨经理<text>健康顾问</text></view>
		</button> -->
		<footer-copyright></footer-copyright>
		<!-- #ifdef MP-WEIXIN -->
		<foot channel="home" :isUpdate="isUpdate"></foot>
		<!-- #endif -->
		<update-userinfo
			:update-info="isUpdateInfo"
			:update-mobile="isUpdateMobile"
			v-if="isShowUpdate"
			@closeUpdate="closeUpdate"
			@updateInfo="updateInfo"
			@updateMobile="updateMobile"
		></update-userinfo>
		<!-- #ifdef H5 -->
		<wx-share ref="wxshare" />
		<!-- #endif -->
	</view>
</template>

<script>
//index.js
//获取应用实例
const app = getApp();
const req = require('../../utils/request.js');
const api = require('../../utils/api.js');
const utils = require('../../utils/util.js');
const mes = require('../../utils/requestmessage.js');
const route = require('../../utils/route');
const QQMapWX = require('../../utils/qqmap.js');
import foot from '../../components/nav-bar/index';
import footerCopyright from '../../components/footer-copyright/footer-copyright';
export default {
	data() {
		return {
			picUrlss: req.public.picUrls,
			isUpdate: false, // 是否更新消息
			config: {},
			systems: {},
			merchant: '',
			cardHeight: 800,
			userinfoVip: {},
			userInfo: {},
			clientData: {
				// 用户手指Y轴
				clientStartY: '', //开始按下的位置
				clientMoveY: '', //按下
				clientEndY: '', //抬起
				// 页面Y轴
				pageY: ''
			},
			sheight: 100,
			isPlay: 0, //是否播放动画
			isRefresh: true,
			cardCount: '',//次卡数量
			isShowBalance: true,
			chatPrams: '',//客服类型
			conTop: '',
			pxToRpxScale: '',//比例
			doctor: '',//专属医生
			advisor: '',//服务顾问
			sessionKey: '',
			scene: '',
			
			isShowUpdate: false, //是否显示更新信息弹窗
			isUpdateInfo: false, //更新用户信息
			isUpdateMobile: false, //绑定手机号
		};
	},

	components: {
		foot,
		footerCopyright
	},
	props: {},
	onLoad: async function(options) {
		this.query = options;
		console.log('首页参数',options,options.scene)
		if(options.scene){
			this.scene = options.scene;
			await this.loadCode();
		}else{
			req.silenceLogin(options.userId, '');
		}
		QQMapWX.initMap(req.public.mapLBSKEY);
		req.getLocation(res => {
			const to = {
				latitude: res.latitude,
				longitude: res.longitude
			};
			QQMapWX.reverseGeocoder(to, resp => {
				if(req.isAuth()){
					this.getuserVip();
					this.getUserInfo();
					this.getCardCount();
					this.getShowUpdata();
				}
			});
		});
		app.globalData.getCheckSessoin(json => {
			this.sessionKey = json.session_key;
		});
	},
	onHide(){
		if(this.isPlay == 1){
			this.isPlay = 2;
		}
	},

	async onShow() {
		let _ts = this;
		_ts.getChatPrams();
		if(isLogin){
			_ts.getuserVip();
			_ts.getUserInfo();
			_ts.getCardCount();
		}
		await this.getConfig().then(async res => {
			await _ts.getMerchant();
			if(this.isRefresh){
				await _ts.getViewInfo();
			}
			await _ts.getDoctor();
			await _ts.getAdvisor();
		});
		let isLogin = req.isAuth();
	},

	onShareAppMessage: function() {
		return this.onShareMessage();
	},
	onShareTimeline() {
		return {
			title: this.getShareTitle(),
			query: this.getSharePath()
		};
	},
	onUnload() {
		
		this.isPlay = 2;
	},
	onReady() {
		// #ifdef H5
		var that = this;
		//初始化分享内容
		setTimeout(function() {
			var shareContent = that.onShareMessage();
			if (shareContent) {
				shareContent.path = window.location.origin + shareContent.path;
			}
			console.log('分享内容》》》》》', shareContent);
			that.$refs.wxshare.init(shareContent);
		}, 4 * 1000);
		// #endif
	},
	
	methods: {
		onShareMessage(){
			return {
				title: this.getShareTitle(),
				path: this.getSharePath()
			};
		},
		
		getShowUpdata(){
			// #ifdef MP-WEIXIN||MP-TOUTIAO
			let userInfo = req.getStorage('userInfo');
			if (req.isAuth()) {
				setTimeout(res => {
					console.log('setTimeoutuserInfo》》》》', userInfo);
					if (!userInfo.avatar || userInfo.nickName == '微信用户') {
						this.isShowUpdate = true;
						this.isUpdateInfo = true;
					}
					if (userInfo.avatar && !userInfo.mobile && (this.userInfo && !this.userInfo.mobile)) {
						this.isShowUpdate = true;
						this.isUpdateMobile = true;
					}
				}, 2000);
			}
			// #endif
		},
		loadCode() {
			let _ts = this;
			console.log('解码参数scene==',_ts.scene)
			return new Promise((resolve, reject) => {
				let form = {
					scene: _ts.scene
				};
				req.getRequest('/api/code/params', form, data => {
					console.log('解码参数==',data)
					req.silenceLogin(data.userId, '');
					req.setStorage('pidCode', data.userId);
					resolve();
				});
			});
		},
		getPhoneNumber(event) {
			// console.log('绑定手机号==',event)
			const detail = event.detail;
			const _ts = this;
			if (!detail || !detail.encryptedData || !detail.iv) return false;
			req.postRequest('/api/weixin/mobile', {
				encryptedData: detail.encryptedData,
				iv: detail.iv,
				sessionKey: _ts.sessionKey
			}, res => {
				console.log('res==',res)
				if(res.mobile){
					var userInfo = req.getStorage('userInfo');
					userInfo.mobile = res.mobile;
					req.setStorage('userInfo', userInfo);
					_ts.jumpUrl('/open/info/index');
				}
			});
		},
		getDoctor(){
			return new Promise((resolve,reject)=>{
				req.getRequest('/api/v3/user/doctor',{},data=>{
					console.log('医生==',data)
					this.doctor = data;
					resolve();
				})
			})
		},
		getAdvisor(){
			return new Promise((resolve,reject)=>{
				req.getRequest('/api/distribution/advisorInfo',{},data=>{
					console.log('服务顾问==',data)
					this.advisor = data;
					resolve();
				})
			})
		},
		customerServiceChat() {
			let chatPrams = this.chatPrams;
			wx.openCustomerServiceChat({
				extInfo: {
					url: chatPrams.url
				},
				corpId: chatPrams.enterpriseId,
				success(res) {
					console.log('调用微信客服')
				}
			})
		},
		getChatPrams() {
			let that = this;
			let chatPrams = req.getStorage('chatService');
			if(chatPrams){
				that.chatPrams = chatPrams;
				that.type = chatPrams.type;
				console.log('type==', that.type)
				that.$forceUpdate();
			}
		},
		optBalance(){
			this.isShowBalance = !this.isShowBalance;
			req.setStorage('isShowBalance',this.isShowBalance);
		},
		touchStart(e){
			// console.log('开始移动==',e)
			this.clientData.clientStartY = e.changedTouches[0].clientY;
		},
		move(e) {
			// console.log('触摸移动==',e);
			if (this.clientData.pageY < 1) {
				let distance = e.changedTouches[0].clientY - this.clientData.clientStartY;
				if(this.isPlay != 1){
					if(distance > 0){
						if(distance > this.sheight){
							this.conTop = this.sheight*this.pxToRpxScale;
						}else{
							this.conTop = distance*this.pxToRpxScale;
						}
					}
				}
				if (distance > this.sheight) {
					this.isPlay = 1;
					this.conTop = 0;
				} else {
					return;
				}
			}
		},
		// 手指抬起
		end(e) {
			let endY = e.changedTouches[0].clientY;
			let subY = endY - this.clientData.clientStartY;
			this.conTop = 0;
			if (subY < -50) {
				console.log('上滑')
				if(subY*-1 > this.sheight){
					if(this.isPlay == 1){
						uni.pageScrollTo({
							duration: 300,
							scrollTop: 0
						})
						this.isPlay = 2;
					}
				}
			} else if (subY > 50) {
				console.log('下滑')
				if(subY > this.sheight){
					this.isPlay = 1;
				}else{
					uni.pageScrollTo({
						duration: 300,
						scrollTop: 0
					})
				}
			}else{
				uni.pageScrollTo({
					duration: 300,
					scrollTop: 0
				})
			}
		},
		getUserInfo(){
			req.getRequest('/api/user/my',{},data=>{
				this.userInfo = data;
				if(req.getStorage('isShowBalance') != ''){
					this.isShowBalance = req.getStorage('isShowBalance');
				}else{
					this.isShowBalance = true;
				}
			})
		},
		getCardCount(){
			req.getRequest('/api/v3/secondary/card/count',{},data=>{
				this.cardCount = data;
			})
		},
		getuserVip() {
			req.getRequest('/api/user/levelDetails', {}, data => {
				let expireTime = Array;
				if (data.expireTime) {
					expireTime = data.expireTime.split(' ');
					data.expireTime = data.expireTime.replace(/-/g, '/');
				}
				let nowTime = new Date().getTime();
				let endTime = new Date(data.expireTime).getTime();
				let times = parseInt((endTime - nowTime) / 1000);
				if(data.cardNo) data.cardNo = data.cardNo.replace(/(.{4}).*(.{4})/, '$1********$2');
				this.userinfoVip = data;
				this.userinfoVip.expireTime = expireTime[0];
				if (times <= 0) {
					this.userinfoVip.end = true;
				} else {
					this.userinfoVip.end = false;
				}
			});
		},
		getSharePath() {
			let path = '/pages/index/index?isShare=' + true+'&appId='+req.getStorage('appId');
			if (req.getStorage('userInfo')) {
				path += '&userId=' + req.getStorage('userInfo').id;
			}
			if (req.getStorage('MERCHANT') && req.getStorage('MERCHANT').id != null) {
				path += '&merchantId=' + req.getStorage('MERCHANT').id;

				if (req.getStorage('smallShop') && req.getStorage('MERCHANT').id != null) {
					path += '&shopId=' + req.getStorage('smallShop').id;
				}
			}
			return path;
		},

		getShareTitle() {
			let title = '';
			if (this.merchant && this.merchant.title && this.merchant.title != '默认门店') {
				title = this.merchant.title;
			} else {
				title = this.config.CONFIG_PROJECT_TITLE;
			}
			return (req.excludeSpecial(req.getStorage('userInfo').nickName) ? req.excludeSpecial(req.getStorage('userInfo').nickName) : '') + '为你推荐' + title;
		},

		/**
		 * 显示门店标题
		 */
		getMerchantTitle() {
			let title = '';
			if (this.merchant && this.merchant.title && this.merchant.title != '默认门店') {
				if (this.merchant.title.length > 12) {
					title = this.merchant.title.substring(0, 12) + '...';
				} else {
					title = this.merchant.title;
				}
			} else {
				title = this.config.CONFIG_PROJECT_TITLE;
			}
			return title;
		},
		callPhone() {
			uni.makePhoneCall({
				phoneNumber: this.merchant.phone
			});
		},

		merchantFun() {
			app.globalData.openPage('merchant/nearby/nearby');
		},
		getConfig() {
			return new Promise((resolve, reject) => {
				req.getRequest('/api/config', {}, data => {
					req.setStorage('configRes', JSON.stringify(data));
					this.config = data;
					resolve();
				});
			});
		},
		getMerchant() {
			let _ts = this;
			return new Promise((resolve, reject) => {
				api.getMerchant(_ts.query, req, data => {
					console.log('===', data);
					if (data == 1) {
						uni.showModal({
							title: '温馨提示',
							content: '获取定位失败，请前往设置打开定位权限',
							showCancel: false,
							success(res) {
								if (res.confirm) {
									// console.log('用户点击确定');
									uni.openSetting({
										success(res) {
											console.log(res.authSetting); // res.authSetting = {
										}
									});
								}
							}
						});
					} else {
						_ts.merchant = data;
					}
					resolve();
				});
			});
		},
		getViewInfo(){
			let that = this;
			const systemInfo = uni.getSystemInfoSync();
			let pxToRpxScale = 750 / systemInfo.windowWidth;
			return new Promise((resolve, reject) => {
				const query = uni.createSelectorQuery();
				query.select('.merchant').boundingClientRect(res => {
					let height = res.height*pxToRpxScale + res.top*pxToRpxScale+40
					that.cardHeight =  that.systems.windowHeight - height;
				}).exec();
				setTimeout(res=>{
					query.select('.bottom').boundingClientRect(data => {
						let height = data.height*pxToRpxScale;
						that.cardHeight =  that.cardHeight - height - 115 - that.systems.safeBottomHeight;
						that.isRefresh = false;
					}).exec();
				},200)
				resolve();
			})
		},

		jumpVip(url) {
			if (req.isLogins(true)) {
				let userInfo = req.getStorage('userInfo');
				if (userInfo.levelId && userInfo.levelId > 0) {
					uni.navigateTo({
						url: '/mine/vip/vip'
					});
				} else {
					uni.navigateTo({
						url: url
					});
				}
			}
		},

		jumpUrl(url) {
			if (req.isLogins(true)) {
				uni.navigateTo({
					url: url
				});
			}
		},
		scanCode() {
			var _this = this; // 允许从相机和相册扫码
			uni.scanCode({
				success: res => {
					console.log('扫码结果1111==',res)
					let path = res.path.split('?scene=')[0];
					let scene = res.path.split('?scene=')[1];
					let paths = '/'+path + '?scene=' +encodeURIComponent(scene);
					console.log('paths===',paths)
					uni.navigateTo({
						url: paths
					}); // this.scene = '1290926887903780865';
				}
			});
		},
		closeUpdate() {
			this.isShowUpdate = false;
		},
		updateInfo(e) {
			this.isUpdateInfo = e;
			this.getuserVip();
			this.getUserInfo();
		},
		updateMobile(e) {
			this.isUpdateMobile = e;
			this.jumpUrl('/open/info/index');
		},
	},
	beforeMount() {
		const systemInfo = uni.getSystemInfoSync();
		console.log('systemInfo==',systemInfo)
		// px转换到rpx的比例
		let pxToRpxScale = 750 / systemInfo.windowWidth;
		this.pxToRpxScale = pxToRpxScale;
		let systems = {
			ktxStatusHeight: systemInfo.statusBarHeight * pxToRpxScale, // 状态栏的高度
			navigationHeight: 44 * pxToRpxScale, // 导航栏的高度
			windowHeight: systemInfo.screenHeight * pxToRpxScale ,// 导航栏的高度
			safeBottomHeight: systemInfo.safeAreaInsets.bottom * pxToRpxScale
		};
		systems.barHeight = systems.ktxStatusHeight + systems.navigationHeight;
		systems.windowHeights = systems.windowHeight - 115- systems.safeBottomHeight;
		// this.sheight = (500/pxToRpxScale)/2;
		this.systems = systems;
		console.log('systems==',systems)
	},
	onPageScroll(e) {
		this.clientData.pageY = e.scrollTop;
	},
};
</script>
<style>
@import './index.css';
</style>
