<template>
	<view>
		<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>
		<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'">
				<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 class="share ddflex" @click="showShare">
			<image src="../../static/pages/images/fxico1_1.png"></image>分享
		</view>
		<v-share :hide-toast="hideShare" :product="params" type="market" :code-url="codeUrl" @onFather="click"></v-share>
	<!-- #ifdef H5 -->
	<wx-share ref="wxshare" />
	<!-- #endif -->
	</view>
</template>

<script>
	const app = getApp();
	const req = require("../../utils/request.js");
	import vShare from "../../components/share/share";
	export default {
		components: {
			vShare
		},
		data() {
			return {
				picUrlss: req.public.picUrls,
				systems: {},
				isTop: 0,
				options:{},
				params: '',
				swiperCurrent: 0,
				hideShare: true,
				codeUrl: '',
				sessionKey: '',
				openid: '',
				userInfo: {},
				saveId: ''
			};
		},
		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;
			});
			req.silenceLogin(options.userId, '');
			if(options.scene){
				await this.loadCodeParams();
			}
			await this.getParams();
			await this.saveBehavior(4);
		},
		onShow() {
			this.userInfo = req.getStorage('userInfo');
		},
		onUnload() {
			this.updateBehavior()
		},
		onShareAppMessage() {
			this.saveBehavior(6)
			return this.onShareMessage();
		},
		
		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: {
			onShareMessage(){
				
				let path = '/leaflet/detail/index?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,
					path: path,
					imageUrl: this.params.pic
				};
			},
			
			getParams() {
				let that = this;
				let params = {
					code: this.options.code
				}
				return new Promise((resolve, reject) => {
					req.getRequest('/api/v3/material/library/detail', params, data => {
						data.params.jsonContent.map(item=>{
							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 = ['大健康','快销品']
									}
								})
							}
							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
			},
			showShare() {
				// #ifdef H5 
				this.hideShare = false
				// #endif
				// #ifndef H5
				req.isLogin().then(success => {
					if (success) {
						this.getCodeUrl()
						this.hideShare = false
					}
				});
				// #endif
			},
			click(e) {
				this.hideShare = e
			},
			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
					};
					if (!_ts.options.scene) {
						resolve();
						return false;
					}
					req.getRequest('/api/code/params', form, data => {
						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=>{
					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
				})
			}
		},
		mounted() {
			const systemInfo = uni.getSystemInfoSync();
			// px转换到rpx的比例
			let pxToRpxScale = 750 / systemInfo.windowWidth;
			let systems = {
				ktxStatusHeight: systemInfo.statusBarHeight * pxToRpxScale, // 状态栏的高度
				navigationHeight: 44 * 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;
			}
		}
	};
</script>

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