<template>
	<view>
		<customNav :shownav="false" title="" tinColor="#006AFF" jiantou="0"></customNav>
		<view class="toptalbarCtv" :style="{top: statusBarHeight+'rpx'}">
			<view class="contentColumnC" style="background-color: #006AFF;height: 90rpx;align-items: center;">
				<view class="contentInRowS" style="width: 92%;">
					<uni-icons custom-prefix="custom-icon" color="white" type="back" size="23" @click="gotoBack"></uni-icons>
					<text style="font-size: 32rpx;color: white;">{{$t('exchange.xinxi')}}</text>
					<text style="font-size: 30rpx;color: white;">{{linkNote}}</text>
					<!-- <uni-icons custom-prefix="custom-icon" color="white" type="person-filled" size="23" @click="friendMSG"></uni-icons> -->
				</view>
			</view>
		</view>
		<view :style="{marginTop: contenttop+'rpx'}">
			<scroll-view scroll-y="true" :style="'height:'+scrollHeight+'rpx;'" :scroll-into-view="btview">
				<view class="contentColumn" style="width: 90%;margin-left: 5%;margin-top: 30rpx;">
					<view v-for="(item,index) in xiaoxiList">
						<view v-if="item.type!=2" class="contentColumn">
							<view class="contentInRowL">
								<text style="font-size: 32rpx;">{{item.rcuser}}</text>
								<text style="font-size: 28rpx;color: darkgray;">{{item.time}}</text>
							</view>
							<view v-if="item.msg.type==0" class="contentInRowL">
								<text class="msgctst">{{item.msg.msg}}</text>
							</view>
							<view v-if="item.msg.type==1" class="contentInRowL">
								<netImage class="spIcon" width="120" height="120" :mysrc="item.msg.msg" mymode="scaleToFill" @Emyimageclick="myimageclick"></netImage>
							</view>
						</view>
						<view v-if="item.type==2" class="contentColumn">
							<view class="contentInRowR" style="align-items: center;margin-top: 20rpx;">
								<text v-if="item.state==2" class="reddoint"></text>
								<text style="font-size: 28rpx;color: darkgray;">{{item.time}}</text>
							</view>
							<view v-if="item.msg.type==0" class="contentInRowR">
								<text class="msgctst">{{item.msg.msg}}</text>
							</view>
							<view v-if="item.msg.type==1" class="contentInRowR">
								<netImage class="spIcon" width="120" height="120" :mysrc="item.msg.msg" mymode="scaleToFill" @Emyimageclick="myimageclick"></netImage>
							</view>
						</view>
					</view>
				</view>
				<view id='bt123' style="height: 140rpx;"></view>
				<view v-if="showActV" style="height: 160rpx;"></view>
			</scroll-view>
			<view class="bottomfloatV">
				<view class="contentInRowC" style="height: 100rpx;align-items: flex-start;margin-top: 8rpx;">
					<input class="inputVst" type="text" :value="msg" :placeholder="$t('exchange.qingshurxx')"  @input="msgInput" confirm-type="send" v-on:confirm="send">
					<uni-icons class="updatamsg" custom-prefix="custom-icon" color="#006AFF" type="plus" size="32" @click="onupdatamsg"></uni-icons>
				</view>
				<view v-if="showActV">
					<view class="item_list" style="width: 90%;">
						<view class="item_content contentColumnC"  v-for="(item, index) in actLst" @click="actLstsel(index)">
							<uni-icons class="updatamsg" custom-prefix="custom-icon" color="#1A1A1A" :type="item.icon" size="32" ></uni-icons>
							<view class="title">
								<text class="text1row" style="font-size: 28rpx;">{{item.title}}</text>
							</view>
						</view>
					</view>
				</view>
			</view>
		</view>
		
	</view>
</template>

<script>
	import api from "@/pages/api/api.js"
	import {
		UploadImage
	} from '@/pages/api/basic.js';
	//import dataBase from "@/pages/api/dataBase.js"
	export default {
		
		data() {
			return {
				statusBarHeight:0,
				contenttop:0,
				scrollHeight:0,
				btview:'bt123',
				userInfo:'',
				linkNote:'',
				msg:'',
				sendIndex:0,
				xiaoxiList:[],
				showActV:false,
				actLst:[],
				roomId: Math.floor(Math.random() * 100000),
				imUser:'',
				iscaller:false,
				isAndroid:false,
				audioObj:null,
				soundPlay:false
			}
		},
		onLoad(option) {
			var systemInfo = uni.getSystemInfoSync();
			this.isAndroid = systemInfo.platform.toLowerCase() === 'android';
			this.statusBarHeight=systemInfo.statusBarHeight*(750/systemInfo.windowWidth);
			this.contenttop=this.statusBarHeight+50;
			this.scrollHeight=systemInfo.windowHeight*(750/systemInfo.windowWidth)-this.contenttop-100;
			
			this.linkNote=this.$t('audioCall.weilianjie') 
			getApp().globalData.EXViewOpen=true;
			this.userInfo = uni.getStorageSync('userInfo');
			if(option.caller==1){
				this.iscaller=true;
				this.imUser = uni.getStorageSync('imUser');
			}
			else{
				var payload=uni.getStorageSync('impayload');
				this.doPushMessage(payload);
				if(!this.isAndroid){
					this.audioObj=uni.createInnerAudioContext();
					this.audioObj.src='hybrid/html/xuanfu/img/y800.mp3';
					this.audioObj.play();
					this.soundPlay=true;
				}
				
			}
			this.initWebSocket();
			this.initACTbut();
			this.getxiaoxiList();
			
		},
		onShow() {
			
		},
		onUnload() {
			if(this.soundPlay){
				this.audioObj.pause();
			}
			this.closeWebSocket();
			getApp().globalData.EXViewOpen=false;
		},
		methods: {
			doPushMessage(str){
				if(str.indexOf("\\\"")!=-1){
					str=str.replace(/\\\"/g, '\"');
					str = str.replace(/\"{/g, '{');
					str = str.replace(/}\"/g, '}');
				}
				var obj = JSON.parse(str)
				this.imUser=obj;
				console.log(this.imUser);
				uni.setStorageSync('imUser',this.imUser)
			},
			getxiaoxiList(){
				var xxstr = 'xiaoxi'+this.imUser.ddId;
				console.log(xxstr);
				var List = uni.getStorageSync(xxstr);
				if(''==List||null==List||undefined==List){
					this.xiaoxiList=[];
					return;
				}
				else{
					if(List.length>20){
						this.xiaoxiList = List.slice(List.length-20);
					}
					else{
						this.xiaoxiList = List;
					}
					var xxstr = 'xiaoxi'+this.imUser.ddId;
					uni.setStorageSync(xxstr,this.xiaoxiList);
				}
				console.log(this.xiaoxiList);
			},
			gotoBack(){
				uni.navigateBack();
			},
			myimageclick(url){
				console.log('myimageclick',JSON.stringify(url));
				uni.navigateTo({
					url:'/pages/index/BigimageView?mysrc='+url
				})
			},
			initACTbut(){
				var img={
					icon:'image',
					title:this.$t('exchange.tupian'),
					index:1
				}
				this.actLst.push(img);
				// var file={
				// 	icon:'upload',
				// 	title:this.$t('exchange.wenjian'),
				// 	index:2
				// }
				// this.actLst.push(file);
				var audio={
					icon:'phone',
					title:'IM',
					index:3
				}
				this.actLst.push(audio);
				// var vidio={
				// 	icon:'videocam',
				// 	title:'视频',
				// 	index:4
				// }
				// this.actLst.push(vidio);
			},
			actLstsel(index){
				console.log(index)
				if(index==0){
					this.selectImage();
					return;
				}
				if(index==1){
					uni.navigateTo({
						url:'/pages/imcall/audioCall?caller=1'
					})
					return;
				}
			},
			//-----------------
			selectImage(){
				var that = this;
				uni.chooseImage({
					count: 1,  // 图片数量
					sizeType: ['compressed'], //可以指定是原图还是压缩图，默认二者都有
					sourceType: ['album'], //从相册选择或者拍照
					success: (res) => {
						const tempFilePaths = res.tempFilePaths;
						console.log('-----',tempFilePaths)
						uni.uploadFile({
							url:this.$baseurl+UploadImage, //上传图片api
							filePath: tempFilePaths[0],
							name: 'file',
							header:{
								//"Authorization": userinfo.token
							},
							success: (res) => {
								let group =  JSON.parse(res.data);
								that.sendImg(group.data);
							}
						});
					}
				});
			},
			sendImg(str){
				var sentMsg={
					msg:str,
					type:1
				};
				var item={
					type:2,
					state:0,
					time:getApp().globalData.sj(),
					msg:sentMsg
				}
				this.xiaoxiList.push(item);
				var xxstr = 'xiaoxi'+this.imUser.ddId;
				uni.setStorageSync(xxstr,this.xiaoxiList);
				console.log(this.xiaoxiList);
				this.sendIndex=this.xiaoxiList.length-1;
				this.sendMessage(sentMsg,0);
			},
			msgInput(event){
				this.msg = event.target.value;
			},
			send(){
				console.log('11111111111111',this.msg)
				if(this.msg.length>0){
					var sentMsg={
						msg:this.msg,
						type:0
					};
					var item={
						type:2,
						state:0,
						time:getApp().globalData.sj(),
						msg:sentMsg
					}
					this.xiaoxiList.push(item);
					var xxstr = 'xiaoxi'+this.imUser.ddId;
					uni.setStorageSync(xxstr,this.xiaoxiList)
					this.sendIndex=this.xiaoxiList.length-1;
					this.sendMessage(sentMsg,0);
					this.msg='';
				}
			},
			onupdatamsg(){
				this.showActV = !this.showActV;
			},
			
			//WebSocket--------------------------------
			// 初始化WebSocket连接
			initWebSocket() {
			  const wsUrl = 'ws://api.awayqtw.com:8080/ws/'+this.userInfo.userId; // 替换为你的WebSocket服务器URL
			 //  this.ws = uni.connectSocket({
				// url: wsUrl,
			 //  });
			 var that = this;
			  this.ws = uni.connectSocket({
			  	url: wsUrl, //仅为示例，并非真实接口地址。
			  	success() {
			  		that.start();
			  	}
			  });
			  console.log(this.ws);
			  // var that = this;
			  // setTimeout(() => {
			  // 	that.start();
			  // }, 1000)
			},
			
			start(){
				var that = this;
				uni.onSocketOpen(function (res) {
				  console.log('WebSocket连接已打开！');
				  if(that.iscaller){
					that.senSocket();  
				  }
				  else{//发送远端连接通知
						that.sendIndex=-1;
					    that.sendMessage('WebSocket远端连接',0);
				  }
				});
				uni.onSocketMessage(function (res) {
					uni.hideLoading();
				  console.log('收到服务器内容：',res);
				  var data = res.data;
				  
				  if(data.indexOf("远端连接")!=-1){
					  that.linkNote=that.$t('audioCall.yilianjie') 
				  	return;
				  }
				  if(data.indexOf("连接成功")!=-1){
				  					  
				  	return;
				  }
				  
				  if(data.indexOf("发送成功")!=-1){//1
					  if(that.sendIndex<0){
						that.linkNote=that.$t('audioCall.yilianjie');
						 return;
					  }
				  	console.log(that.xiaoxiList[that.sendIndex]);
					that.xiaoxiList[that.sendIndex].state=1;
				  	return;
				  }
				  if(data.indexOf("发送失败")!=-1){//2
					  if(that.sendIndex<0){
						return;
					  }
				  	that.xiaoxiList[that.sendIndex].state=2;	  
				  	return;
				  }
				  console.log(JSON.parse(res.data));
				  var rcmag = JSON.parse(res.data);
				  rcmag=JSON.parse(rcmag.msg);
				  var item={
				  	type:1,
					state:3,
				  	time:getApp().globalData.sj(),
				  	msg:rcmag
				  }
				  console.log(item);
				  that.xiaoxiList.push(item);
				  var xxstr = 'xiaoxi'+that.imUser.ddId;
				  uni.setStorageSync(xxstr,that.xiaoxiList);
				});
				
				uni.onSocketError(function (res) {
				  console.log('WebSocket连接打开失败，请检查！');
				});
				
				uni.onSocketClose(function (res) {
				  console.log('WebSocket 已关闭！');
				});
				
			},
			// 发送消息
			sendMessage(sentMsg,type) {
				console.log('sendMessage',sentMsg);
				var data={
					to:this.imUser.userId,
					type:type,//类型0个人，1群聊，2全体
					time:getApp().globalData.sj(),
					msg:sentMsg,
				};
				uni.showLoading({
					title:'Loading...',
					mask:true
				})
				uni.sendSocketMessage({
			      data:JSON.stringify(data)
				});
			},
					 
			// 关闭WebSocket连接
			closeWebSocket() {
			  uni.closeSocket();
			},
			senSocket(){//推送消息通知
				if(this.imUser.cid==''||this.imUser.cid==null||this.imUser.cid==undefined){
					uni.showToast({
						title:this.$t('audioCall.wfjt'),
						icon: 'none',
						duration: 1000
					});
					return;
				}
				var payload={
					ddId:this.imUser.ddId,
					roomId:this.roomId,
					userId:this.userInfo.userId,
					nickName:this.userInfo.nickName,
					avatar:this.userInfo.avatar,
					cid:this.userInfo.cid,
				}
				api('pushMsgYH',{
					cid:this.imUser.cid,
					title:'IM Message',
					content:'IM Message',
					payload:payload
				},res=>{
					console.log(res)
				},failc=>{
					//console.log('getadvertis----',failc)
				})
			},
		}
	}
</script>

<style lang="scss">
page{
	background-color: #F4F4F4;
}
.toptalbarCtv{
	position: fixed;
	background-color: white;
	left: 0;
	right: 0;
	top: 0;
	z-index: 999;
}
.msgctst{
	font-size: 32rpx;
	color: #1a1a1a;
	background-color: white;
	border-radius: 12rpx;
	padding: 16rpx;
}
.mymsgctst{
	font-size: 32rpx;
	color:white;
	background-color: #7a7a7a;
	border-radius: 12rpx;
	padding: 16rpx;
}
.spIcon{
	width: 150rpx;
	height: 150rpx;
}
.bottomfloatV{
	position: fixed;
	flex-direction: column;
	justify-content: center;
	align-items: center;
	left: 0;
	right: 0;
	bottom: 0;
	z-index: 999;
	background-color: white;
}
.inputVst{
	margin-top: 10rpx;
	width: 76%;
	background-color: #F4F4F4;
	height: 80rpx;
	border-radius: 20rpx;
}
.updatamsg{
	margin-left: 10rpx;
	margin-top: 10rpx;
}

.item_list{
	display: flex;
	flex-wrap: wrap;
	justify-content:flex-start;
	width: 90%;
	margin-left: 5%;
	.item_content{
		width: 24.6%;
		height: 160rpx;
		box-sizing: border-box;
		image{
			width: 100rpx;
			height: 100rpx;
			display: block;
		}
		.title{
			width: 100%;
			text-align: center;
			//height: 60rpx;
			line-height: 40rpx;
			padding-bottom: 10rpx;
		}
	}
}
			
.titleview{
	padding-left: 40rpx;
	padding-top: 22rpx;
	line-height: 46rpx;
}
.reddoint{
	background-color: crimson;
	width: 30rpx;
	height: 30rpx;
	border-radius: 15rpx;
	margin-right: 10rpx;
}
</style>
