<template>
	<view id="topId">
		<!-- <view :class="'top-fixed' + (skinNotColor ? ' not-color' : '')" :style="'height: '+ systems.barHeight + 'rpx;'">
			<view :class="'bgcolor' + (isTop == 1 ? ' opacity' : '')" :style="'height:' + systems.barHeight + 'rpx'"></view>
			<view class="top-fixed-c" :style="'height: '+ systems.navigationHeight + 'rpx;margin-top:' + systems.ktxStatusHeight + 'rpx;'">
				<navigator url="" hover-class="none" open-type="navigateBack" class="back"><image :src="picUrlss+'back_black.png'"></image></navigator>
				<view class="top-title tover" :style="'line-height: '+ systems.navigationHeight + 'rpx;'" v-if="isTop == 1">{{params.title}}</view>
			</view>
		</view>
		
		<view :style="'height:'+(systems.barHeight?systems.barHeight:44)+'rpx;'"></view> -->
		
		<view class="side" :class="specClassSide" @tap="showSide">
			<image src="../static/images/share_close.png" class="share-close" @click.stop="hideSide"></image>
			<view class="share" @tap="showShare()"><image src="../static/images/share_img.png"></image></view>
		</view>
		
		<view id="topId">
			
			<!-- <view class="title">{{ params.title }}</view> -->
			<!-- <view class="det-sta ddflex">
				<view class="sort" v-if="params.cateName">{{params.cateName}}</view>
				<view class="sort-line" v-if="params.cateName"></view>
				<view class="time" style="color: #5B698F;">
					{{(params.user && params.user.nickName)?params.user.nickName:config.CONFIG_PROJECT_TITLE}}
				</view>
				<view class="time" style="margin-left: 10rpx;">
					{{formatTime(params.createDate)}}
				</view>
			</view> -->
			
			<view :class="'viewMore' + (viewMoress?' con-vheight':'')" :style="'max-height:' + height">
				<block v-for="(item,index) in params.params.jsonContent" :key="index">
					<view class="ban" v-if="item.key == 'banner'">
						<swiper class="swiper" @change="swiperChange" autoplay="true" interval="5000" duration="300">
							<block v-for="(it, idx) in item.value.imageList" :key="idx">
								<swiper-item>
									<image lazy-load="true" :src="it.src" mode="aspectFill" @click="clickBanner(item)"></image>
								</swiper-item>
							</block>
						</swiper>
						<view class="dots ddflex">
							<block v-for="(it, idx) in item.value.imageList" :key="idx"><view :class="['dot', idx == swiperCurrent ? 'active' : '']"></view></block>
						</view>
					</view>
					<view class="form" v-if="item.key == 'applicationForm'" :id="item.elementId">
						<view class="form-title" v-if="item.value.title.isShow">{{item.value.title.value}}</view>
						<view class="form-list">
							<view class="li" v-for="(it,idx) in item.value.formItemList" :key="idx">
								<view class="label">{{it.label}}</view>
								<block v-if="it.type == 1">
									<button open-type="getPhoneNumber" hover-class="none" @getphonenumber="getPhoneNumber" :class="'phone-ipt fflex' + (it.fieldValue?'':' placeholder')" v-if="it.dataType == 1">
										<block v-if="it.fieldValue">{{it.fieldValue}}</block>
										<block v-else>请填写{{it.label}}</block>
									</button>
									<input v-model="it.fieldValue" :placeholder="'请填写' + it.label" placeholder-class="placeholder" class="ipt fflex" v-else />
								</block>
								<textarea v-model="it.fieldValue" :placeholder="'请填写' + it.label" placeholder-class="placeholder" class="textarea fflex" v-else-if="it.type == 4"></textarea>
								<picker :range="it.option" class="pickers fflex" @change="changeOptions($event,idx)" v-else-if="it.type == 5">
									<view v-if="it.fieldValue">{{it.fieldValue}}</view>
									<view class="placeholder" v-else>请选择{{it.label}}</view>
								</picker>
							</view>
						</view>
						<view class="form-btn" @click="formSubmit(item.value)">{{item.value.buttonName}}</view>
					</view>
					<view class="richText" v-if="item.key == 'text'">
						<rich-text :nodes="item.value.content"></rich-text>
					</view>
					<block v-if="item.key == 'product'">
					<view class="product" v-if="item.value.layoutNum == 1">
						<view class="li ddflex" v-for="(it,idx) in item.value.productList" :key="idx" @click="jumpUrl('/product/detail/detail?id=' + it.id)">
							<image :src="it.pic" mode="aspectFill" class="pro-img"></image>
							<view class="pro-info fflex">
								<view class="pro-name tovers">{{it.title}}</view>
								<view class="pro-bri tover" v-if="it.brief">{{it.brief}}</view>
								<view class="pro-opt ddflex">
									<view class="money">￥{{it.minSalePrice}}<text>/起</text></view>
									<view class="pro-btn">立即购买</view>
								</view>
							</view>
						</view>
					</view>
					<view class="product2 ddflex" v-if="item.value.layoutNum == 2">
						<view class="li" v-for="(it,idx) in item.value.productList" :key="idx" @click="jumpUrl('/product/detail/detail?id=' + it.id)">
							<image :src="it.pic" mode="aspectFill" class="pro-img"></image>
							<view class="pro-info fflex">
								<view class="pro-name tovers">{{it.title}}</view>
								<view class="pro-opt ddflex">
									<view class="money">￥{{it.minSalePrice}}<text>/起</text></view>
									<view class="pro-cart"><image src="../../static/pages/images/jia.png"></image></view>
								</view>
							</view>
						</view>
					</view>
					<view class="product product3" v-if="item.value.layoutNum == 3">
						<scroll-view scroll-x="true">
							<view class="li" v-for="(it,idx) in item.value.productList" :key="idx" @click="jumpUrl('/product/detail/detail?id=' + it.id)">
								<view class="ddflex">
									<image :src="it.pic" mode="aspectFill" class="pro-img"></image>
									<view class="pro-info fflex">
										<view class="pro-name tovers">{{it.title}}</view>
										<view class="pro-bri tover" v-if="it.brief">{{it.brief}}</view>
										<view class="pro-opt ddflex">
											<view class="money">￥{{it.minSalePrice}}<text>/起</text></view>
											<view class="pro-btn">立即购买</view>
										</view>
									</view>
								</view>
							</view>
						</scroll-view>
					</view>
					</block>
					<view class="images" v-if="item.key == 'images'">
						<image :src="item.value.src" mode="widthFix"></image>
					</view>
					<block v-if="item.key == 'customerService'"></block>
					<button open-type="contact" class="contact ddflex" v-if="item.value.type == '0'">
						<image src="../../static/pages/images/kfico.png"></image>客服
					</button>
					<view class="contact ddflex" @click="customerServiceChat(item.value)" v-if="item.value.type == '1'">
						<image src="../../static/pages/images/kfico.png"></image>客服
					</view>
					<view class="contact ddflex" @click="jumpHref(item.value)" v-if="item.value.type == '2'">
						<image src="../../static/pages/images/kfico.png"></image>客服
					</view>
				</block>
			</view>
			
			<!-- <view class="view-more" @tap="viewMores()" v-if="viewMoress">查看全文</view> -->
			
			<!-- <view class="bottom-info">
				<view class="bottom-info-browse">浏览 {{params.browseCount}}</view>
				<view style="margin-top: 20rpx;">
					<view class="ddflex">
						<image class="bottom-info-logo" :src="config.CONFIG_PROJECT_LOGO"></image>
						<view class="fflex">{{config.CONFIG_PROJECT_TITLE}}</view>
						<view class="bottom-info-option" @click="showShare">
							<image style="width: 32rpx;height: 32rpx;margin: auto;" src="../static/images/share.png"></image>
							<view>分享</view>
						</view>
						<view class="bottom-info-option" style="margin-left: 50rpx;">
							<image style="width: 32rpx;height: 32rpx;margin: auto;" src="../static/images/dz.png"></image>
							<view>99+</view>
						</view>
					</view>
				</view>
			</view> -->
			
			<!-- <view class="guwen ddflex" v-if="cardInfo" @click="jumpUrl('/card/index/index?cardId='+cardInfo.id)">
				<image :src="picUrlss+'lvluo/home_guwen.png'" class="guwen-img"></image>
				<view class="fflex">
					<view class="ddflex">
						<image :src="cardInfo.imageMap?cardInfo.imageMap:picUrlss+'lvluo/hulei.png'" class="guwen-user"></image>
						<view class="fflex">
							<view class="guwen-name ddflex">{{cardInfo&&cardInfo.realName?cardInfo.realName:'胡雷'}}</view>
							<text class="guwen-tag">{{cardInfo&&cardInfo.job?cardInfo.job:'绿萝云-诊所私域专家'}}</text>
							<view class="guwen-mobile">{{cardInfo&&cardInfo.phone?cardInfo.phone:'15173158288'}}</view>
						</view>
					</view>
				</view>
				<view class="guwen-ewm">
					<image :src="cardInfo.qrCode?cardInfo.qrCode:picUrlss+'lvluo/wechat.png'" show-menu-by-longpress="true"></image>
					<view>长按扫码添加微信</view>
				</view>
			</view> -->
			
			<view style="height: 100rpx;" v-if="anchorId"></view>
			<view class="bottom-option ddflex" v-if="anchorId">
				<view class="ddflex" @click="jumpSingleChatRoom()">
					<image style="width: 37rpx;height: 38rpx;margin-right: 17rpx;" src="/martial/static/images/kf.png"></image>
					<view>联系客服</view>
				</view>
				<view class="bottom-option-line"></view>
				<view class="ddflex" @click="anchor(anchorId)">
					<image style="width: 36rpx;height: 38rpx;margin-right: 17rpx;" src="/martial/static/images/bd.png"></image>
					<view>填写表单</view>
				</view>
			</view>
			
		</view>
		
		<!-- 
		<view class="share ddflex" @click="showShare">
			<image src="../../static/pages/images/fxico1_1.png"></image>分享
		</view> -->
		<view @click="jumpSingleChatRoom()" class="contact-nav ddflex" v-if="advisor&&advisor.id">
			<image :src="advisor.headUrl ? advisor.headUrl : picUrlss+'lvluo/fixed_img.png'" mode="aspectFill"></image>
			<view class="contact-text"><view class="tover"><!-- {{advisor.realName}} -->服务</view><text>顾问</text></view>
			<!-- <view v-if="unReadSpotNum>0" class="newsDot"></view> -->
		</view>
		
	<!--#ifndef H5-->
	<v-share ref="vshare" :hide-toast="hideShare" :product="params" type="market" :code-url="codeUrl" @onFather="click"></v-share>
	<!-- #endif -->
	<!-- #ifdef H5 -->
	<view class="share-pop" @click="hideSharePop" v-if="isShowSharePop">
		<image src="../static/images/fx-tip1.png"></image>
	</view>
	<wx-share ref="wxshare" />
	<!-- #endif -->
	</view>
</template>

<script>
	const app = getApp();
	const req = require("../../utils/request.js");
	import vShare from "../../components/share/share";
	const util = require("../../utils/util.js");
	var timer = ''
	export default {
		components: {
			vShare
		},
		data() {
			return {
				picUrlss: req.public.picUrls,
				systems: {},
				isTop: 0,
				config:{},
				options:{},
				params: '',
				swiperCurrent: 0,
				codeUrl: '',
				sessionKey: '',
				openid: '',
				userInfo: {},
				saveId: '',
				
				viewMoress: false,
				height: 'initial',
				
				cardInfo:'',
				
				advisor:'',
				
				anchorId:'',
				
				specClassSide: 'hide-side',
				
				hideShare: true,
				isShowSharePop: false,
				
				code: '',
				rootCode: '',
			};
		},
		async onLoad(options) {
			if(options.appId) req.setStorage('appId',options.appId);
			this.options = options;
			if(options.userId){
				req.setStorage('pidCode',options.userId)
			}
			if(options.saveBehaviorId){
				this.saveId = options.saveBehaviorId
			}
			app.globalData.getCheckSessoin(json => {
				this.sessionKey = json.session_key;
				this.openid = json.openid;
			});
			if(options.scene ||　options.x_code_id){
				await this.loadCodeParams();
			}
			this.PAGE_DATA_INIT_FN({
				BIND_ID:this.options.code
			})
			await req.silenceLogin(this.options.userId, '');
			this.code = options.code;
			this.rootCode = options.rootCode
			this.getConfig()
			
			await this.getParams();
			
			// if(this.options.userId){
			// 	// 查询分享人名片
			// 	await this.getCardInfo()
			// }
			
			// this.$nextTick(()=>{
			// 	this.monitor();
			// })
			await this.saveBehavior(4);
		},
		onShow() {
			this.userInfo = req.getStorage('userInfo');
			// if(this.options.userId)
			// 	this.getCardInfo()
			this.getAdvisor()
		},
		onUnload() {
			this.updateBehavior()
		},
		async onShareAppMessage() {
			var content = await this.onShareMessage();
			this.SEND_SHARE_FN()
			return content;
		},
		
		onShareTimeline() {
			this.saveBehavior(6)
			let path = {
				code: this.params.code,
				appId: req.getStorage('appId')
			}
			if(req.getStorage('userInfo').id){
				path.userId = req.getStorage('userInfo').id
			}
			if(this.saveId){
				path += '&saveBehaviorId=' + this.saveId
			}
			return {
				title: this.params.title,
				query: path,
				imageUrl: this.params.pic
			};
		},
		
		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: {
			
			getConfig() {
				req.getRequest('/api/config', {}, res => {
					this.config = res
				})
			},
			async onShareMessage(options) {
				let isSolution = '';
				let path = '';
				// #ifndef H5
				isSolution = req.env[req.env.NODE_ENV].isSolution;
				// #endif
				// #ifdef H5
				isSolution = false;
				// #endif
				let userInfo = req.getStorage('userInfo');
				if (isSolution) {
					path = '/share/home/index?appId=' + req.getStorage('appId') + '&userId=' + req.getStorage(
						'userInfo').id;
				} else {
					let page = getCurrentPages()
					let pageCurrent = page[page.length-1]
					path = pageCurrent.route+'?code=' + this.code + '&rootCode=' + this.rootCode + '&isShare=' + true + '&appId=' + req
						.getStorage('appId');
					// console.log(!req.getStorage('userInfo').id);
					if (!userInfo.id) {} else {
						path += '&userId=' + userInfo.id;
					}
					path = this.SHARE_BEHAVIOR_FN({path:path,sendShare:false}).path
				}
				console.log({
					title: this.params.title,
					imageUrl: this.params.pic,
					path: path
				})
				return {
					title: this.params.title,
					imageUrl: this.params.pic,
					path: path
				};
			},
			showShare() {
				// #ifdef H5
				this.hideShare = false;
				this.showSharePop();
				console.log('引导分享==')
				// #endif
				// #ifndef H5
				req.isLogin().then(success => {
					if (success) {
						this.getCodeUrl()
						this.hideShare = false
					}
				});
				this.$refs.vshare.chnageHideToast()
				// #endif
			},
			showSharePop() {
				this.isShowSharePop = true;
			},
			hideSharePop() {
				this.isShowSharePop = false;
			},
			
			getAdvisor() {
				return new Promise((resolve, reject) => {
					req.getRequest('/api/distribution/advisorInfo', {}, data => {
						console.log('服务顾问==', data)
						this.advisor = data;
						resolve();
					})
				})
			},
			jumpSingleChatRoom() {
				// if (!this.getUpdate()) return false;
				// if (this.advisor) {
				// 	req.jumpSingleChatRoom(this.advisor.id, this.advisor.headUrl, this.advisor
				// 		.realName);
				// }
				// #ifdef H5
				if(!req.isLogins(true)) return false
				// #endif
				this.jumpUrl('/other/contact/index')
			},
			// 锚点
			anchor(id) {
				console.log(id)
				this.$nextTick(() => {
					setTimeout(() => {
						uni.createSelectorQuery().select('#topId').boundingClientRect(data => {
							uni.createSelectorQuery().select("#" + id).boundingClientRect(res => {
								if(res){
									uni.pageScrollTo({
										duration: 100, //过渡时间
										scrollTop: res.top - data.top -
											100, //返回顶部的top值
										success: () => {
										}
									})
								}
							}).exec()
						}).exec();
					}, 50)
				})
			},
			getParams() {
				let that = this;
				let params = {
					code: this.options.code
				}
				return new Promise((resolve, reject) => {
					req.getRequest('/api/v3/material/library/detail', params, data => {
						uni.setNavigationBarTitle({
							title:params.title
						})
						data.params.jsonContent.map((item,index)=>{
							if(item.key == 'applicationForm'){
								item.value.formItemList.map(it=>{
									if(it.label.indexOf('姓名')>-1){
										if(that.userInfo.nickName){
											it.fieldValue = that.userInfo.nickName
										}
									}
									if(it.dataType == 1){
										if(that.userInfo.mobile){
											it.fieldValue = that.userInfo.mobile
										}
									}
									if(it.type == 5){
										it.option = ['大健康','快销品']
									}
								})
								item.elementId = item.key+index
								if(!this.anchorId) this.anchorId = item.elementId
							}
							return item
						})
						that.params = data
						uni.setNavigationBarTitle({
							title: data.title
						})
						console.log('data.title==',data.title)
						resolve();
					});
				});
			},
			saveBehavior(behavior){
				let params = {
					behavior: behavior,
					type: 7,
					bindId: this.params.libraryId
				}
				if(req.getStorage('pidCode')){
					params.pid = req.getStorage('pidCode')
				}
				if(this.saveId){
					params.parentId = this.saveId
				}
				req.saveBehavior(params,data=>{
					if(behavior != 6){
						this.saveId = data
					}
				})
			},
			updateBehavior(){
				let params = {
					id: this.saveId
				}
				req.getBehaviorUpdate(params,data=>{})
			},
			swiperChange(e) {
				this.swiperCurrent = e.detail.current;
			},
			jumpUrl(url){
				uni.navigateTo({
					url: url
				})
			},
			customerServiceChat(item) {
				wx.openCustomerServiceChat({
					extInfo: {
						url: item.target
					},
					corpId: item.id,
					success(res) {
						console.log('调用微信客服')
					}
				})
			},
			jumpHref(item){
				window.location.href = item.target
			},
			click(e) {
				this.hideShare = e
				console.log(this.hideShare)
			},
			getCodeUrl() {
				let that = this;
				let scene = that.params.code;
				if(req.getStorage('appId')) scene += '_'+ req.getStorage('appId');
				const params = {
					page: 'leaflet/detail/index',
					scene: scene
				};
				req.getRequest('/api/program/codev', params, url => {
					that.codeUrl = url
				});
			},
			loadCodeParams() {
				let _ts = this;
				return new Promise((resolve, reject) => {
					let form = {
						scene: _ts.options.scene?_ts.options.scene:_ts.options.x_code_id
					};
					if (!_ts.options.scene && !_ts.options.x_code_id) {
						resolve();
						return false;
					}
					req.getRequest('/api/code/params', form, data => {
						
						if(_ts.options.x_code_id){
							let res = JSON.parse(data.scene)
							for(let key in res){
								this.options[key] = res[key]
							}
							req.silenceLogin(_ts.options.userId, '');
							resolve();
						}else{
							let res = data.scene.split('_');
							this.options.code = res[0];
							req.setStorage('pidCode', data.userId);
							req.silenceLogin(data.userId, '');
							req.setStorage('appId',res[res.length-1]);
							resolve();
						}
					});
				});
			},
			getPhoneNumber(e) {
				console.log('获取手机号',e)
				let that = this;
				let _params = {
					sessionKey: that.sessionKey,
					iv: e.detail.iv,
					encryptedData: e.detail.encryptedData
				};
				if (req.getStorage('pidCode')) {
					_params.parentId = req.getStorage('pidCode');
				}
				if (e.detail.errMsg == 'getPhoneNumber:ok') {
					req.postRequest('/api/weixin/mobile', _params, json => {
						// console.log(json);
						if (json.mobile) {
							var userInfo = req.getStorage('userInfo');
							userInfo.mobile = json.mobile;
							req.setStorage('userInfo', userInfo);
							that.params.params.jsonContent.map(item=>{
								if(item.key == 'applicationForm'){
									item.value.formItemList.map(it=>{
										if(it.dataType == 1){
											it.fieldValue = json.mobile
										}
									})
								}
								return item
							})
							that.$forceUpdate();
						}
					});
				}
			},
			changeOptions(e,idx){
				console.log('选择==',e)
				console.log('idx==',idx)
				this.params.params.jsonContent.map((item,index)=>{
					if(item.key == 'applicationForm'){
						item.value.formItemList.map((it,index)=>{
							if(it.type == 5&&idx==index){
								it.fieldValue = it.option[e.detail.value]
							}
						})
					}
					return item
				})
				this.$forceUpdate()
			},
			checkRequire(formItemList){
				for(var i = 0; i < formItemList.length; i++){
					if(formItemList[i].required){
						if(!formItemList[i].fieldValue){
							req.msg('请填写' + formItemList[i].label);
							return false;
						} 
					}
				}
				return true;
			},
			formSubmit(datas){
				let params = {
					formId: datas.database,
					libraryId: this.params.libraryId
				}
				if(req.getStorage('userInfo').id){
					params.belongUid = req.getStorage('userInfo').id
				}
				let formItemList = datas.formItemList
				let valueList = []
				if(!this.checkRequire(formItemList)) return false
				formItemList.map(it=>{
					let obj = {
						fieldId: it.databaseLabel,
						fieldName: it.label,
						fieldType: it.type,
						fieldValue: it.fieldValue
					}
					valueList.push(obj)
				})
				params.valueList = valueList;
				console.log('表单提交==',params)
				req.postRequest('/api/v3/custom/form/submit',params,data=>{
					req.alertMsg('你的信息已成功提交，会有专业人员联系你，请耐心等待',suc=>{
						this.getParams();
					})
				})
			},
			callPhone(phone){
				uni.makePhoneCall({
					phoneNumber: phone
				})
			},
			monitor() {
				console.log('monitor')
				let that = this;
				let system = uni.getSystemInfoSync();
				let query = uni.createSelectorQuery();
				query.select('.viewMore').boundingClientRect(data=>{
					console.log('monitor data',data)
					if(data){
						let height = data.height*that.systems.pxToRpxScale;
						if(height > (system.windowHeight*that.systems.pxToRpxScale-30-that.systems.barHeight)) {
							that.height = (system.windowHeight*that.systems.pxToRpxScale-30-that.systems.barHeight-(this.cardInfo?650:300)) + 'rpx';
							that.viewMoress = true
						}
					}
				}).exec();
			},
			viewMores(){
				this.height = 'initial';
				this.viewMoress = false;
			},
			getCardInfo() {
				return new Promise((r,j)=>{
					var url = '';
					var dataP = {};
					url = '/api/v3/visiting/card/user';
					dataP.userId = this.options.userId;
					req.getRequest(url, dataP, data => {
						this.cardInfo = data;
						r()
					}, false);
				})
			},
			formatTime(time){
				let date = new Date(time.replace(/-/g,'/'))
				return util.formatTimeComm(date,'Y.M.D h:m')
			},
			
			showSide(){
				this.specClassSide = 'hide-side';
			},
			hideSide(){
				this.specClassSide = 'show-side';
			},
		},
		mounted() {
			const systemInfo = uni.getSystemInfoSync();
			// px转换到rpx的比例
			let pxToRpxScale = 750 / systemInfo.windowWidth;
			let systems = {
				ktxStatusHeight: systemInfo.statusBarHeight * pxToRpxScale, // 状态栏的高度
				navigationHeight: 44 * pxToRpxScale, // 导航栏的高度
				pxToRpxScale:pxToRpxScale
			};
			systems.barHeight = systems.ktxStatusHeight + systems.navigationHeight;
			this.systems = systems;
		},
		onPageScroll: function(e) {
			if (e.scrollTop > this.systems.barHeight) {
				this.isTop = 1;
			} else {
				this.isTop = 0;
			}
			this.specClassSide = 'show-side';
			// 检测是否停留了 N 秒
			// 如果停留则表示滚动结束
			// N: 500(定时器时间 毫秒) -> 0.5秒算停止滚动
			// 滚动后多长时间算停止滚动
			timer = setTimeout(() => {
				// console.log('结束滚动');
				// 告知标识 -> 结束滚动
				this.specClassSide = 'hide-side';
			}, 500);
			this.$forceUpdate();
		}
	};
</script>

<style>
	@import './index.css';
</style>