<template>
	<!-- 聊天记录 -->
	<view class="chat">
		<view class="chat-list">
			<view class="more-btn" @click="tomore">
				{{showmore ? '点击查看更多' : '没有更多了'}}
			</view>
			<view v-for="(item,index) in list" :key="index">
				<view class="u-flex u-row-between" style="margin-bottom: 10rpx;">
					<text :style="{opacity:item.type == 2 ? 1 : 0}"
						style="margin-bottom: -20rpx;">{{item.create_at}}</text>
					<text :style="{opacity:item.type == 2 ? 0: 1}">{{item.create_at}}</text>
				</view>
				<view class="chat-item u-flex u-col-top u-row-between">
					<image :src="item.headimg" :style="{opacity:item.type == 2 ? 1 : 0}" class="user-head" mode="">
					</image>
					<view class="item-box u-flex-1 u-flex-col"
						:style="{alignItems: item.type == 2 ? 'flex-start' : 'flex-end'}">
						<text>{{item.name}}</text>
						<text v-if="item.is_url == 0"
							:class="item.type == 2 ? 'text1' : 'text2'">{{item.content}}</text>
						<view class="" v-if="item.is_url == '1'" @tap="onPlay(item,index)"
							:class="item.type == 2 ? 'back1' : 'back2'">
							<view class="record" v-if="item.type==1">
								<text style="#fff">{{item.time}}</text> "
								<u-icon custom-style="transform: rotate(-90deg) !important;" name="wifi"
									size="28"></u-icon>
							</view>
							<view class="record1" v-if="item.type==2">
								<u-icon custom-style="transform: rotate(90deg) !important;" name="wifi"
									size="28"></u-icon>
								"
								<text>{{item.time}}</text>
							</view>
						</view>
					</view>
					<image :src="item.headimg" :style="{opacity:item.type == 2 ? 0 : 1}" class="user-head" mode="">
					</image>
				</view>
			</view>
			<view class="" v-for="(item,index) in chatlist" :key="index">
				<view class="u-flex u-row-between" style="margin-bottom: 10rpx;">
					<text :style="{opacity:item.type == 2 ? 1 : 0}"
						style="margin-bottom: -20rpx;">{{item.create_at}}</text>
					<text :style="{opacity:item.type == 2 ? 0: 1}">{{item.create_at}}</text>
				</view>
				<view class="chat-item u-flex u-col-top u-row-between">
					<image :src="item.headimg" :style="{opacity:item.type == 2 ? 1 : 0}" class="user-head" mode="">
					</image>
					<view class="item-box u-flex-1 u-flex-col"
						:style="{alignItems: item.type == 2 ? 'flex-start' : 'flex-end'}">
						<text>{{item.name}}</text>
						<text v-if="item.type1 != 'record'"
							:class="item.type == 2 ? 'text1' : 'text2'">{{item.content}}</text>
						<view class="record" v-if="item.type1 == 'record'" :class="item.type == 2 ? 'text1' : 'text2'"
							@tap="onPlay1(item,index)">
							<view class="record" v-if="item.type==1">
								<text>{{item.message}}</text>"<u-icon name="wifi" size="28"></u-icon>
							</view>
							<view class="record1" v-if="item.type==2">
								<u-icon name="wifi" size="28"></u-icon>
								"
								<text>{{item.message}}</text>
							</view>
						</view>
					</view>
					<image :src="item.headimg" :style="{opacity:item.type == 2 ? 0 : 1}" class="user-head" mode="">
					</image>
				</view>
			</view>
		</view>
		<view class="" style="height: 170rpx;"></view>
		<view class="chat-btn u-flex u-row-between">
			<u-icon v-if="show == false" @click="startRecord" name="mic" size="44"></u-icon>
			<u-icon v-if="show == true" @click="startRecord1" name="more-circle-fill" size="44"></u-icon>
			<nb-voice-record v-if="show == true" :vibrate="false" @startRecord="start" @endRecord="end"
				@cancelRecord="cancel"></nb-voice-record>
			<input v-if="show == false" type="text" placeholder="请输入" v-model="text">
			<text v-if="show == false" class="post" @click="send(text)">发送</text>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				bgAudioManager: '', // 全局音频播放
				show: false,
				text: '',
				hx_username: '',
				worker_id: '',
				page: 1,
				list: [],
				chatlist: [],
				myname: '',
				myheadimg: '',
				workername: '',
				workerheadimg: '',
				voicePath: '',
				userinfoheadimg: "",
				ossdata: {},
				duration: 0,
				time1: 0,
				url: "",
				url1: ""
			}
		},
		onLoad(option) {
			this.hx_username = option.hx_username
			this.worker_id = option.worker_id
			console.log(this.worker_id);
			console.log(this.hx_username);
			this.myname = uni.getStorageSync("name")
			this.myheadimg = uni.getStorageSync("headimg")
			this.getlist()
			this.getworker()
			this.getmsg()
			let self = this;
			this.getoss()
			// this.getaudio()
		},
		computed: {
			showmore() {
				if (this.list.length % 20 == 0 && this.list.length > 0) {
					return true
				} else {
					return false
				}
			}
		},
		methods: {
			onPlay(e, index) {
				let that = this
				if (this.url && this.url == e.content) return
				if (this.url && this.url !== e.content) {
					this.bgAudioManager.stop()
					let obj = this.list.find(item => item.content == this.url)
					clearTimeout(obj.timeOut)
					obj.time = obj.defaultTime
				}
				this.url = e.content


				// 我这里没有写暂停播放 需要的可以 设置变量 根据变量状态判断 pause 或 play
				this.bgAudioManager = uni.createInnerAudioContext()
				this.bgAudioManager.src = e.content
				this.bgAudioManager.play()
				this.time1 = e.time

				var music = wx.setInnerAudioOption({
					obeyMuteSwitch: false,
					success: function(res) {
						console.log("开启静音模式下播放音乐的功能");
					},
					fail: function(err) {
						console.log(err);
						console.log("静音设置失败");
					},
				});

				this.bgAudioManager.onPlay(() => {
					function time_a(obj) {
						obj.timeOut = setTimeout(() => {
							obj.time--
							obj.time < 0 ? obj.time = that.time1 : time_a(obj)
						}, 1000)
					}
					time_a(this.list[index])

				})

				this.bgAudioManager.onEnded(() => {
					this.url = ''
					// this.list[index].time = this.time1
					this.bgAudioManager.offPlay()
					this.bgAudioManager.offEnded()
					this.bgAudioManager = null
				})
			},
			onPlay1(e, index) {
				let that = this
				if (this.url1 && this.url1 == e.content) return
				if (this.url1 && this.url1 !== e.content) {
					this.bgAudioManager.stop()
					let obj = this.chatlist.find(item => item.content == this.url1)
					clearTimeout(obj.timeOut)
					obj.message = obj.defaultTime
				}
				this.url1 = e.content

				this.bgAudioManager = uni.createInnerAudioContext()
				this.bgAudioManager.src = e.content
				this.bgAudioManager.play()
				// this.bgAudioManager.obeyMuteSwitch = false
				this.time1 = e.message
				console.log(that.time1);
				var music = wx.setInnerAudioOption({
					obeyMuteSwitch: false,
					success: function(res) {},
					fail: function(err) {},
				});
				this.bgAudioManager.onPlay(() => {
					function time_a(obj) {
						obj.timeOut = setTimeout(() => {
							obj.message--
							// obj.message < 0 ? obj.message = that.time1 : time_a(obj)
							if (obj.message < 0) {
								obj.message = that.time1
								clearTimeout(obj.timeOut)
								that.bgAudioManager.offPlay()
								that.bgAudioManager.offEnded()
								that.bgAudioManager = null
								that.url1 = ''
							} else {
								// console.log(time_a(obj));
								// time_a(obj)
								obj.message = obj.message
								time_a(obj)
							}
						}, 1000)
					}
					time_a(this.chatlist[index])
				})
			},
			start() {
				// 开始录音
			},
			getoss() {
				this.$u.post('/api/Upload/getSignedUrl').then(res => {
					this.ossdata = res.data
				})
			},
			end(event) {
				// 结束录音并处理得到的录音文件
				// event中，app端仅有tempFilePath字段，微信小程序还有duration和fileSize两个字段
				// this.sendPrivateAudio(event.tempFilePath,event.duration)
				if (event.duration < 1000) {
					this.$u.toast("说话时间太短了")
				} else {

					this.duration = event.duration
					var key = this.ossdata.key + new Date().getTime() + Math.floor(Math.random() * 150) + '.mp3'
					uni.uploadFile({
						url: this.ossdata.host, //输入你的bucketname.endpoint
						filePath: event.tempFilePath,
						name: 'file',
						formData: {
							key: key,
							policy: this.ossdata.policy, // 输入你获取的的policy
							OSSAccessKeyId: this.ossdata.OSSAccessKeyId, // 输入你的AccessKeyId
							success_action_status: '200', // 让服务端返回200,不然，默认会返回204
							signature: this.ossdata.Signature, // 输入你获取的的signature
						},
						success: (res) => {
							if (res.statusCode == 200) {
								this.userinfoheadimg = this.ossdata.host + '/' + key
								this.send1(this.userinfoheadimg, this.duration)
							}
						},
						fail: (err) => {
							console.log(err);
						}
					})
				}

			},
			cancel() {
				// 用户取消录音
				console.log(3333);
			},
			startRecord() {
				this.show = true
			},
			startRecord1() {
				this.show = false
			},
			tomore() {
				if (this.showmore) {
					this.page++
					this.getlist()
				}
			},
			getmsg() {
				this.$WebIM.conn.addEventHandler('getmsg', {
					// 当前用户收到文本消息。
					onTextMessage: (message) => {
						console.log(message);
						this.chatlist.push({
							content: message.msg,
							create_at: this.$u.timeFormat(message.time, 'yyyy-mm-dd hh:MM:ss'),
							headimg: message.from == uni.getStorageSync("hx_username") ? this
								.myheadimg : this.workerheadimg,
							name: message.from == uni.getStorageSync("hx_username") ? this.myname :
								this.workername,
							type: message.from == uni.getStorageSync("hx_username") ? 1 : 2,
						})
						this.$nextTick(() => {
							uni.pageScrollTo({
								scrollTop: 99999
							})
						})
					},
					onAudioMessage: (message) => {
						this.chatlist.push({
							// defaultTime:message.length,
							content: message.url,
							create_at: this.$u.timeFormat(message.time, 'yyyy-mm-dd hh:MM:ss'),
							headimg: message.from == uni.getStorageSync("hx_username") ? this
								.myheadimg : this.workerheadimg,
							name: message.from == uni.getStorageSync("hx_username") ? this.myname :
								this.workername,
							type: message.from == uni.getStorageSync("hx_username") ? 1 : 2,
							type1: "record",
							message: message.length
						})
						this.$nextTick(() => {
							uni.pageScrollTo({
								scrollTop: 99999
							})
						})
					},
				})
			},
			getworker() {
				this.$u.post('/api/News/get_worker_info', {
					worker_id: this.worker_id
				}).then(res => {
					this.workername = res.data.name
					this.workerheadimg = res.data.headimg
				})
			},
			getlist() {
				uni.showLoading({
					mask: true,
					title: "请稍后"
				})
				this.$u.post('/api/News/news_list', {
					worker_id: this.worker_id,
					page_num: 20,
					page: this.page
				}).then(res => {
					var list = res.data
					list.forEach(val => {
						val.defaultTime = val.time
						this.list.unshift(val)
					})
					if (this.page == 1) {
						this.$nextTick(() => {
							uni.pageScrollTo({
								scrollTop: 99999
							})
						})
					}

				})
			},
			send1(tempFilePath, duration) {
				var option = {
					type: "audio",
					chatType: "singleChat",
					filename: "tempFilePath",
					from: uni.getStorageSync("hx_username"),
					// 消息接收方：单聊为对端用户 ID，群聊和聊天室分别为群组 ID 和聊天室 ID。
					to: this.hx_username,
					body: {
						//文件 URL。
						url: tempFilePath,
						//文件类型。
						type: "audio",
						//文件名。
						filename: "tempFilePath",
						// 音频文件时长，单位为秒。
						length: Math.ceil(duration / 1000),
					},
				};

				// let option = {
				// 	// 消息类型。
				// 	type: "audio",
				// 	file: tempFilePath,
				// 	// 语音文件长度，单位为秒。
				// 	length: Math.ceil(duration / 1000),
				// 	// 消息接收方：单聊为对方用户 ID，群聊和聊天室分别为群组 ID 和聊天室 ID。
				// 	to: this.hx_username,
				// 	// 会话类型：单聊、群聊和聊天室分别为 `singleChat`、`groupChat` 和 `chatRoom`。
				// 	chatType: "singleChat",
				// 	// 语音文件上传失败。
				// 	// onFileUploadError: function() {
				// 	// 	console.log("onFileUploadError");
				// 	// },
				// 	// // 语音文件上传进度。
				// 	// onFileUploadProgress: function(e) {
				// 	// 	console.log(e);
				// 	// },
				// 	// // 语音文件上传成功。
				// 	// onFileUploadComplete: function() {
				// 	// 	console.log("onFileUploadComplete");
				// 	// },
				// 	// ext: {},
				// };
				// let option = {
				// 	// 消息类型。
				// 	type: "txt",
				// 	// 消息内容。
				// 	msg: tempFilePath,
				// 	// 消息发送方：单聊为对方用户 ID，群聊和聊天室分别为群组 ID 和聊天室 ID。
				// 	from: uni.getStorageSync("hx_username"),
				// 	// 消息接收方：单聊为对方用户 ID，群聊和聊天室分别为群组 ID 和聊天室 ID。
				// 	to: this.hx_username,
				// 	// 会话类型：单聊、群聊和聊天室分别为 `singleChat`、`groupChat` 和 `chatRoom`，默认为单聊。
				// 	chatType: "singleChat",
				// };
				let msg = this.$WebIM.message.create(option);
				console.log(msg);
				this.$WebIM.conn.send(msg).then(res => {
					this.$u.post('/api/News/send_news', {
						worker_id: this.worker_id,
						content: tempFilePath,
						type1: "record",
						time: msg.body.length
					}).then(res => {
						this.chatlist.push({
							defaultTime: msg.body.length,
							content: tempFilePath,
							create_at: this.$u.timeFormat(msg.time, 'yyyy-mm-dd hh:MM:ss'),
							headimg: this.myheadimg,
							name: this.myname,
							type: 1,
							type1: "record",
							message: msg.body.length
						})
						this.$nextTick(() => {
							uni.pageScrollTo({
								scrollTop: 99999
							})
						})

						console.log(this.chatlist);
					})
				})
			},




			send(text) {
				if (!text) {
					this.$u.toast("请输入内容")
					return
				}
				this.text = ''
				let option = {
					// 消息类型。
					type: "txt",
					// 消息内容。
					msg: text,
					// 消息发送方：单聊为对方用户 ID，群聊和聊天室分别为群组 ID 和聊天室 ID。
					from: uni.getStorageSync("hx_username"),
					// 消息接收方：单聊为对方用户 ID，群聊和聊天室分别为群组 ID 和聊天室 ID。
					to: this.hx_username,
					// 会话类型：单聊、群聊和聊天室分别为 `singleChat`、`groupChat` 和 `chatRoom`，默认为单聊。
					chatType: "singleChat",
				};
				// 创建文本消息。
				let msg = this.$WebIM.message.create(option);
				// console.log(msg);
				this.$WebIM.conn.send(msg).then(res => {
					this.$u.post('/api/News/send_news', {
						worker_id: this.worker_id,
						content: text
					}).then(res => {
						this.chatlist.push({
							content: msg.msg,
							create_at: this.$u.timeFormat(msg.time, 'yyyy-mm-dd hh:MM:ss'),
							headimg: this.myheadimg,
							name: this.myname,
							type: 1,
						})
						this.$nextTick(() => {
							uni.pageScrollTo({
								scrollTop: 99999
							})
						})

						// console.log(this.chatlist);
					})
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
	page {
		background-color: #F2F2F2;
	}

	.record {
		display: flex;
		align-items: center;
		background-color: #1F7EFF;
		color: #fff;
		border-radius: 20rpx;
		box-sizing: border-box;
	}

	.record1 {
		display: flex;
		align-items: center;
		background-color: #eee;
		color: #000;
		border-radius: 20rpx;
		box-sizing: border-box;
	}

	.quxiao {

		background: #1F7EFF;
		border-radius: 12rpx;
		font-size: 30rpx;
		font-family: PingFangSC-Medium, PingFang SC;
		font-weight: 500;
		color: #000;
		text-align: center;
		height: 84rpx;
		line-height: 84rpx;
	}

	.fasong {
		background: limegreen;
		border-radius: 12rpx;
		font-size: 30rpx;
		font-family: PingFangSC-Medium, PingFang SC;
		font-weight: 500;
		color: #fff;
		text-align: center;
		height: 84rpx;
		line-height: 84rpx;
	}

	.chat {
		.chat-list {
			padding: 24rpx;

			.more-btn {
				padding: 10rpx 0;
				text-align: center;
			}

			.chat-item {
				margin-bottom: 44rpx;

				.item-box {
					text:first-child {
						font-size: 28rpx;
						font-weight: 500;
						// color: #666666;
						padding: 8rpx 24rpx;
					}

					text:last-child {

						padding: 9rpx 24rpx;
						border-radius: 20rpx;
					}

					.text1 {
						background-color: #fff;
						border-radius: 20rpx;
					}

					.text2 {
						background-color: #1F7EFF;
						color: #fff;
						border-radius: 20rpx;
					}
				}

				.user-head {
					width: 70rpx;
					height: 70rpx;
					border-radius: 100rpx;
				}
			}
		}

		.chat-btn {
			position: fixed;
			bottom: 0;
			left: 0;
			width: 750rpx;
			height: 166rpx;
			background: #FFFFFF;
			z-index: 10;
			padding: 0 24rpx 60rpx 24rpx;

			input {
				// width: 540rpx;
				flex: 1;
				margin-right: 20rpx;
				height: 58rpx;
				background: #F2F2F2;
				border-radius: 30rpx;
				padding: 0 28rpx;
				box-sizing: border-box;
			}

			.post {
				width: 102rpx;
				line-height: 58rpx;
				background: #1F7EFF;
				border-radius: 30rpx;
				text-align: center;
				font-size: 24rpx;
				// font-family: PingFangSC-Regular, PingFang SC;
				font-weight: 400;
				color: #FFFFFF;
			}
		}
	}

	::v-deep .record-btn {
		width: 80vw !important;
		text-align: center !important;
		flex: 1 !important;
	}

	::v-deep .record .u-icon.data-v-6e20bb40 {
		transform: rotate(-90deg) !important;
	}

	::v-deep .record1 .u-icon.data-v-6e20bb40 {
		transform: rotate(90deg) !important;
	}
</style>