<template>
	<view class="main">
		<view class="padding text-center text-white" style="background-color: #dddcdc;margin-left: 60rpx;margin-right: 60rpx;margin-top: 25rpx;" v-if="sures">
			本次咨询：24小时内回复有效。超时平台将自动退单，请及时回复患者。
		</view>
		<view class="cu-chat" style="position: relative;" v-for="(item,index) in messages" :key="index">
			<view class="cu-item self" v-if="item.senderId==currentUser.uuid">
				<view class="time-lag" style="position: absolute;top: 36rpx; right: 43%;">
					{{renderMessageDate(item, index)}}
				</view>
				<view class="main" style="width: 500rpx;word-break:break-all;display: flex;justify-content: flex-end;" v-if="item.type=='text'">
					<view class="content bg-green shadow">
						<text>{{item.payload.text}}</text>
					</view>
				</view>
				<view class="main" v-else-if="item.type =='image'">
					<image :src="item.payload.url" @click="yulan(item.payload.url)" :style="'width:'+item.payload.width+'rpx;height'+item.payload.height+'rpx;'"
					 class="radius" mode="widthFix"></image>
				</view>
				<view class="main" v-else="item.type =='audio'">
					<GoEasyAudioPlayer :src="item.payload.url" :duration="item.payload.duration" />
				</view>
				<view class="cu-avatar radius" :style="'background-image:url('+currentUser.avatar+');'"></view>
			</view>
			<view class="cu-item" v-else>
				<view class="cu-avatar radius" :style="'background-image:url('+doctorInfo.user_avatar+');'"></view>
				<view class="main" style="width: 500rpx;word-break:break-all;" v-if="item.type=='text'">
					<view class="content shadow">
						<text>{{item.payload.text}}</text>
					</view>
				</view>
				<view class="main" v-else-if="item.type =='image'">
					<image :src="item.payload.url" @click="yulan(item.payload.url)" :style="'width:'+item.payload.width+'rpx;height'+item.payload.height+'rpx;'"
					 class="radius" mode="widthFix"></image>
				</view>
				<view class="main" v-else="item.type =='audio'">
					<GoEasyAudioPlayer :src="item.payload.url" :duration="item.payload.duration" />
				</view>
			</view>
		</view>
		<view class="padding text-center text-white" style="background-color: #dddcdc;margin-left: 60rpx;margin-right: 60rpx;" v-if="!sures">
			本次咨询已结束，如还有问题可向患者发起电话回访。
		</view>
		<view class="cu-tabbar-height"></view>
		<!-- <view class="cu-tabbar-height"></view> -->
		<view :class="InputBottom!=0?'cu-bar foot tab input cur':'cu-bar foot input'" style="padding-bottom: 45rpx;padding-top: 45rpx;"
		 :style="'bottom:'+InputBottom+'px'" v-show="sures">
			<view class="action" @click="sendvoice">
				<text class="cuIcon-sound text-grey"></text>
			</view>
			<input v-if="!isvoice" v-model="keyword" class="solid-bottom" @focus="InputFocus" @blur="InputBlur" :disabled="isinput"
			 :adjust-position="false" :focus="false" maxlength="300" :placeholder="textinput" cursor-spacing="10"></input>
			<button class="flex-sub" style="font-size: 30rpx; height: 64rpx;padding: 0;" @longpress="onRecordStart"
			 @touchend.stop="onRecordEnd" v-else>{{audio.recording ? '松开发送':'按住发送语音'}}</button>
			<view class="action" style="margin-right: 20rpx;" @click="sendImage">
				<text class="cuIcon-picfill text-grey"></text>
			</view>
			<button class="cu-btn bg-green shadow" @click="sendMessage">发送</button>
		</view>
		<view class="record-loading" v-if="audio.recording"></view>


		<view class="top_details" @click="detailsShow = true" v-if="orderDetailsList.length!=0">
			<u-icon name="arrow-down" size="40"></u-icon>
		</view>
		<u-popup v-model="detailsShow" mode="top">
			<view class="details">
				<view>患者姓名:<text>{{orderDetailsList.name}}</text></view>
				<view>患者年龄:<text>{{orderDetailsList.numbirthday}}</text></view>
				<view>患者性别:<text>{{orderDetailsList.sex==2?'女':'男'}}</text></view>
				<view>症状描述:{{orderDetailsList.symptoms}}</view>
				<view>图片:</view>
				<scroll-view :scroll-x="true">
					<view style="display: flex;">
						<view v-for="item,index in orderDetailsList.medical_imgs" :key='index' style="margin: 0 10rpx 10rpx 0 ;">
							<image mode="aspectFit" :src="item" @click="TanPreviewImage(item)" style="height: 200rpx;width: 200rpx;"></image>
						</view>
					</view>
				</scroll-view>
			</view>

			<view class="bot_details" @click="detailsShow = false">
				<u-icon name="arrow-up" size="40"></u-icon>
			</view>
		</u-popup>
	</view>
</template>

<script>
	import {
		sendMessages
	} from "../../common/goeasyimutil.js"
	import store from '@/store'
	import GoEasyAudioPlayer from "../../components/GoEasyAudioPlayer/GoEasyAudioPlayer.vue";
	import IMService from "../../common/goeasyimutil.js"
	const recorderManager = uni.getRecorderManager()
	export default {
		components: {
			GoEasyAudioPlayer
		},
		onLoad: function(op) {
			// this.messages = []
			// this.self_messages = []
			console.log('聊天状态', op)
			if (op.type == 2) {
				this.sures = false;
			}
			this.imService = getApp().globalData.imService;
			this.doctorInfo = JSON.parse(op.patient)
			console.log(this.doctorInfo)
			// this.getMessage("member_" + this.doctorInfo.user_id)
			//对话数据
			this.friend = {
				uuid: "member_" + this.doctorInfo.user_id,
				name: this.doctorInfo.user_name,
				avatar: this.doctorInfo.user_avatar
			};

			this.currentUser = this.imService.currentUser;

			let privateMessages = this.imService.getPrivateMessages(this.friend.uuid);
			this.messages = privateMessages.sentMessages;
			this.pendingMessages = privateMessages.pendingMessages;
			uni.setNavigationBarTitle({
				title: this.friend.name
			});
			this.initialListeners();
			//每次进入聊天页面，总是滚动到底部

			//收到的消息设置为已读
			if (this.messages.length != 0) {
				this.imService.markPrivateMessageAsRead(this.friend.uuid);
			}
			this.loadMoreHistoryMessage();
			// 获取订单详情
			this.getOrderDetails();
		},
		mounted() {

		},
		data() {
			return {
				//控制患者详情
				detailsShow: false,
				sures: true,
				keyword: "",
				InputBottom: 0,
				isvoice: false,
				textinput: "请输入",
				isinput: false,
				messages: [],
				self_messages: [],
				friend: null,
				currentUser: null,
				imService: null,
				audio: {
					//语音录音中
					recording: false,
				},
				doctorInfo: {},
				orderDetailsList: {}
			}
		},
		onPullDownRefresh: function(e) {
			this.loadMoreHistoryMessage();
		},
		onUnload() {
			console.log("页面卸载")
			this.messages.splice(0, this.messages.length)
			//退出聊天页面之前，清空页面传入的监听器
			if (this.imService) {
				this.imService.onNewPrivateMessageReceive = (friendId, message) => {};
			}
		},
		methods: {
			//图片预览
			TanPreviewImage(imageUrl) {
				console.log(imageUrl) // http://192.168.100.251:8970/6_1597822634094.png
				var images = [];
				images.push(imageUrl);
				console.log(images) // ["http://192.168.100.251:8970/6_1597822634094.png"]
				uni.previewImage({ // 预览图片  图片路径必须是一个数组 => ["http://192.168.100.251:8970/6_1597822634094.png"]
					current: 0,
					urls: images,
					longPressActions: { //长按保存图片到相册
						itemList: ['保存图片'],
						success: (data) => {
							console.log(data);
							uni.saveImageToPhotosAlbum({ //保存图片到相册
								filePath: payUrl,
								success: function() {
									uni.showToast({
										icon: 'success',
										title: '保存成功'
									})
								},
								fail: (err) => {
									uni.showToast({
										icon: 'none',
										title: '保存失败，请重新尝试'
									})
								}
							});
						},
						fail: (err) => {
							console.log(err.errMsg);
						}
					}
				});
			},
			//
			getOrderDetails: async function() {
				let res = await this.$request.post("patient/CaseAcquisition", {
					'user_id': this.doctorInfo.user_id
				});
				if (res.status == 0) {
					console.log("订单详情", res)
					this.orderDetailsList = res.data
					this.orderDetailsList.medical_imgs = this.orderDetailsList.medical_imgs.split(",")

					// this.orderDetailsList.medical_imgs = this.orderDetailsList.medical_imgs.replace(/"/g,"")
					// this.orderDetailsList.medical_imgs = this.orderDetailsList.medical_imgs.replace("]"/g,"")
					// this.orderDetailsList.medical_imgs = this.orderDetailsList.medical_imgs.replace("["/g,"")
					// this.orderDetailsList.medical_imgs.forEach(function(element) {
					// 	element = element.replace(/\"/g, ""); 
					// 	element = element.replace("[","")
					// 	element = element.replace("]","")
					// });
					for (let a = 0; a < this.orderDetailsList.medical_imgs.length; a++) {
						this.orderDetailsList.medical_imgs[a] = this.orderDetailsList.medical_imgs[a].replace(/\"/g, "");
						this.orderDetailsList.medical_imgs[a] = this.orderDetailsList.medical_imgs[a].replace("[", "");
						this.orderDetailsList.medical_imgs[a] = this.orderDetailsList.medical_imgs[a].replace("]", "");
					}
					console.log("图片", this.orderDetailsList.medical_imgs)
				}
			},
			// ["https://wechat.fresherbaby.com/uploads/20210119/4IPuheVvP1s7hX5LvHoHcexiswK0DY4XGCNlplba.jpeg","https://wechat.fresherbaby.com/uploads/20210119/NECAiCuWs3mHwH7cb5YiqVhGiwTakxzawfYsK1Ii.jpeg","https://wechat.fresherbaby.com/uploads/20210119/FJkLJVfEBn3sjsltkhvCVh0vdnGfokcWoBVZi8sr.jpeg","https://wechat.fresherbaby.com/uploads/20210119/Ef0E7fgB0fiBf5HQaX6vlSqP2HGP3LnZ0D5i8pfd.jpeg"]
			// getMessage: async function(flag) {
			// 	let res = await this.$request.post("doctor/getImList", {
			// 		'flag': flag
			// 	});
			// 	if (res.status == 0) {
			// 		if (res.data.length != 0) {
			// 			let newList = [];
			// 			for (let i = 0; i < res.data.length; i++) {
			// 				this.messages.push(res.data[i]);
			// 				// newList.push(res.data[i]);
			// 			}
			// 		}
			// 		this.scrollToBottom()
			// 	}
			// },
			renderMessageDate(message, index) {
				if (index === 0) {
					return this.formatDate(message.timestamp)
				} else {
					if (message.timestamp - this.messages[index - 1].timestamp > 5 * 60 * 1000) {
						return this.formatDate(message.timestamp)
					}
				}
				return ''
			},
			InputFocus(e) {
				this.InputBottom = e.detail.height
			},
			InputBlur(e) {
				this.InputBottom = 0
			},
			sendvoice() {
				this.isvoice = !this.isvoice
			},
			subscribeMessage() { //订阅消息

			},
			yulan(url) {
				uni.previewImage({
					urls: [url],
					current: url
				})
			},
			initialListeners() {
				//传入监听器，收到一条私聊消息总是滚到到页面底部
				this.imService.onNewPrivateMessageReceive = (friendId, message) => {
					if (friendId == this.friend.uuid) {
						this.imService.markPrivateMessageAsRead(friendId);
						//收到新消息，是滚动到最底部

						this.scrollToBottom()
					}
				};
				// 录音监听器
				this.initRecorderListeners();
			},
			initRecorderListeners() {
				let self = this;
				// 监听录音开始
				recorderManager.onStart(function() {
					self.audio.recording = true;
				});

				//录音结束后，发送
				recorderManager.onStop(function(res) {
					console.log(res)
					self.audio.recording = false;
					self.imService.sendPrivateAudioMessage(self.friend.uuid, res)
				});

				// 监听录音报错
				recorderManager.onError(function(res) {
					console.log("录音报错：", res);
				})
			},
			onRecordStart(event) {
				try {
					recorderManager.start();
				} catch (e) {
					uni.showModal({
						title: '发送语音错误',
						content: '请联系客服'
					});
				}
				event.preventDefault();
			},
			onRecordEnd() {
				try {
					recorderManager.stop();
				} catch (e) {
					uni.showModal({
						title: '发送语音错误',
						content: '请联系客服'
					});
				}
			},
			sendMessage() { //发送消息
				if (this.keyword.trim() != '') {
					console.log(this.friend.uuid)
					this.imService.sendPrivateTextMessage(this.friend.uuid, this.keyword);
				}
				this.keyword = "";
			},
			scrollToBottom() {
				this.$nextTick(function() {
					uni.pageScrollTo({
						scrollTop: 2000000,
						duration: 10
					})
				})
				console.log("滚动")
			},
			sendImage() {
				uni.chooseImage({
					count: 1,
					success: (res) => {
						this.imService.sendPrivateImageMessage(this.friend.uuid, res);
					}
				})
			},
			loadMoreHistoryMessage() { //历史消息
				let lastMessageTimeStamp = Date.now();
				let lastMessage = this.messages[0];
				if (lastMessage) {
					lastMessageTimeStamp = lastMessage.timestamp;
				}
				var currentLength = this.messages.length;
				let promise = this.imService.loadPrivateHistoryMessage(this.friend.uuid, lastMessageTimeStamp);
				promise.then(messages => {
					if (messages.length == currentLength) {
						this.allHistoryLoaded = true
					}
					this.messages = messages;
					uni.stopPullDownRefresh();
				}).catch(e => {
					console.log(e)
					uni.stopPullDownRefresh();
				})
				console.log(this.messages)
			},
		}
	};
</script>

<style lang="scss">
	page {
		padding-bottom: 100rpx;
	}

	.time-lag {
		font-size: 20rpx;
		text-align: center;
	}

	.record-loading {
		position: fixed;
		top: 50%;
		left: 50%;
		width: 300rpx;
		height: 300rpx;
		margin: -150rpx -150rpx;
		background: #262628;
		background: url("https://zhengda.oss-cn-chengdu.aliyuncs.com/baoma/static/recording-loading.gif") no-repeat center;
		background-size: 100%;
		border-radius: 40rpx;
	}

	// 顶部患者详情小图标
	.top_details {
		height: 50rpx;
		width: 100rpx;
		margin: 0 -50rpx;
		position: fixed;
		left: 50%;
		top: -20rpx;
		border: 1rpx solid #E4E4E4;
		border-radius: 20rpx;
		box-shadow: 0px 0px 0.5px #bfbfbf;
		display: flex;
		justify-content: center;
		align-items: flex-end;
	}

	.bot_details {
		height: 50rpx;
		width: 100rpx;
		margin: 0 -50rpx;
		position: relative;
		left: 50%;
		border-radius: 20rpx;
		display: flex;
		justify-content: center;
		align-items: flex-end;
		z-index: 99;
	}

	.details {
		margin: 20rpx 28rpx;
		font-size: 30rpx;

		view {
			margin-bottom: 20rpx;

			text {
				margin-left: 20rpx;
				font-weight: bold;
			}
		}

	}
</style>
