<template>
	<view class="chat">
		<view class="chat-navbar">
			<u-navbar :title="title">
				<view class="slot-wrap" slot="right" @click="toSheet()">
					<u-icon name="more-dot-fill" color="#000000" size="30"></u-icon>
				</view>
			</u-navbar>
		</view>
		<view class="chat-hd" v-if="list.length>0">
			<u-notice-bar style="width: 100%;" :volume-icon="false" mode="horizontal" :list="list"></u-notice-bar>
		</view>
		<scroll-view class="chat-bd" scroll-y :class="list.length==0?(isOpen?'chat-bd-active1':'chat-bd-active'):(isOpen?'chat-bd-on':'')">
			<view class="item" :class="userId != a.rightUserId?'item-on':''" v-for="(a,index) in chatList" :key="index">
				<template v-if="userId != a.rightUserId">
					<view class="fr">
						<view class="desc">{{a.message}}</view>
					</view>
					<view class="fl"><image :src="a.leftFaceImage"></image></view>
				</template>
				<template v-else>
					<view class="fl"><image :src="a.rightFaceImage"></image></view>
					<view class="fr">
						<view class="name">李大花<text>陪玩师</text></view>
						<view class="desc" v-if="a.type == 6 || a.type==3">{{a.message}}</view>
						<view class="gift" v-if="a.type == 5">送出礼物<image mode="widthFix" src="/static/logo.png"></image>棒棒糖<text>X3</text></view>
						<view class="yinping" v-if="a.type == 1">
							<image src="@/static/chat-03.png"></image> 8”
						</view>
						<view class="video" v-if="a.type == 2">
							<video src=""></video>
						</view>
						<view class="img" v-if="a.type == 4">
							<image src="/static/pic.jpg"></image>
						</view>
					</view>
				</template>
			</view>
		</scroll-view>
		<view class="chat-fd">
			<view class="a">
				<view class="luyin" @click="toToggle()">
					<image v-if="isToggle" src="/static/chat-01.png"></image>
					<image v-else src="/static/chat-05.png"></image>
				</view>
				<view class="input" v-if="isToggle">
					<input type="text" v-model="content" placeholder="单行输入" />
					<view class="more" @click="isOpen = !isOpen">
						<u-icon name="more-dot-fill" color="#000000" size="30"></u-icon>
					</view>
				</view>
				<view class="input" v-else>
					<view class="star" v-if="isPlay">开始录音</view>
					<view class="star" v-else>停止录音</view>
				</view>
				<view class="btn" @click="toSend()">
					发送
				</view>
			</view>
			<view class="b" v-if="isOpen">
				<image @click="uploadImg()" src="@/static/chat-zhaopian.png"></image>
				<image @click="uploadVideo()" src="@/static/chat-xiangji.png"></image>
				<image src="@/static/chat-yinshipin.png"></image>
				<image @click="openGift()" src="@/static/chat-liwu.png"></image>
			</view>
		</view>
		
		<u-popup v-model="show" mode="top" :mask-close-able='false' :zIndex="5">
			<view class="permissions_box">
				当您使用APP时，为了使用录音的功能，我们需要申请麦克风权限。
			</view>
		</u-popup>
	</view>
</template>

<script>
	import permision from "@/js_sdk/wa-permission/permission.js"
	const recorderManager = uni.getRecorderManager();
	const innerAudioContext = uni.createInnerAudioContext();
	innerAudioContext.autoplay = true;
	let timer = 0;
	// import ZIM from '@/js_sdk/zego-ZIMUniplugin-JS/lib/index.js';
	// ZIM.create({ appID: 267111980, appSign: 'afcaa90a7750ee556e450ca62287c5f9a362e9ed711789717cda0e18f088858e' });
	// const zim = ZIM.getInstance();
	export default {
		data() {
			return {
				id: "",
				isToggle: true,
				isOpen: false,
				title: "",
				content: "",
				userInfo: {},
				list: [],
				itemList: [],
				chatList: [],
				userId: "",
				img: "",
				show: false,
				isPlay: true,
				
			};
		},
		onLoad(o) {
			this.userId = uni.getStorageSync("userInfo").id;
			this.id = o.id;
			this.getUserInfo();
			this.getChatList();
		},
		onReady() {
			const that = this;
			this.toImLogin()
			recorderManager.onStop(function (res) {
				that.uploadVideo(res.tempFilePath);
				clearInterval(timer);
			});
			innerAudioContext.onEnded(res=>{
				that.isPlay = false
			})
			// 注册监听“收到单聊消息”的回调
			// zim.on('receivePeerMessage', function (zim, { messageList, fromConversationID }) {
			//     console.log('receivePeerMessage', messageList, fromConversationID);
			// });
		},
		methods: {
			toToggle() {
				this.isToggle = !this.isToggle
			},
			toOpen(){
				// APP检查权限
				if(uni.getSystemInfoSync().platform == 'android') {
					plus.android.checkPermission(
						'android.permission.RECORD_AUDIO',
						granted => {
						  if (granted.checkResult==-1){
							that.show=true
						  }else{
							that.show=false
							if(that.isPlay){
								innerAudioContext.pause();
								that.isPlay = false
							}
						  }
						},
						error => {
						  console.error('Error checking permission:', error.message);
						}
					  );
					 that.requestAndroidPermission('android.permission.RECORD_AUDIO')
					return ;
				}
			},
			recorderAuthModal: function () {
				const that = this;
				uni.showModal({
					title: '温馨提示',
					content: '为了麦克风的功能，我们需要申请麦克风权限，请您确认授权，否则无法使用该功能~',
					cancelText: '关闭',
					confirmText: '去授权',
					success(res) {
						that.show=false
						if (res.confirm) {
							permision.gotoAppPermissionSetting()
						}
					}
				})
			},
			async requestAndroidPermission(permisionID) {
				const that = this;
				var result = await permision.requestAndroidPermission(permisionID);
				if(result != 1){
					that.recorderAuthModal();
				}else{
					that.show =false
				}
			},
			//上传语音
			uploadVideo(filePath) {
				const that = this
				uni.uploadFile({
					name: 'file',
					url: that.$baseUrl+'/prod-api/common/upload',
					filePath,
					success: (res) => {
						const {code, fileName, url, msg} = JSON.parse(res.data);
						if(code == 200){
							that.img = url
						}
					},
					fail: (err) => {
						console.log(err)
					}
				});	
			},
			//上传视频
			uploadVideo() {
				const that = this
				uni.chooseVideo({
					count: 1,
					sourceType: ["album", "camera"],
					success: (res1) => {
						console.log(res1)
						uni.uploadFile({
							name: 'file',
							url: that.$baseUrl+'/prod-api/common/upload',
							filePath: res1.tempFilePath,
							success: (res) => {
								const {code, fileName, url, msg} = JSON.parse(res.data);
								if(code == 200){
									that.img = url
								}
							},
							fail: (err) => {
								console.log(err)
							}
						});	
					},
					fail(err){
						console.log("fail",err)
					}
				});
			},
			//上传图片
			uploadImg() {
				const that = this
				uni.chooseImage({
					count: 1,
					sizeType: ["original"], //可以指定是原图还是压缩图，默认二者都有
					sourceType: ["album", "camera"],
					success: (res1) => {
						console.log(res1)
						uni.uploadFile({
							name: 'file',
							url: that.$baseUrl+'/prod-api/common/upload',
							filePath: res1.tempFilePath,
							success: (res) => {
								const {code, fileName, url, msg} = JSON.parse(res.data);
								if(code == 200){
									that.img = url
								}
							},
							fail: (err) => {
								console.log(err)
							}
						});	
					},
					fail(err){
						console.log("fail",err)
					}
				});
			},
			toSend() {},
			//登录房间
			toImLogin() {
				// zim.login(uni.getStorageSync("userInfo").id, {
				// 		userName: uni.getStorageSync("userInfo").nickname,
				// 		token: uni.getStorageSync("chatToken"),
				// })
				// .then(function (res) {
				//     // 登录成功
				// 	console.log(res,"登录成功")
				// })
				// .catch(function (err) {
				//     // 登录失败
				// 	console.log(err)
				// });
			},
			async getChatList(){
				const { code, data , msg } = await this.$api.findChatList({formUserId: uni.getStorageSync("userInfo").id,toUserId: this.id});
				if(code == 200){
					this.chatList= data;
				}
			},
			async getUserInfo() {
				const { code, data , msg } = await this.$api.findOtherUserInfo({userId: uni.getStorageSync("userInfo").id,sellerId: this.id,});
				if(code == 200){
					this.userInfo = data;
					this.itemList = ["查看TA的主页", (data.isCare == 0?"关注":"取消关注"), "举报", (data.isBlack == 0?"加入黑名单":"移除黑名单")];
					this.title = data.nickname+(data.isOnline == 1?"_(在线)":"_(离线)");
					this.getConfigData();
				}else{
					uni.showToast({
						title: mgs,
						position: "bottom",
						icon: "none",
					})
				}
			},
			//字典查询
			async getConfigData() {
				const that = this;
				let res1 = await that.$api.getConfigData({dictType: 'CONFIG_MESSAGE_NOTICE'});
				that.list = [res1.data.content]
			},
			//加入黑名单
			async toYichu(type) {
				const { code, data } = await this.$api.addOrRemoveBlacklist({
					userId: uni.getStorageSync("userInfo").id,
					sellerId: this.id,
					type
				})
				if(code == 200){
					uni.showToast({
						title: type == 2?"移除成功":"加入成功"
					})
					setTimeout(()=>{
						this.getInfo();
					},2000)
				}
			},
			toSheet() {
				uni.showActionSheet({
					itemList: this.itemList,
					success(res){
						console.log(res.tapIndex)
					}
				})
			},
			inputValue(e) {
				console.log(e)
			},
		},
		onBackPress() {
			zim.logout();
		}
	}
</script>

<style scoped lang="scss">
.chat{
	&-navbar{
		width: 100%;
		.slot-wrap{
			margin-right: 30rpx;
		}
	}
	&-hd{
		width: 100%;
		height: 70rpx;
		background: #FFEBEB;
		font-weight: 500;
		font-size: 24rpx;
		color: #222222;
		line-height: 70rpx;
		padding: 0 10rpx;
		box-sizing: border-box;
		display: flex;
		align-items: center;
	}
	&-bd{
		width: 100%;
		height: calc(100vh - 190rpx - 88rpx);
		padding: 0 25rpx;
		box-sizing: border-box;
		&-on{
			height: calc(100vh - 190rpx - 88rpx - 160rpx);
		}
		&-active{
			height: calc(100vh - 120rpx - 88rpx);
		}
		&-active1{
			height: calc(100vh - 120rpx - 88rpx - 160rpx);
		}
		.item{
			padding: 20rpx 0;
			width: 100%;
			align-items: flex-start;
			display: flex;
			overflow: hidden;
			justify-content: flex-start;
			.fl{
				width: 80rpx;
				height: 80rpx;
				border-radius: 50%;
				margin-right: 20rpx;
				image{
					width: 100%;
					height: 100%;
					border-radius: 50%;
				}
			}
			.fr{
				flex: 1;
				overflow: hidden;
				.name{
					font-weight: 500;
					font-size: 28rpx;
					color: #222222;
					display: flex;
					align-items: center;
					text{
						width: 100rpx;
						line-height: 40rpx;
						background: linear-gradient(0deg, #000000, #3D3B38);
						box-shadow: 0px 4rpx 18rpx 0px rgba(42,41,39,0.34);
						border-radius: 40rpx;
						text-align: center;
						font-weight: 500;
						font-size: 22rpx;
						color: #FFFFFF;
						display: block;
						margin-left: 30rpx;
					}
				}
				.video{
					width: 400rpx;
					background: #FFFFFF;
					border-radius: 20rpx;
					margin-top: 20rpx;
					padding: 20rpx;
					video{
						width: 100%;
					}
				}
				.img{
					width: 400rpx;
					background: #FFFFFF;
					border-radius: 20rpx;
					margin-top: 20rpx;
					padding: 20rpx;
					image{
						width: 100%;
					}
				}
				.yinping{
					width: 200rpx;
					background: #FFFFFF;
					border-radius: 10rpx;
					margin-top: 20rpx;
					padding: 20rpx;
					display: flex;
					align-items: center;
					color: #000;
					font-size: 30rpx;
					image{
						width: 50rpx;
						height: 50rpx;
						margin-right: 20rpx;
					}
				}
				.gift{
					font-weight: 500;
					font-size: 24rpx;
					color: #999999;
					line-height: 44px;
					display: flex;
					align-items: center;
					margin-top: 20rpx;
					image{
						width: 60rpx;
						margin: 0 10rpx;
					}
					text{
						margin-left: 10rpx;
					}
				}
				.desc{
					max-width: 400rpx;
					background: #FFFFFF;
					border-radius: 30rpx 0px 30rpx 30rpx;
					margin-top: 20rpx;
					padding: 30rpx;
					font-weight: 500;
					font-size: 30rpx;
					color: #222222;
					line-height: 48rpx;
				}
			}
			
			&-on{
				.fl{
					margin-left: 20rpx;
					margin-right: 0;
				}
				.fr{
					.desc{
						float: right;
						background: #EAEBEB;
						border-radius: 0px 30rpx 30rpx 30rpx;
					}
				}
			}
		}
	}
	&-fd{
		width: 100%;
		min-height: 120rpx;
		background: #F6F6F6;
		.a{
			width: 100%;
			height: 120rpx;
			display: flex;
			align-items: center;
			justify-content: space-between;
			padding: 0 20rpx;
			box-sizing: border-box;
			.luyin{
				width: 50rpx;
				height: 50rpx;
				image{
					width: 100%;
					height: 100%;
				}
			}
			.input{
				flex: 1;
				height: 80rpx;
				background: #FFFFFF;
				border-radius: 10rpx;
				display: flex;
				align-items: center;
				justify-content: space-between;
				margin-left: 20rpx;
				margin-right: 20rpx;
				font-size: 30rpx;
				.star{
					flex: 1;
					line-height: 80rpx;
					text-align: center;
					background: #FFFFFF;
				}
				editor,input{
					flex: 1;
					height: 50rpx;
					line-height: 50rpx;
					min-height: 50rpx;
					font-style: normal !important; 
					margin-left: 20rpx;
				}
				.more{
					margin: 0 20rpx;
				}
			}
			.btn{
				width: 120rpx;
				line-height: 70rpx;
				background: linear-gradient(0deg, #000000, #3D3B38);
				box-shadow: 0px 4rpx 18rpx 0px rgba(42,41,39,0.34);
				border-radius: 50rpx;
				text-align: center;
				font-weight: 500;
				font-size: 28rpx;
				color: #FFFFFF;
			}
		}
		.b{
			width: 100%;
			height: 160rpx;
			display: flex;
			align-items: center;
			justify-content: space-between;
			border-top: 1px solid #E2E2E2;
			padding: 0 45rpx;
			box-sizing: border-box;
			image{
				width: 100rpx;
				height: 100rpx;
				display: block;
			}
		}
	}
}
</style>
