<template>
	<view class="uni-column">
		<view class="content" id="content" >
			<scroll-view id="scrollview" scroll-y="true" :scroll-with-animation="true"
			    :scroll-top="scrollTop">
				<view id="allmsgview">
					<message-show v-for="(message,index) in messages" :key="index" v-bind:message="message" :msgid="index" :isShare="true"
					@fullscreen="handleFullscreen"></message-show>
				</view>
			</scroll-view>
		</view>
		<view class="chat-enter" >
			<button class="start-btn" type="primary" plain="true" @click="gotoChat">我也来试试</button>
		</view>
		<uni-popup ref="fullscreen">
			<view class="fullscreen">
				<towxml :nodes="mdcontent"></towxml>
				<view class="btn-view ">
					<!-- <view class="btn">
						点赞
					</view> -->
					<view class="btn" @click="handleCopy">
						复制全文
					</view>
					<view class="btn" @click="handleCloseFullpage">
						关闭
					</view>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script>
	
	import messageShow from '../components/messageshow.vue';
	// import { Client } from '@stomp/stompjs
	import { orderBy } from 'lodash'
	import { shareSuccess, chatHistory } from '@/api/index.js'
	import { curVersion, chatDefaultMsg } from '@/common/config.js'
	import { CHAT_TYPE } from '@/common/enum.js'
	import {
		mapState,
		mapGetters,
		mapMutations
	} from 'vuex'
	let stompClient = ''

	var app = getApp();
	export default {
		data() {
			return {
				timer: null,
				chatStatus: 0,
				curSessionId: 0,
				showBtn: false,
				style: {
					pageHeight: 0,
					contentViewHeight: 0,
					footViewHeight: 90,
					mitemHeight: 0,
				},
				scrollTop: 0,
				messages: [],
				fromUserId: '',
				mdcontent: '',
				fpcontent: ''
			}
		},
		computed: {
			...mapState(['userId', 'chatToken', 'settings', 'version'])
		},	
		components: {
			messageShow
		},
		onLoad(option) {
			console.log('option', option.uid, option.sid);
			if (option.uid && option.uid != 'undefined') {
				this.setShareId(option.uid)
			}
			if (option.ctype && option.ctype != 'undefined') {
				this.setChatType(option.ctype)
			}
			
			this.curSessionId = option.sid
			if (!this.chatToken || curVersion !== this.version) {
				this.$store.dispatch('login').then(rst => {
					this.getChatHistory()
				})
			} else {
				this.getChatHistory()
			}
		},
		created: function () { 
			const res = app.globalData.systemInfo;
			this.style.pageHeight = res.windowHeight;
			this.style.contentViewHeight = res.windowHeight - res.screenWidth / 750 * (100); //像素
			
			wx.showShareMenu({
				withShareTicket: true,
				//设置下方的Menus菜单，才能够让发送给朋友与分享到朋友圈两个按钮可以点击
				menus: ["shareAppMessage", "shareTimeline"]
			})
		},
		mounted() {
		},
		methods: {
			...mapMutations(['setShareId', 'setVersion', 'setChatType']),
			handleFullscreen(msg) {
				this.parseMarkdown(msg)
				this.$refs.fullscreen.open()
			},
			handleCloseFullpage() {
				this.$refs.fullscreen.close()
			},
			parseMarkdown(content) {
				this.fpcontent = content
				let result = this.$towxml(content,
					'markdown', {
						// base: 'https://xxx.com', // 相对资源的base路径
						theme: 'dark', // 主题，默认`light`
						events: { // 为元素绑定的事件方法
							tap: (e) => {
								console.log('tap', e);
							}
						}
					});
				// 更新解析数据
				this.mdcontent = result
			},
			handleCopy() {
				const that = this
				wx.setClipboardData({
					data: that.fpcontent, //这个是要复制的数据
					success (res) {
						wx.showToast({
							title: '复制成功',
							icon: 'success',
							duration: 1500
						})
					}
				})
			},
			async gotoChat() {
				// this.setChatType(CHAT_TYPE.NORMAL)
				uni.navigateTo({
					url: '/pages/ai/chat/chat'
				});
			},
			addQuestion: function (question) { 
				this.messages.push({
					user: 'customer',
					content: question
				});
			},
			addMessage: function(msg, status = 'WAITING', replace = false) {
				const temp = {
					user: 'ai',
					content: msg,
					status
				}
				if (replace) {
					this.messages.splice(this.messages.length -1, 1, temp);
				} else {
					this.messages.push(temp);
				}
				this.startToScroll()
			},
			addAnswer: function(message, replace = false ) {
				const { id, question, answer, status, liked } = message
				const temp = {
					user: 'ai',
					content: answer,
					id, question, status, liked
				}
				if (replace) {
					this.messages.splice(this.messages.length -1, 1, temp);
				} else {
					this.messages.push(temp);
				}
				this.startToScroll()
			},
			startToScroll(time = 100) {
				setTimeout(() => {
					this.scrollToBottom();
				}, )
			},
			scrollToBottom: function () {
				var that = this;
				var query = uni.createSelectorQuery().in(this);;
			    query.select('#allmsgview').boundingClientRect();
				query.select('#scrollview').boundingClientRect();

				query.exec(function (res) {
					that.style.mitemHeight = 0;
					// res[0].forEach(function (rect) {
					// 	console.info('rect.height:',rect.height);
					// 	that.style.mitemHeight = that.style.mitemHeight + rect.height + 20;
					// });
					that.style.mitemHeight = res[0].height
					const scrollHeight = res[1].height
					if (that.style.mitemHeight > scrollHeight) {
						that.scrollTop = that.style.mitemHeight - scrollHeight;
					}
				});
			},
			async getChatHistory(){
				wx.showLoading()
				const res = await chatHistory(this.curSessionId, 30)
				wx.hideLoading()
				if (res.code === 0 && res.data) {
					const temps = []
					const list = orderBy(res.data.list, ['id'])
					list.map(m => {
						const { id, question, answer, status, liked } = m
						const que = {
							user: 'customer',
							content: question
						}
						const ans = {
							user: 'ai',
							content: answer ? answer : '请求异常',
							id, question, status, liked
						}
						temps.push(que)
						temps.push(ans)
					})
					
					this.messages = [chatDefaultMsg].concat(temps)
					this.startToScroll()
				}
				setTimeout(() => {
					this.showBtn = true
				}, 1000)
			},
			handleShareSession() {
				
			},
			// onShareTimeline() {
			// 	return {
			// 		title: '我是测试标题，你可以随便修改',
			// 		path: '/pages/index/index'
			// 	}
			// }
			onShareAppMessage: function (obj) {
				// let path = `/pages/ai/main/main?uid=${this.userId}`
				// let title = '加入AI降临派，与AI真神对话！'
				if (obj.from === 'button' && obj.target.id === 'shareSessionBtn') {
					path = `/pages/ai/share/share?uid=${this.userId}&sid=${this.curSessionId}`;
				}
				return { title,	path };
			}
		}
	}
</script>

<style lang="less" scoped>
	.uni-column {
		height: 100%;
		background-color: #33373f;
		display: flex;
		flex-direction: column;
	
		.content {
			height: 100%;
			display: flex;
			flex: 1;
			padding-bottom: 170rpx;
			box-sizing: border-box;
			#scrollview {
				height: 100%;
					
				#allmsgview {
					padding-bottom: 40rpx;
				}
			}
		}
		.chat-enter {
			position: fixed;
			width: 100%;
			padding-top: 20rpx;
			bottom: 60rpx;
			color: #FFF;
			font-size: 28rpx;
			text-align: center;
			box-sizing: border-box;
			.chat-desc {
				padding-bottom: 20rpx;
			}
			.start-btn {
				border-color: @mainColor;
				background-color: @mainColor;
				color: #FFF;
				width: 320rpx;
				padding: 6rpx 0;
				font-size: 30rpx;
				border-radius: 10rpx;
			}
		}
		.uni-popup .uni-popup__wrapper.center {
			width: 100%;
			.fullscreen {
				height: 100vh;
				width: 100%;
				padding: 0 0rpx 80rpx;
				background-color: @mainBg;
				overflow: auto;
				position: relative;
				box-sizing: border-box;
				.btn-view {
					position: fixed;
					bottom: 0;
					height: 80rpx;
					width: 100%;
					display: flex;
					justify-content: space-around;
					align-items: center;
					background-color: darken(@mainBg, 5%);
					.btn {
						color: #ededed;
						width: 180rpx;
						line-height: 60rpx;
						&:active {
							color: @mainColor;
						}
					}
				}
				
			}
		}
	}
</style>
