<template>
	<view class="onlineService">
		<!-- 标题栏 -->
		<u-navbar
				back-icon-color="#fff"
				:back-text="$t('common.Back')"
				:is-back="true"
				:background="{background:'#1777FE'}"
				:back-text-style="{color:'#fff'}"
				:border-bottom="true"
				title-color="#fff"
				:title="title"
		>
		</u-navbar>

		<!-- 转人工-->
		<view v-if="this.chatState == 'ROBERT'" class="manmade"  @click="changeOnline"><text class="text">{{$t('common.TransferToRober')}}</text></view>
		<view v-if="this.chatState == 'Artificial'" class="manmade"  @click="changeOnline"><text class="text">{{$t('common.TransferToArt')}}</text></view>
		<!-- 聊天信息列表 -->
		<view class="chats"  id="messageList">
			<view class="charitem" v-for="(charitem,charidx) in chatsList" :key="charitem.id">

				<!-- 机器人发信息，引导词 -->
				<view class="robot" v-if="charitem.messageUserType=='ROBERT' && charitem.messageContent.messageContentType != 'HTML'">
					<view class="robotImg"><image class="robotimg" :src="logo" mode="widthFix"></image></view>
					<view class="robotmsg">
						<view class="msg" v-if="charitem.messageContent.messageContentType == 'ML'">{{charitem.messageContent.content}}</view>
					</view>
				</view>
				<!--客服信息为ML格式时，猜你喜欢消息列表-->
				<view class="guessYou" v-if="charitem.messageUserType=='ROBERT' &&charitem.messageContent.messageContentType == 'ML'">
					<view class="robotmsg">
						<!--猜你喜欢-->
						<view class="tag" v-if="charidx=='0'">
							<image v-if="$i18n.locale == 'zh'" src="../../../static/img/server/servers/oline/guessZh.png" mode="" style="width: 100%;height: 100%;"></image>
							<image v-if="$i18n.locale == 'en'" src="../../../static/img/server/servers/oline/guessEn.png" mode="" style="width: 100%;height:80%;"></image>
							<!-- <view class="text">{{$t('common.Youmaylike')}}</view>
							<u-icon name="question-circle-fill" size="36" color="#FD9D00"></u-icon> -->
						</view>
						<view class="msglist">
							<view class="robomsgitem"
								 v-for="(charList,listId) in charitem.messageContent.messageContentList"
								 :key="listId"
								 @click="answerList(charList,listId)">
								<text class="msg" >{{charList.content}}</text>
								<!-- <text class="symbol">&gt;</text> -->
							</view>
						</view>
						
					</view>
				</view>
				<!-- 服务列表 -->
				<view class="serivceBox" v-if="charidx=='0'">
					<scroll-view class="scroll-view_H" scroll-x="true">
						<view id="list" class="scroll-view-item_H uni-bg-red" style="line-height: 40upx;" v-for="(item,serviveId) in serviceList"  @click="toService(item)">
							<view class="serviceImg">
								<image :src="'../../../static/img/server/servers/oline/'+(++serviveId)+'.png'" alt="" style="width: 100%;height: 100%;">
							</view>
							{{item.modelName}}
						</view>
					</scroll-view>
				</view>
				<!--客服信息为HTML格式时-->
				<view class="robot" v-if="charitem.messageUserType=='ROBERT' && charitem.messageContent.messageContentType == 'HTML'">
					<view class="robotImg"><image class="robotimg" :src="logo" mode="widthFix"></image></view>
					<view class="robotmsg">
						<view class="msglist" >
							<view class="robomsgitem">
								<text class="msg" v-html="charitem.messageContent.content"></text>
							</view>
						</view>
					</view>
				</view>
				<!-- 在线客服消息 -->
				<view class="robot" v-if="charitem.messageUserType=='CUSTOMER'">
					<view class="robotImg"><image class="robotimg" :src="logo" mode="widthFix"></image></view>
					<!-- <view class="robotmsg"> -->
					<view class="onlinerobt">
						<view class="msg">{{charitem.messageContent.content}}</view>
					</view>
				</view>

				<!-- 当前咨询用户 -->
				<view class="currentUser" v-if="charitem.messageUserType=='USER'">
					<view v-if="!charitem.messageContent.content.messageContentType">
						<view class="currentUserMsg">{{charitem.messageContent.content}}</view>
						<view class="currentUserImg" v-if="user.umsUser&&user.umsUser.userPic">
							<image :src="'https://geidcp.com/api/fileextend/pub/'+user.umsUser.userPic" style="width: 100%;height: 100%;"></image>
						</view>
						<view class="currentUserImg" v-else>
							<image class="currentUserimg" src="../../../static/E2.png" mode="widthFix"></image>
						</view>
						<view style="clear: both"></view>
					</view>
					<view v-if="charitem.messageContent.content.messageContentType == 'COL'">
						<view class="currentUserMsg">{{charitem.messageContent.content.content}}</view>
						<view class="currentUserImg"><image class="currentUserimg" :src="robotImg" mode="widthFix"></image></view>
						<view style="clear: both"></view>

					</view>

				</view>
			</view>
		</view>
		<!-- 底部滑动块菜单 -->
		<view class="scrollBox">
			<view>
				<scroll-view class="scroll-view_H" scroll-x="true">
					<view id="list" class="scroll-view-item_H uni-bg-red" v-for="item in Morelist"   @click="clickMorelist(item)" >{{item.modelName}}</view>
				</scroll-view>
			</view>
		</view>
		<!-- 发送信息 -->
		<view class="sendMsgBox">
			<view class="voice">
				<u-icon name="mic" size="36"></u-icon>
			</view>
			<view class="itp">
				<input class="uni-input"  @input="showCurrentMsgStr" v-model="inputText"/>
				<view class="expression">
					<u-icon name="more-circle-fill" size="36"></u-icon>
				</view>
			</view>
			<view class="sendTip" @click="sendMessage">{{i18n('Send')}}</view>
		</view>

	</view>
</template>

<script>
	import UNavbar from '@/components/uni-nav-bar/uni-nav-bar.vue'
	import { getAllInformationByCustomer} from "@/api/customer/baseCustomerMessage"
	import config from '@/config'
	import {robertClientMessages,getOperationListByOperationType} from "@/api/customer/customerServiceRobert"
	export default {
		name:'onlineService',
		components:{
			UNavbar
		},
		data(){
			return {
				title: '',
				logo: '../../../static/logo11.png',
				robotImg: '',
				token: '',
				user:{
					id:'',
				},
				inputText: '',
				chatState: 'ROBERT',
				chatsList: [],
				userMess: {},
				sokectOpen:false,
				//服务列表图片顺序
				userSendMessage: {
					id: null,
					senderId: '',
					senderName: '',
					sendContent: '',
					receiverId: '',
					receiverName: '',
					sendingStatus: '',
					receivingStatus: '',
					messageType: '',
					status: '',
					createBy: ''
				},	
				timestamp: "",
				//心跳检测
				heartCheck: {},
				pingpangTimes: null, //socket心跳计时器
				loginPopRemind: '',
				commentScrollCount: '',
				//本地重连状态
				lockReconnect: false,
				timeterver:{},
				customerServiceId: "",
				params: '',
				customAnswer:"",
				oldbottom:0,
				scrollTop:0,
				lastMsgItem:{},
				socketUrl:"",
				messageCount: 'FIRST',
				//在线客服信息
				artificial: {
					userId: '',
					userName: '',
					userImage: '',
				},
				//用户发送消息内容信息
				sendRequestMessageContent: {
					messageContentType: 'STR',
					content: "",
					language:"",
				},
				//用户消息信息
				sendRequestMessage: {
					"userId": "0",
					"userName": "",
					"userImage": "helpCenter/logo11.png",
					"messageTime":(new Date()).getTime(),
					"messageType": "USER",
					"messageUserType": "USER",
					"messageTypeExtend": "",
					"language":"",
					"messageContent": "",
				},
				//底部左右滑动块
				Morelist:[],
				serviceList:[],
			}
		},
		onLoad(e){
			uni.showLoading({
				title: this.$i18n.locale == 'zh' ? '加载中...' : 'Loading...'
			});
			this.title = this.$i18n.locale == 'zh' ? '在线客服' : 'Help Center'
			setTimeout(() => {
				uni.hideLoading();
			}, 100)

		},
		mounted() {
			this.token = uni.getStorageSync('Auth-Token') ? 'Bearer ' + uni.getStorageSync('Auth-Token') : '';
			const us = {id:''}
			this.user = uni.getStorageSync('user') ? JSON.parse(uni.getStorageSync('user')) : us;

			this.initSocket();
			this.heartBeat()
			this.messageCount='FIRST';
			this.getBotMenu();
			this.getserviceMenu();
		},
		// watch(){
		// 	this.messageCount='FIRST';
		// },

		methods:{

			/***发送消息事件 ***/
			
			// 用户点击列表，发送消息
			answerList(item, index) {
				this.userSendCof(item.content, index)
			},
			//点击底部可滑动块菜单
			clickMorelist(item){
				//用户发送消息方法
				this.userSendCof(item.modelName)
			},
			//获取客服消息
			async getMessList(messageCount){
				let that = this;
				let message = JSON.stringify(this.sendRequestMessage);

				let res = await this.$myRequest({
					url:'/customer/robertClient/get/robert/nologin',
					data:{
						messageCount,
						message
					}
				});
				if (res.status == '200') {
					if (messageCount == 'FIRST') {
						that.chatsList = []
					}
					that.chatsList.push(res.data.messages)
					this.messageCount = 'CHAT'
				}
				this.scroBootom()

			},
			// 切换客服状态
			changeOnline() {
				const that = this;
				if(this.chatState == 'ROBERT'){
					this.chatState = "Artificial";
					this.openSocket()
				}else{
					this.chatState = "ROBERT";
					if(this.sokectOpen = true){
						this.sokectOpen = false;
						console.log(this.sokectOpen)
						
						uni.onSocketClose(function (res) {
							console.log('WebSocket 已关闭！');		
						});
					}
					
					// this.closeheart();
					// this.heartCheck.stop();
				}			
			},
			// 获取输入框内容
			showCurrentMsgStr(val) {

				var userSend = {
					type: '3',
					name: val.detail.value
				}
				this.userMess = userSend;
			},
			// 点击发送按钮发送消息
			sendMessage() {

				if (this.userMess.name) {
					this.userSendCof(this.userMess.name)
					this.userMess = "";
					this.inputText = "";

				} else {
					uni.showToast({
						title: '说点什么吧 ~',
						icon: 'none'
					})
				}
				this.scroBootom()
			},
			//识别并且发送消息
			userSendCof(item, index) {
				// this.getUserMessage();
				let that = this;
				this.sendRequestMessageContent.language = this.$i18n.locale.toUpperCase();
				this.sendRequestMessage.language =  this.$i18n.locale.toUpperCase();
				if(this.chatState == 'ROBERT'){
					//机器人小E
					this.sendRequestMessageContent.content = item;
					this.sendRequestMessage.messageContent = this.sendRequestMessageContent;
					this.filters();
					let messageCount = JSON.parse(JSON.stringify(this.messageCount));
				
					if (this.messageCount != 'FIRST') {
						let sendRequestMessageget = JSON.parse(JSON.stringify(this.sendRequestMessage));
						that.chatsList.push(sendRequestMessageget)
					}
					this.getMessList(messageCount);
				}else if(this.chatState == 'Artificial'){
					//人工客服
					this.sendRequestMessageContent.content = item;
					this.sendRequestMessage.messageContent = this.sendRequestMessageContent;
					this.sendRequestMessage.userName = this.user.username;
					this.filters();
					var message = {
						language:this.$i18n.locale.toUpperCase(),
						userId: "",
						message: "",
						messageType: "ARTM",
					}
					message.message = this.sendRequestMessage;
					message.userId = '2';
					this.sendSocket(JSON.stringify(message))
					
					let sendRequestMessageget = JSON.parse(JSON.stringify(this.sendRequestMessage));
					
					if(item != ""){
						that.chatsList.push(sendRequestMessageget)
					}								
				}
				this.scroBootom()
			},
			//调用Socket方法发送消息
			sendSocket(msg) {
				uni.sendSocketMessage({
					data: msg,
					success : ()=> {
						console.log('发送成功')
						
					}	
				});
			},
			
			
			
			/**获取数据信息**/

			async getBotMenu(){
				let that = this;
				var operationType = "QUICKLIST";
				var language = this.$i18n.locale.toUpperCase();
				let res =  await this.$myRequest({
					url:'/customer/customerOperations/getOperationListByOperationType',
					data:{
						operationType,
						language
					}
				});
				if ('200' == res.status) {
					if(res.data.customerOperations){
						this.Morelist = res.data.customerOperations
					}	
				}
			},
			/**获取服务列表**/
			async getserviceMenu(){
				let that = this;
				var operationType = "PLATFORMSERVICES";
				var language = this.$i18n.locale.toUpperCase();
				let res =  await this.$myRequest({
					url:'/customer/customerOperations/getOperationListByOperationType',
					data:{
						operationType,
						language
					}
				});
				if ('200' == res.status) {
					if(res.data.customerOperations){
						this.serviceList = res.data.customerOperations
					}
					
				}
			
			},
			
			
			
			/*** socket事件 ***/
			
			//初始化socket
			initSocket() {
				const that = this;
				//获取用户信息
				this.getUserMessage();
				//第一次发起请求
				this.userSendCof("");
				//监听socket消息
				this.getTimeMessage();
				this.scroBootom()
			},
			//创建socket连接
			openSocket(){
				const that = this;
				that.user.id = (new Date()).getTime();
				 // if(process.env.NODE_ENV === 'development'){
					// console.log('开发环境')
				 //    this.socketUrl ="http://172.16.10.44:7028/userConn/" + this.$i18n.locale.toUpperCase() + "/" + this.user.id;
					// console.log(this.socketUrl)
				 // }else{
					 this.socketUrl = 'wss://www.geidcp.com' + "/userConn/"+ this.$i18n.locale.toUpperCase() + "/" + this.user.id;
				 // }
				this.socketUrl = this.socketUrl.replace("https", "wss").replace("http", "ws");
				uni.connectSocket({				
					url: this.socketUrl
				});
				// 打开socket
				uni.onSocketOpen(function (res) {
				  console.log('Socket连接已打开！');
				  this.sokectOpen = true;
				 
				});
				//初始化socket
				this.initOperation()
				//监听socket错误
				uni.onSocketError((res) => {
					console.log('Socket连接打开失败');
					that.reconnect(this.socketUrl);
				})
				this.scroBootom()
			},
			//检查用户身份
			getUserMessage(){
				//用户信息
				if (this.user.id != '') {
					this.sendRequestMessage.userId = this.user.id;
					this.sendRequestMessage.userName = this.user.username;
					this.robotImg = this.user.umsUser.userPic;
				} else{
					this.user.id = new Date().getTime();
					this.sendRequestMessage.userId = this.user.id;
					if (this.$i18n.locale.toUpperCase() == 'ZH') {
						this.user.username = '游客';
						this.sendRequestMessage.userName = '游客';
					} else {
						this.user.username = 'Tourist';
						this.sendRequestMessage.userName = 'Tourist';
					}
					this.user.userImage = '';
					this.sendRequestMessage.userImage = this.user.userImage;
				}
			},
			//初始化socket操作方法
			initOperation(){
				let that = this;
				// 监听到socket
				uni.onSocketMessage(function (res) {
					
					var message = JSON.parse(res.data);
					console.log(message)
					if (message.messageType == 'PONG') {
					} else {
						that.artificial.userId = message.userId;
						that.artificial.userName = message.userName;
						that.chatsList.push(message)
					}
				});
			},
			//心跳机制
			heartBeat(){
				let that = this;
				this.heartCheck = {
					timeout:30000,
					timeoutObj: null,
					serverTimeoutObj: null,
					//socket: this.socket,
					start: function () {
						console.log('start');
						var self = this;

						this.timeoutObj && clearTimeout(this.timeoutObj);
						this.serverTimeoutObj && clearTimeout(this.serverTimeoutObj);
						this.timeoutObj = setTimeout(function () {
							//发送一个心跳
							var message = {
								userId: "",
								message: "",
								messageType: "PING",
							}
							var a = JSON.stringify(message);
							uni.sendSocketMessage({
								data:a,
								success: () => {
								},
							});
							self.serverTimeoutObj = setTimeout(function () {
								uni.onSocketClose(function (res) {
									console.log('WebSocket 已关闭！');
								});
							}, self.timeout);
						}, this.timeout)
					},
					stop () {
						clearTimeout(this.timeoutObj);
						clearTimeout(this.serverTimeoutObj);
					},
				}
			},
			
			// 重新连接心跳
			reconnect() {
				let that = this;
				if (this.lockReconnect) {
					return;
				};
				this.lockReconnect = true;
				//没连接上会一直重连，设置延迟避免请求过多
				this.timeterver && clearTimeout(this.timeterver);
				this.timeterver = setTimeout(function () {
					that.openSocket();
					that.lockReconnect = false;
				}, 4000);
			},
			//监听socket消息
			getTimeMessage(){
				const that  = this;
				//监听socket消息
				uni.onSocketMessage(function (res){
					if(!res){
						console.log("没有监听到的返回数据")
					}
					that.heartCheck.start();
					let infos = JSON.parse(res.data);
					that.chatsList.push(infos);
					this.scroBootom();
				})
			},

			//发送消息滚动到底部
			scroBootom(){
				setTimeout(() => {
					uni.pageScrollTo({scrollTop: 99999, duration: 0});
				}, 50);
			},
			//跳转至服务
			toService(item){
				if(item.linkPath == "conferenceServices"){
					//会议服务
					item.link = '/pages/conference/meetingIndexCh/meetingIndex'
				}else if(item.linkPath == "IntroductionMemberProfile"){
					//定制服务
					item.link = '/pages/cooperationNetwork/cooperationNetwork'
				}else if(item.linkPath == "financialServices"){
					//金融服务
					item.link = '/pages/financialService/financialService'
				}else if(item.linkPath == "resourceSharing"){
					//资源共享
					item.link = '/pages/resourceSharing/resourceSharing'
				}else{
					//资源共享
					item.link = '/pages/category/exhibition';
				}
				this.toView(item.link)
			},
			//跳转事件
			toView(href){
				uni.navigateTo({
					url:href
				})
			},
			
			i18n (data) {
				return this.$t('common.'+data);
			},
			//时间戳的处理    
			filters(){
				var dates=new Date();
				// var now = new Date(dates*1000);
				var year = dates.getFullYear();
				var month = dates.getMonth() + 1;
				if (month < 10) {
					month = '0' + month
					}
				var date = dates.getDate();
				if (date < 10) {
					date = '0' + date
				}
				var hours = dates.getHours();
				if (hours < 10)
					hours = "0" + hours;
				var minutes = dates.getMinutes();
				if (minutes < 10)
					minutes = "0" + minutes;
					
				var seconds = dates.getSeconds();
				if (seconds < 10)
					seconds = "0" + seconds;
				let time = year + "-" + month + "-" + date +" " + hours + ":" + minutes+ ":" + seconds;
				this.sendRequestMessage.messageTime = time;

			},
		}
	}
</script>

<style lang="scss" scoped>
	.onlineService{
		padding-bottom:20upx;
		.manmade{
			position: fixed;
			width: 100%;
			background:#5FC1B9;
			padding:5px 0;
			text-align: center;
			z-index: 100;
			.text{
				color:#fff;
				padding:10upx 40upx;
				border-radius:10upx;
			}
		}
		.serviceStatus{
			font-size:24upx;
			display:flex;
			justify-content:flex-end;
			padding:1% 3% 1% 3%;
			color:#666;
		}
		.robot,.currentUser{
			display:flex;
			width:94%;
			margin:80upx auto 50upx;
			.robotImg,.currentUserImg{
				width:100upx;
				height:100upx;
				position:relative;
				overflow:hidden;
				margin-right:20upx;
				border-radius:50%;
				background-color:#fff;
				&.currentUserImg{
					margin-left:20upx;
					display: inline-block;
				}
				.robotimg,.currentUserimg{
					width:80%;
					margin:10%;
					display:block;
				}
			}
			.robotmsg{
				color:#333;
				background:#fff;
				padding:20upx;
				border-radius:20upx;
				width:80%;
				.msglist{
					.robomsgitem{
						margin:20upx 0;
						border-bottom:1px solid #fafafa;
						padding:10upx 0;
						display:flex;
						justify-content:space-between;
						align-items:flex-end;
						&.blue {
							.msg{
								color:#0091FF;
							}
						}

					}
				}
			}
			.onlinerobt{
				color:#333;
				background:#fff;
				padding:20upx;
				border-radius:20upx;
				max-width:80%;
			}
			&.currentUser{
				justify-content:flex-end;
				.currentUserMsg{
					text-align:right;
					background:#fff;
					padding:20upx;
					border-radius:20upx;
					/*display: inline-block;*/
					float: left;
					max-width: 80%;
					text-align: left;
				}
			}
		}
		.serivceBox{
			width: 90%;
			height: 120upx;
			background-color: #fff;
			margin:40upx auto;
			border-radius: 20upx;
			padding: 0 20upx;
			display: flex;
			flex-wrap: nowrap;
			position: relative;

			.serviceImg{
				width: 66upx;
				height: 66upx;
			    position: relative;
			    left: 25%;
			}
			
			
		}
		.guessYou{
			display:flex;
			width:94%;
			margin:auto;
			.robotmsg{
				color:#333;
				background:#fff;
				padding:20upx;
				border-radius:20upx;
				width: 95%;
				margin: auto;
				.tag{
					width:13%;
					height: 180upx;
					margin: 20px 0 0 15px;
					float: left;

					.text{
						font-size:40rpx;
						font-family:"microsoft yahei";
						font-weight:1000;
						font-style:italic;
						margin-right:20upx;
						color:#2DA4EA;
					}
				}
				.symbol{
					color:#aaa;
					margin-left: 20upx;
				}
				.msglist{
					width: 65%;
					float: left;
					margin-left: 20upx;
					.robomsgitem{
						margin:20upx 0;
						border-bottom:1px solid #fafafa;
						padding:10upx 0;
						display:flex;
						justify-content:space-between;
						align-items:flex-end;
						&.blue {
							.msg{
								color:#0091FF;
							}
						}

					}
				}
			}
		}
		.chats{
			padding:0 0 200upx 0;

		}
		// 发送信息框
		.sendMsgBox{
			position:fixed;
			bottom:0;
			width:100%;
			padding:20upx 10%;
			height:120upx;
			background:#FaFaFa;
			z-index:9999;
			display:flex;
			align-items:center;
			.voice{
				margin-right:16upx;
			}
			.itp{
				flex:1;
				display:flex;
				background:#fff;
				text-indent:20upx;
				border-radius:60upx;
				align-items:center;
				.uni-input{
					height:60upx;
					line-height:60upx;
					flex:1;

				}
				.expression{
					margin-right:16upx;
				}
			}
			.sendBtn{
				width:60upx;
				height:60upx;
				line-height:60upx;
				text-align:center;
				font-size:60upx;
				color:#666;
			}
			.sendTip{
				font-size: 24upx;
				color:#666;

			}
		}
		.scrollBox{
			width: 100%;
			background-color: #D5DCE1;
			position: fixed;
			bottom: 120upx;
			height: 80upx;
		}
		.scroll-view_H {
			white-space: nowrap;
			width: 100%;
		}
		.scroll-view-item_H {
			    display: inline-block;
			    min-width: 20%;
			    height: 40upx;
			    background: #fff;
				line-height: 40upx;
			    text-align: center;
			    font-size: 20upx;
			    border-radius: 40upx;
			    margin: 20upx 16upx;
				padding: 0 10upx;
		}
	
	}
</style>
