<script>
	import chatInput from '../component/chatinput.vue';
	import messageShow from '../component/messageshow.vue';
	export default {
		data() {
			return {
				style: {
					pageHeight: 0,
					contentViewHeight: 0,
					footViewHeight: 90,
					mitemHeight: 0,
				},
				scrollTop: 0,
				messages: [{
					user: 'home',
					type: '', //input,content 
					content: '你好',
					date:this.getCurrentTime()
				}]
			}
		},
		components: {
			chatInput,
			messageShow
		},
		created: function () { 
			this.initWebSocket();
			const res = uni.getSystemInfoSync();
			this.style.pageHeight = res.windowHeight;
			this.style.contentViewHeight = res.windowHeight - uni.getSystemInfoSync().screenWidth / 750 * (100); //像素
		},
		methods: {
			getCurrentTime:function(){
        //获取当前时间并打印
        var time='';
    　　let yy = new Date().getFullYear();
    　　let mm = new Date().getMonth()+1;
    　　let dd = new Date().getDate();
    　　let hh = new Date().getHours();
    　　let mf = new Date().getMinutes()<10 ? '0'+new Date().getMinutes() : new Date().getMinutes();
    　　let ss = new Date().getSeconds()<10 ? '0'+new Date().getSeconds() : new Date().getSeconds();
    　　time = yy+'-'+mm+'-'+dd+' '+hh+':'+mf+':'+ss;
    　　 return time;
    },
			initWebSocket: function () {
				// WebSocket与普通的请求所用协议有所不同，ws等同于http，wss等同于https
				var userId = this.$store.getters.userid;
				var sessionId=this.$store.getters.sessionId;
				var url = this.$config.apiUrl.replace("https://","wss://").replace("http://","ws://")+"/websocket/"+userId+"/"+sessionId;
				console.log('websocket url>>'+url);
				this.websock = new WebSocket(url);
				this.websock.onopen = this.websocketOnopen;
				this.websock.onerror = this.websocketOnerror;
				this.websock.onmessage = this.websocketOnmessage;
				this.websock.onclose = this.websocketOnclose;
				
			},
			websocketOnopen: function () {
				console.log("WebSocket连接成功");
				//心跳检测重置
				//this.heartCheck.reset().start();
			},
			websocketOnerror: function () {
				console.log("WebSocket连接发生错误");
				this.reconnect();
			},
			websocketOnmessage: function (e) {
				console.log("-----接收消息-------",e);
				this.addMessage('home', e.data, false);
				this.scrollToBottom();
				
					
				//心跳检测重置
				//this.heartCheck.reset().start();
			},
			websocketOnclose: function (e) {
				console.log("connection closed (" + e.code + ")");
				this.reconnect();
			},
			websocketSend:function(text) { // 数据发送
				try {
				  this.websock.send(text);
				} catch (err) {
				  console.log("send failed (" + err.code + ")");
				}
			},
			getInputMessage: function (message) { //获取子组件的输入数据
				// console.log(message);
				this.addMessage('customer', message.content, false);
				this.toRobot(message.content);
			},
			addMessage: function (user, content, hasSub, subcontent) {
				var that = this;
				that.messages.push({
					user: user,
					content: content,
					date:this.getCurrentTime(),
					hasSub: hasSub,
					subcontent: subcontent
				});
			},
			scrollToBottom: function () {
				var that = this;
				var query = uni.createSelectorQuery();
				query.selectAll('.m-item').boundingClientRect();
				query.select('#scrollview').boundingClientRect();

				query.exec(function (res) {
					that.style.mitemHeight = 0;
					res[0].forEach(function (rect) {
						// console.info(rect.height);
						that.style.mitemHeight = that.style.mitemHeight + rect.height + 20;
					});

					if (that.style.mitemHeight > that.style.contentViewHeight) {
						that.scrollTop = that.style.mitemHeight - that.style.contentViewHeight;
					}
				});
			},
			toRobot: function (info) {
				var ToSendUserno=this.$store.getters.chatid;//接收人编号：4567
				var message=info+"|"+ToSendUserno+"|"+this.$store.getters.userid//将要发送的信息和内容拼起来，以便于服务端知道消息要发给谁
				this.websocketSend(message)
				
			}
		}
	}
</script>
<template>
	<div>
	<cu-custom bgColor="bg-gradual-pink" :isBack="true">
		<block slot="backText">返回</block>
		<block slot="content">{{this.$store.getters.chatname}}</block>
	</cu-custom>
	<view class="uni-column">
		<view class="content" id="content" :style="{height:style.contentViewHeight+'px'}">
			<scroll-view id="scrollview"   scroll-y="true" :style="{height:style.contentViewHeight+'px'}" :scroll-with-animation="true"
			    :scroll-top="scrollTop">
				<message-show v-for="(message,index) in messages" :key="index" v-bind:message="message" :id="index"></message-show>
				<view id="bottom"></view>
			</scroll-view>
		</view>
		<view class="foot">
			<chat-input @send-message="getInputMessage" ></chat-input>
		</view>
	</view>
	</div>
</template>

<style>
	.uni-column {
		display: flex;
		flex-direction: column;
		background-image: url(../../static/bj001.jpeg );
	}
	.content {

		display: flex;
		flex: 1;
		
		 
	}
	.foot {
		position: fixed;
		width: 100%;
		left: 0px;
		bottom: 0px;
		overflow: hidden;
	}
</style>
