<template>
	<view v-if="detaile">
		<view class="top-fixed" :style="'height:' + systems.barHeight + 'rpx;'">
			<view class="user dflex" :style="'margin-top:' + systems.ktxStatusHeight + 'rpx;height:' + systems.navigationHeight + 'rpx;'" v-if="detaile.user">
				<image :src="detaile.user.avatar ? detaile.user.avatar : '../../static/images/userimg.png'" class="userimg"></image>
				<view class="flex">{{detaile.user.nickName}}</view>
				<view class="share-top" @click="showShare()"><image src="../../static/images/share1.png"></image></view>
			</view>
		</view>
		<view :style="'height:' + systems.barHeight + 'rpx;'"></view>
		<block v-if="detaile.params&&detaile.params.imageList&&detaile.params.imageList.length > 0">
		<view class="banner">
			<view class="pic-nums">{{swiperCurrent+1}}/{{detaile.params.imageList.length}}</view>
			<swiper class="swiper" @change="swiperChange" autoplay="true" interval="5000" duration="300">
				<block v-for="(item, index) in detaile.params.imageList" :key="index">
					<swiper-item><image lazy-load="true" :src="item.url" mode="aspectFill"></image></swiper-item>
				</block>
			</swiper>
			<view class="dots ddflex">
				<block v-for="(item, index) in detaile.params.imageList" :key="index"><view :class="['dot', index == swiperCurrent ? 'active' : '']"></view></block>
			</view>
		</view>
		</block>
		<block v-if="detaile.params&&detaile.params.product">
		<view class="pro dflex">
			<image :src="detaile.params.product.icon" mode="aspectFit" class="proimg"></image>
			<view class="fflex">
				<view class="proname">{{detaile.params.product.title}}</view>
				<view class="ope dflex">
					<view class="price dflex">
						￥<text>{{detaile.params.product.money}}</text>
					</view>
					<view v-html="wxOpenTags"></view>
					<!-- <view class="btn">立即抢购</view> -->
				</view>
			</view>
		</view>
		</block>
		<view class="title">{{ detaile.title }}</view>
		<view class="content">
			<view :class="'viewMore' + (viewMoress?' con-vheight':'')" :style="'max-height:' + height">
				<mp-html :content="detaile.text" :lazy-load="true" @imgtap="choose"></mp-html>
			</view>
			<view class="view-more" @tap="viewMores()" v-if="viewMoress">查看全文</view>
		</view>
		<view class="operate ddflex">
			<view class="time">编辑于{{getDateTimeStamp(detaile.createDate)}}</view>
			<view class="flex dflex">
				<view class="zan ddflex"><image src="../static/images/view.png"></image>{{detaile.browseCount}}</view>
				<view class="zan ddflex" @click="thumbs()"><image :src="'../../static/images/' + (detaile.isThumbs ? 'like1_h.png' : 'like1.png')"></image>{{detaile.thumbsCount}}</view>
			</view>
			<view class="share ddflex" @click="showShare()"><image src="../static/images/share.png"></image>分享</view>
		</view>
		<view class="box" v-if="contentList && contentList.length > 0">
			<view class="tit ddflex">为您推荐</view>
			<view class="rec">
				<navigator :url="'/other/content/index?code=' + item.code + '&rootCode=' + rootCode" hover-class="none" class="li ddflex" v-for="(item,index) in contentList" :key="index" v-if="index < 3">
					<view class="fflex">
						<view class="rec-tit tovers">{{item.title}}</view>
						<view class="ddflex">
							<!-- <view class="author ddflex"><image src="../../static/pages/images/zbgw.png" mode="aspectFill"></image>欧衡</view> -->
							<view class="rec-time">{{item.createDate}}</view>
						</view>
					</view>
					<image :src="item.pic" mode="aspectFill" class="rec-img"></image>
				</navigator>
			</view>
		</view>
		<share-group :is-show-share="isShowShare" :bottom-positon="bottomPositon" :material-params="detaile" @hidePop="hideShare"></share-group>
	</view>
</template>

<script>
const app = getApp();
const req = require('../../utils/request.js');
const api = require('../../utils/api.js');
const util = require('../../utils/util.js');
import mpHtml from "../../components/mp-html/components/mp-html/mp-html";
export default {
	components: {
		mpHtml,
	},
	data() {
		return {
			systems: {},
			code: '',
			rootCode: '',
			detaile: '',
			type: 2, //详情类型：1 普通内容 2 自定义页面内容
			form: {
				page: 1,
				limit: 4,
			},
			contentList: [],
			height: 'initial',
			viewMoress: false,
			productList: [],
			merchant: {},
			bannerList: [],
			swiperCurrent: 0,
			isShowShare: false,
			bottomPositon: '-100%',
			wxOpenTags: ''
		};
	},

	onLoad: async function(options) {
		if(options.detail){
			let params = JSON.parse(decodeURIComponent(options.detail));
			console.log('params==',params)
			this.code = params.code;
			this.shareCode = params.shareCode
			this.rootCode = params.rootCode
			if(params.appId){
				req.setStorage('appId',params.appId)
			}
			// if(params.userId){
			// 	req.setStorage('pidCode', params.userId);
			// }
		}
		if(options.x_code_id){
			console.log('options==',options)
			this.sceneId = options.x_code_id
			await this.loadCodeParams()
		}
		await this.getDetail();
		this.getContentList();
		if(this.detaile.text){
			setTimeout(async res=>{
				await this.monitor();
			},500)
		}
		if(this.detaile.product){
			this.getWxConfig();
		}
	},
	onShow(){
	},

	methods: {
		getWxConfig(){
			let that = this;
			if (uni.getSystemInfoSync().platform == 'ios') {
				var href = window.location.href.split('#')[0] || window.location.href
			} else {
				var href = window.location.href
			}
			// 这里要换成自己的api接口,返回公众号配置
			req.getRequest(api.getWeiXinJsApiInfo, {
				url: href
			}).then(response => {
				jWeixin.config({
					debug: response.debug,
					appId: response.appId,
					timestamp: response.timestamp,
					nonceStr: response.nonceStr,
					signature: response.signature,
					jsApiList: response.jsApiList,
					openTagList:[
						'wx-open-launch-weapp'//打开小程序
					]
				})
				jWeixin.ready(() => {
					setTimeout(()=>{
						// 这里的username代表小程序的原始id,需要到小程序后台去看,和appid不同,需要换成自己的小城id
						that.wxOpenTags=`<wx-open-launch-weapp path="pages/index/index" id="launch-wxapp" username="gh_6ff3f1da728a">  
							<template>  
								<style>  
								.btn-open-weapp{  
									background: linear-gradient(to right, #ffd52e 0%, #ffef93 50%, #ffd52e 100%);  
									border: 0;  
									color: #424242;  
									text-shadow: 0px 1px 1px #fff;  
									border-radius: 50px;  
									text-align: center;  
									width: 120px;  
									height: 35px;  
									line-height: 35px;  
									outline:none;  
								}  
								</style>  
								<button class="btn-open-weapp">立即抢购</button >  
							</template>  
						</wx-open-launch-weapp>`;  
					},1000);  
				})
			}).catch(error => {
				console.log(error)
			})
		},
		monitor() {
			let that = this;
			let system = uni.getSystemInfoSync();
			let query = uni.createSelectorQuery();
			query.select('.viewMore').boundingClientRect(data=>{
				if(data){
					let height = data.height;
					if(height > system.windowHeight*2) {
						that.height = system.windowHeight *1.8 + 'px';
						that.viewMoress = true
					}
				}
			}).exec();
		},
		viewMores(){
			this.height = 'initial';
			this.viewMoress = false;
		},
		choose: function () {
		  let freshen = false;
		  this.$emit('freshen', {
		    detail: freshen
		  });
		},
		toIndex(){
			uni.switchTab({
				url: '/pages/index/index'
			})
		},
		getDateTimeStamp(dateStr){
		 return util.getDateDiff(Date.parse(dateStr.replace(/-/gi,"/")));
		},
		getDetail() {
			let that = this;
			let apiUrl = api.api_material_detail;
			return new Promise((resolve,reject)=>{
				req.getRequest(apiUrl,{ code: that.code },async res => {
					that.detaile = res;
					resolve();
				},true);
			})
		},
		getContentList() {
			let form = this.form;
			form.rootCode = this.rootCode;
			req.getRequest(api.api_material_library,form,res => {
				this.contentList = res.list;
				for (var i = 0; i < this.contentList.length; i++) {
					if (this.contentList[i].code == this.code){
						this.contentList.splice(i,1);
					}
				}
			});
		},
		getBannerList() {
			let that = this;
			req.getRequest('/api/banner', {
				groupId: '1196269897935630413'
			}, data => {
				that.bannerList = data;
			});
		},
		swiperChange(e) {
			this.swiperCurrent = e.detail.current;
		},
		clickBanner(item) {
			let url = '';
			if (item.type * 1 == 2 && item.content != "") {
				url = "product/detail/detail?id=" + item.content;
			} else if (item.type * 1 == 5) {
				url = "product/coupon/coupon";
			} else if (item.type * 1 == 6) {
				url = "service/live/live";
			} else if (item.type * 1 == 9 && item.content != "") {
				url = "product/list/list?id=" + item.content;
			} else if (item.type * 1 == 10) {
				url = "plugin-private://wx2b03c6e691cd7370/pages/live-player-plugin?room_id=" + item.content;
				// console.log(
				// url); // url=`plugin-private://wx2b03c6e691cd7370/pages/live-player-plugin?room_id=${dt.content}`
			} else if (item.type * 1 == 19 && item.content != "") {//文章内容
					url = "topic/content/content?id=" + item.content;//1为普通文章内容
			} else {
				url = "";
			}
		
			if (item.type * 1 == 6) app.globalData.switchTab(url);
			else app.globalData.openPage(url);
		},
		thumbs(){
			req.postRequest(api.api_material_thumbs,{code: this.detaile.code},data=>{
				if(this.detaile.isThumbs){
					this.detaile.isThumbs = false
					this.detaile.thumbsCount--
				}else{
					this.detaile.isThumbs = true
					this.detaile.thumbsCount++
				}
			})
		},
		showShare(){
			console.log('点击显示分享')
			this.isShowShare = true
			this.bottomPositon = 0
			this.$forceUpdate()
		},
		hideShare(){
			this.isShowShare = false
			this.bottomPositon = '-100%'
		},
	},
	created() {
		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;
	},
	filters: {
		/**
		 * 处理富文本里的图片宽度自适应
		 * 1.去掉img标签里的style、width、height属性
		 * 2.img标签添加style属性：max-width:100%;height:auto
		 * 3.修改所有style里的width属性为max-width:100%
		 * 4.去掉<br/>标签
		 * @param html
		 * @returns {void|string|*}
		 */
		formatRichText(html) {
			//控制小程序中图片大小
			let newContent = html.replace(/<img[^>]*>/gi, function(match, capture) {
				match = match.replace(/style="[^"]+"/gi, '').replace(/style='[^']+'/gi, '');
				match = match.replace(/width="[^"]+"/gi, '').replace(/width='[^']+'/gi, '');
				match = match.replace(/height="[^"]+"/gi, '').replace(/height='[^']+'/gi, '');
				return match;
			});
			newContent = newContent.replace(/style="[^"]+"/gi, function(match, capture) {
				match = match.replace(/width:[^;]+;/gi, 'max-width:100%;').replace(/width:[^;]+;/gi, 'max-width:100%;');
				return match;
			});
			// newContent = newContent.replace(/<br[^>]*\/>/gi, '');
			newContent = newContent.replace(/<br[^>]*\/>/gi, '<p style="margin: 10px 0;"></p>');
			newContent = newContent.replace(/<br[^>]*\>/gi, '<p style="margin: 10px 0;"></p>');
			newContent = newContent.replace(/font-size:[^;]+;?/g,'');
			newContent = newContent.replace(/\<img/gi, '<img style="max-width:100%;height:auto;display:inline-block;margin:12rpx auto;"');
			return newContent;
		}
	}
};
</script>
<style>
@import './index.css';
</style>
