<template>
	<view>
		<!--prescription/inquiry/index.wxml-->
		<scroll-view :scroll-into-view="toView" :style="'height: ' + scroll_height + 'px;'" upper-threshold="100"
			scroll-y="true" enable-back-to-top="true" class="message-list">
			<!-- 每一行 -->
			<view v-for="(item, index) in messages" :key="index" class="row" :id="'row_' + index">
				<!-- 日期 -->
				<!-- <view class="datetime" wx:if="{{item.msgTime != ''}}">{{item.msgTime}}</view> -->
				<!-- 头像与内容文本 -->
				<view class="body" :style="'flex-flow: ' + (item.flow == 'in' ? 'row' : 'row-reverse')">
					<view class="avatar-container">
						<image v-if="item.flow=='in'" class="avatar"
							:src="friendAvatarUrl?friendAvatarUrl:'/prescription/image/ys.png'"></image>
						<image v-else class="avatar" :src="userData.avatar"></image>
					</view>
					<!-- 画对话框 -->
					<!-- <view class="triangle" style="{{item.flow == 'out' ? 'right: 60px; background: #7ECB4B' : 'left: 60px;'}}">
      </view> -->
					<view :class="item.flow == 'out' ? 'content' : 'contentl'"
						:style="item.flow == 'out' ? 'background: #7ECB4B' : ''">
						<view v-if="item.type === 'TIMTextElem'">{{item.payload.text}}</view>
						<image class="image-message" v-else-if="item.type === 'TIMImageElem'"
							:src="item.payload.imageInfoArray[1].url" @tap="previewImage"
							:data-src="item.payload.imageInfoArray[1].url"></image>
						<view v-else-if="item.type === 'TIMSoundElem'" :url="item.payload.url">
							<view class="box" @tap="openAudio" :data-eventid="'13_'+index"
								:data-time="item.payload.second" :data-comkey="item.payload.url">
								<image :src="'13_'+index==audioIndex?audioGif:audioPng" style="height:22px;width:22px"
									class="_image">
								</image>
								<!-- <view style="padding-left: 4px;" class="_div data-v-afeb3abc">
              {{item.payload.second<1?1:item.payload.second}}s
            </view> -->
							</view>
						</view>
					</view>
				</view>
			</view>
			<view class="placeholder-view" :style="'height:' + (bottomBlankHeight + bottomShow?170:58) + 'rpx'"></view>
			<!-- <view class="placeholder-view" style="height:{{bottomBlankHeight + num>1?230:120}}rpx" wx:if="{{bottomShow}}"></view> -->
		</scroll-view>
		<view class="reply" :style="'bottom:' + reply_height + 'px;'">
			<view class="top" v-if="num>1" :style="'bottom:' + (reply_height+55) + 'px;'">
				<text class="num">对不起，医生忙不过来，您前面还有 <text class="sum">{{num}}</text> 人在排队中！</text>
			</view>
			<view class="top" v-else :style="'bottom:' + (reply_height+55) + 'px;'">
				<text class="num">医生正在开方中，请耐心等待...</text>
			</view>
			<!-- <view class="Audio">
    <image wx:if="{{opration==true}}" bindtap="Audio" src="../image/Audio.png"></image>
    <image wx:else bindtap="keyboard" src="../image/keyboard.png"></image>
  </view> -->
			<view class="opration-area">
				<input :adjust-position="false" @focus="bindfocus" @blur="blur" @confirm="sendMsg" v-if="opration==true"
					type="text" @input="getContent" :value="content"></input>
				<!-- <view wx:else class="voice-button {{touchBtn?'hoverBtn':''}}" bind:touchstart="startAudio"
      bind:touchend="onTouchEnd" bind:longpress="onLongpress" bind:touchmove="onTouchMove"  >
      {{touchBtn?'松开 结束':'按住说话'}}
    </view> -->
			</view>
			<view :class="sendBtn==true?'send':'sendActive'" @tap="sendMsg">发送</view>
			<!-- <view class="add" bind:tap="moreClick">
    <image class="more" src="../image/more.png"></image>
  </view> -->
			<!-- <view class="send" bindtap="sendImg">相册</view>
  <view class="send" bindtap="startAudio">开始</view>
  <view class="send" bindtap="endAudio">结束</view> -->
		</view>
		<!-- <view class="more_box" hidden="{{moreShow}}">
  <view class="more_item" bindtap="sendImg">
    <view class="img_box">
      <image src="../image/picture.png"></image>
    </view>
    <view style="margin-top:10rpx;">
      <text>相册</text>
    </view>
  </view>
</view> -->
	</view>
</template>

<script>
	const TIM = require("../imjs/tim-wx-sdk.js");
	const COS = require("../imjs/cos-wx-sdk-v5");
	const req = require("../../utils/request.js");
	var windowWidth = uni.getSystemInfoSync().windowWidth;
	var windowHeight = uni.getSystemInfoSync().windowHeight;
	var keyHeight = 0;
	var numberTime;
	var orderTime;
	let tim;
	const app = getApp();
	let recorderManager = uni.getRecorderManager(); // 录音部分参数 小程序文档
	// 录音部分参数 小程序文档
	const recordOptions = {
		duration: 60000,
		// 录音的时长，单位 ms，最大值 600000（10 分钟）
		sampleRate: 44100,
		// 采样率
		numberOfChannels: 1,
		// 录音通道数
		encodeBitRate: 192000,
		// 编码码率
		format: 'aac' // 音频格式，选择此格式创建的音频消息，可以在即时通信 IM 全平台（Android、iOS、微信小程序和Web）互通

	};
	/**
	 * 处理历史消息 
	 */
	function handlerHistoryMsgs(result, that) {
		// console.log(result, that.messages);
		var historyMsgs = that.messages;
		result.forEach(item => {
			// console.log(item);

			if (item.payload.text == "__end__") {
				item.payload.text = "医生端结束在线问诊！";
			}

			historyMsgs.push(item);
		}); // historyMsgs.push(result[0])

		that.setData({
			messages: historyMsgs
		}); // 将某会话下所有未读消息已读上报

		let promise = tim.setMessageRead({
			conversationID: that.conversationID
		});
		promise.then(function(imResponse) { // 已读上报成功
		}).catch(function(imError) { // 已读上报失败
		});
	}

	export default {
		data() {
			return {
				bottomBlankHeight: app.globalData.isIPhoneX ? 68 : 0,
				friendId: '',
				friendName: '',
				friendAvatarUrl: '',
				messages: [],
				// 消息集合
				complete: 0,
				// 是否还有历史消息可以拉取，1 - 表示没有，0 - 表示有
				content: '',
				// 输入框的文本值
				lock: false,
				// 发送消息锁 true - 加锁状态 false - 解锁状态
				scroll_height: uni.getSystemInfoSync().windowHeight - 54,
				reply_height: 0,
				moreShow: true,
				userData: [],
				audioPng: "/prescription/static/prescription/image/audio-play.png",
				audioGif: "/prescription/static/prescription/image/audio-play.gif",
				audioState: true,

				/**
				 * 历史消息消息集合（结构如下）：
				 * nextReqMessageID 用于续拉，分页续拉时需传入该字段。
				 * isCompleted 表示是否已经拉完所有消息。
				 */
				nextReqMessageID: "",
				isCompleted: "",
				isFirstGetList: true,
				audioContext: null,
				opration: true,
				touchBtn: false,
				recording: false,
				stopflag: false,
				cancelRecord: false,
				refreshTime: '',
				ScrollLoading: 0,
				audioIndex: null,
				sendBtn: true,
				conversationID: "",
				num: "",
				toView: "",
				stopFlag: false,
				bottomShow: false,
				titleShow: false,
				orderDetail: {},
				end: false,
				config: ''
			};
		},

		components: {},
		props: {},
		onLoad: function(options) {
			var that = this;
			that.product = true;
			that.config = JSON.parse(req.getStorage('configRes'));
			uni.hideNavigationBarLoading();
			// console.log(options);
			let opt = {
				SDKAppID: options.sdkAppID // 接入时需要将0替换为您的即时通信 IM 应用的 SDKAppID

			}; // 创建 SDK 实例，`TIM.create()`方法对于同一个 `SDKAppID` 只会返回同一份实例

			tim = TIM.create(opt); // SDK 实例通常用 tim 表示
			// 设置 SDK 日志输出级别，详细分级请参见 setLogLevel 接口的说明

			tim.setLogLevel(1); // 普通级别，日志量较多，接入时建议使用
			// tim.setLogLevel(1); // release 级别，SDK 输出关键信息，生产环境时建议使用
			// 注册 COS SDK 插件

			tim.registerPlugin({
				'cos-wx-sdk': COS
			});
			this.query = options;
			that.messages = []; // 清空历史消息
			// tim.on(TIM.EVENT.SDK_READY,this.getMessageList)

			if (options.msg) {
				let msg = JSON.parse(options.msg);
				msg = msg.map(it => {
					it.payload = {
						text: it.msg
					}; //  it.concat(...it[index],payload:{text:1})

					// console.log(it);
					return it;
				});
				this.setData({
					messages: msg
				});
				// console.log(options.msg.replace(/msg/g, 'payload'), JSON.parse(options.msg), msg);
			}
			this.getNumber();
			this.setData({
				friendId: JSON.parse(options.doctor).uuid,
				friendName: JSON.parse(options.doctor).name,
				friendAvatarUrl: JSON.parse(options.doctor).img,
				conversationID: 'C2C' + options.comunicationid
			});
			uni.setNavigationBarTitle({
				title: JSON.parse(options.doctor).name + '医生在线问诊'
			});
			var userData = req.getStorage('userInfo');
			let audioContext = uni.createInnerAudioContext();
			this.setData({
				userData,
				audioContext
			});

			// 将某会话下所有未读消息已读上报

			let promise = function(event) {
				tim.setMessageRead({
					conversationID: options.comunicationid
				});
				promise.then(function(imResponse) { // 已读上报成功
				}).catch(function(imError) { // 已读上报失败
				});
			};

			// console.log("=========================");
			this.out()

			let newlist = function() {
				setTimeout(function() {
					promise;
				}, 1000);
			};

			tim.on(TIM.EVENT.SDK_READY, newlist);
			let login = tim.login({
				userID: this.query.identifier,
				userSig: this.query.userSig
			});
			login.then(function(imResponse) {
				// console.log("login"); // 登录成功
				// console.log(imResponse); // 登录成功
				// console.log(imResponse.data.repeatLogin, "重复登录");
				if (imResponse.data.repeatLogin === true) {
					let promise = tim.logout();
					promise.then(function(imResponse) {
						// console.log(imResponse.data, "============"); // 登出成功
					}).catch(function(imError) {
						// console.warn('logout error:', imError);
					});
					let login = tim.login({
						userID: this.query.identifier,
						userSig: this.query.userSig
					}); // 标识账号已登录，本次登录操作为重复登录。v2.5.1 起支持

					// console.log(imResponse.data.errorInfo);
				}

				let time = function() {
					setTimeout(function() {
						that.sendMsg("__refresh__");
					}, 1000);
				};

				tim.on(TIM.EVENT.SDK_READY, time);
			}).catch(function(imError) {
				uni.showModal({
					title: '提示',
					cancelText: '返回首页',
					confirmText: '查看订单',
					content: '与医生对话连接失败，不影响开方，请关注订单状态',

					success(res) {
						if (res.confirm) {
							// console.log('用户点击确认');
							app.globalData.redirectTab("mine/orderDet/orderDet?id=" + that.query
								.orderId);
							that.out()
						} else if (res.cancel) {
							// app.globalData.reLaunchTo('pages/index/index')
							// console.log('用户点击取消');
							that.out();
							that.goHome();
						}
					}

				});
				console.warn('login error:', imError, "与医生对话连接失败，不影响开方，请关注订单状态"); // 登录失败的相关信息
			});
		},
		onShow: function() {
			let that = this; // 开始登录
			that.scrollToBottom();
			orderTime = setInterval(() => {
				this.getOrder();
			}, 3000);
			numberTime = setInterval(() => {
				this.getNumber();
			}, 3000);
			let onMessageReceived = function(event) {
				// event.data - 存储 Message 对象的数组 - [Message]
				let msgList = that.messages;
				// console.log("====================================", that.product, event.data[0].payload.text ==
				// 	"__end__", !that.end, that.orderDetail.id, that.orderDetail.state, that.query.orderId);
				// console.log(that.orderDetail,event,that)
				if ((event.data[0].payload.text == "__end__" && !that.end && that.product) || (that.orderDetail
						.state != 21 && that.query.orderId)) {
					let content
					if (that.orderDetail.state == '22') {
						content = '因' + that.orderDetail.orderDrugUser.reasons + '，开方失败，请重新开方'
					} else if (that.orderDetail.state != '21') {
						content = '您的订单开方成功！'
					} else {
						content = '医生在线问诊结束，处方稍后就会开出来，请关注您的订单！'
					}
					uni.showModal({
						title: '提示',
						cancelText: '返回首页',
						confirmText: '查看订单',
						content: content,
						success(res) {
							if (res.confirm) {
								// console.log('用户点击确认', that.query
								// 	.orderId);
								app.globalData.redirectTab("mine/orderDet/orderDet?id=" + that.query
									.orderId);
								that.out()
								clearInterval(orderTime);
							} else if (res.cancel) {
								// console.log('用户点击取消');
								that.out()
								that.goHome();
								clearInterval(orderTime);
							}
						}
					});
					that.end = true;
				} else {
					that.end = false
					handlerHistoryMsgs(event.data, that);
				}

				that.scrollToBottom();
			};

			tim.on(TIM.EVENT.MESSAGE_RECEIVED, onMessageReceived); // 获取当前聊天的历史列表

			let mestime = function() {
				setTimeout(function() {
					that.getMessageList();
				}, 1000);
			};

			tim.on(TIM.EVENT.SDK_READY, mestime); // 监听录音结束

			recorderManager.onStop(function(res) {
				if (that.recording) {
					if (that.cancelRecord) {
						uni.hideToast();
						that.setData({
							cancelRecord: false
						});
					} else {
						// 创建消息实例，接口返回的实例可以上屏
						const message = tim.createAudioMessage({
							to: that.friendId,
							conversationType: TIM.TYPES.CONV_C2C,
							payload: {
								file: res
							},
							onProgress: function(event) {}
						}); //  发送消息

						let promise = tim.sendMessage(message);
						promise.then(function(imResponse) {
							// 发送成功
							that.addMessage(imResponse.data.message, that);
						}).catch(function(imError) { // 发送失败
						});
						that.setData({
							recording: false
						});
					}
				} else {
					uni.showToast({
						title: '说话时间太短',
						duration: 1000,
						image: "/prescription/static/prescription/image/err.png"
					});
				}
			});
		},
		onHide() {
			clearInterval(orderTime);
		},

		onUnload() {
			// console.log("123456", this.query.orderId, this.orderDetail)
			this.orderDetail = {}
			delete this.query.orderId
			// console.log(this.orderDetail)
			this.product = false;
			// console.log(orderTime, "789")
			clearInterval(orderTime);
			// console.log(orderTime, "555")
		},

		methods: {
			// 登出
			out() {
				let out = tim.logout();
				out.then(function(imResponse) {
					// console.log(imResponse.data, "======登出成功======"); // 登出成功
				}).catch(function(imError) {
					// console.warn('logout error:', imError);
				});
			},
			
			goHome(){
				app.globalData.openHome();
			},
			// 获取订单状态
			getOrder() {
				// console.log(this.query.orderId)
				if (!this.query.orderId) {} else {
					if (!this.orderDetail.id || this.orderDetail.state == 21) {
						req.getRequest('/api/order/detail', {
							id: this.query.orderId
						}, data => {
							this.orderDetail = data
							// console.log(this.orderDetail, data.id)
						}, true)
					} else if (this.orderDetail.state != 21) {
						// console.log(this.orderDetail, this.orderDetail.id, "清除定时器")
						clearInterval(orderTime);
					}
				}

			},
			// 获取排队人数
			getNumber() {
				if (this.num - 1 <= 0) {
					clearInterval(numberTime);
				} else {
					req.getRequest('/api/userDrugPeople/getNumber', {
						doctorId: JSON.parse(this.query.doctor).id
					}, data => {
						// console.log(data)
						this.setData({
							num: data
						});
					}, true);
				}
			},

			/**
			 * 获取消息列表
			 */
			getMessageList() {
				let that = this;
				// console.log(that.conversationID);
				let cb = tim.getMessageList({
					conversationID: that.conversationID,
					//会话列表传递过来的参数
					count: 15
				});
				cb.then(function(imResponse) {
					const messageList = imResponse.data.messageList; // 消息列表。

					const nextReqMessageID = imResponse.data.nextReqMessageID; // 用于续拉，分页续拉时需传入该字段。

					const isCompleted = imResponse.data.isCompleted; // 表示是否已经拉完所有消息。

					that.setData({
						nextReqMessageID: nextReqMessageID,
						isCompleted: isCompleted
					});
					handlerHistoryMsgs(messageList, that);
					that.scrollToBottom();
				});
			},

			/**
			 * 获取文本的消息
			 */
			getContent: function(e) {
				if (e.detail.value == "") {
					this.setData({
						sendBtn: true
					});
				} else {
					this.setData({
						sendBtn: false
					});
				}

				// console.log(e);
				var that = this;
				that.setData({
					content: e.detail.value
				});
			},

			/**
			 * 发送消息
			 */
			sendMsg(content) {
				// console.log(content, typeof content);

				if (this.content == "" && typeof content != "string") {
					uni.showToast({
						title: '请输入内容',
						duration: 1000,
						icon: 'none'
					});
					return;
				}

				var that = this;
				// console.log(typeof this.content); // 发送文本消息，Web 端与小程序端相同
				// 1. 创建消息实例，接口返回的实例可以上屏

				let message = tim.createTextMessage({
					to: this.friendId,
					conversationType: TIM.TYPES.CONV_C2C,
					type: TIM.TYPES.MSG_CUSTOM,
					payload: {
						text: typeof content == 'string' ? content : this.content
					}
				});

				message._elements.push({
					content: {
						text: this.query.comunicationid
					},
					type: "TIMTextElem"
				});

				// console.log(message); // message.Elem.Text(this.data.conversationID)
				// 2. 发送消息

				let promise = tim.sendMessage(message);
				promise.then(function(imResponse) {
					// 发送成功
					// console.log(imResponse, imResponse.data.message.payload.text);

					if (content !== '__refresh__') {
						that.addMessage(imResponse.data.message, that);
						that.setCommunication(imResponse.data.message.payload.text);
					}
					that.titleShow = true
					that.setData({
						sendBtn: true
					});
				}).catch(function(imError) { // 发送失败
				});
			},

			/**
			 * 刷新文本消息
			 */
			addMessage: function(msg, that) {
				var messages = that.messages;
				// console.log(msg);
				messages.push(msg);
				that.setData({
					messages: messages,
					content: '' // 清空输入框文本

				});
				that.scrollToBottom();
			},

			/**
			 * 发送图片消息
			 */
			sendImg() {
				let that = this;
				uni.chooseImage({
					sourceType: ['album'],
					// 从相册选择
					count: 1,
					// 只选一张，目前 SDK 不支持一次发送多张图片
					success: function(res) {
						// 2. 创建消息实例，接口返回的实例可以上屏
						let message = tim.createImageMessage({
							to: that.friendId,
							conversationType: TIM.TYPES.CONV_C2C,
							payload: {
								file: res
							},
							onProgress: function(event) {}
						}); // 3. 发送图片

						let promise = tim.sendMessage(message);
						promise.then(function(imResponse) {
							// 发送成功
							that.addMessage(imResponse.data.message, that);
						}).catch(function(imError) { // 发送失败
						});
					}
				});
			},

			scrollToBottom: function() {
				this.setData({
					toView: 'row_' + (this.messages.length - 1)
				});
			},

			previewImage(e) {
				let src = '';
				uni.previewImage({
					current: e.currentTarget.dataset.src,
					// 当前显示图片的http链接
					urls: [e.currentTarget.dataset.src]
				});
			},

			// 保存聊天记录
			setCommunication(content) {
				let from = {
					communicationId: this.query.comunicationid,
					content: content,
					orderId: this.query.orderId
				};
				req.postRequest('/api/userDrugPeople/setCommunication', from, data => {
					// console.log(data);
				});
			},

			// 录制语音
			startAudio: function() {
				uni.showToast({
					title: '上滑取消发送',
					duration: 10000,
					image: "/prescription/static/prescription/image/cancel.png"
				});
				this.setData({
					touchBtn: true
				});

				if (this.stopFlag) {
					return;
				}

				recorderManager.start(recordOptions);
				recorderManager.onError(function(errMsg) {});
			},

			// # 利用长按判断录音是否太短
			onLongpress() {
				this.setData({
					recording: true
				});
			},

			// 发送录音
			onTouchEnd: function() {
				uni.hideToast();
				let that = this;
				that.setData({
					touchBtn: false
				});

				if (that.stopFlag) {
					return;
				}

				if (that.recording) {
					recorderManager.stop();
				} else {
					that.setData({
						stopFlag: true
					});
					setTimeout(() => {
						recorderManager.stop();
						that.setData({
							stopFlag: false
						});
					}, 400);
				}
			},

			// 播放语音
			openAudio(audio) {
				// console.log(audio);
				let index = audio.currentTarget.dataset.eventid;
				this.setData({
					audioIndex: index // audioState:false

				});
				this.audioContext.src = audio.currentTarget.dataset.comkey;
				this.audioContext.autoplay = true;
				this.audioContext.play();
				this.audioContext.onPlay(res => {});
				this.audioContext.onEnded(() => {
					uni.hideToast();
					this.setData({
						audioIndex: null
					});
					// console.log("语音结束了");
				});
				this.audioContext.onError(res => {});
			},

			// 上滑取消
			onTouchMove(e) {
				if (e.touches[0].clientY < 520) {
					// # 取消发送
					this.setData({
						cancelRecord: true
					});
					uni.showToast({
						title: '松开，取消发送',
						duration: 10000,
						image: "/prescription/static/prescription/image/cancel.png"
					});
				} else {
					// # 不取消
					uni.hideToast();
					uni.showToast({
						title: '上滑取消发送',
						duration: 10000,
						image: "/prescription/static/prescription/image/cancel.png"
					});
					this.setData({
						cancelRecord: false
					});
				}
			},

			// 下拉加载聊天记录
			refresh: function(e) {
				let that = this;

				if (that.ScrollLoading == 1) {
					//防止多次触发
					return false;
				}

				if (e.detail.scrollTop < 1) {
					that.setData({
						ScrollLoading: 1
					});
					uni.showLoading({
						title: '加载中'
					});
					setTimeout(() => {
						let promise = tim.getMessageList({
							conversationID: that.conversationID,
							nextReqMessageID: that.nextReqMessageID,
							count: 15
						});
						promise.then(function(imResponse) {
							const newMessageList = imResponse.data.messageList; // 消息列表。

							const nextReqMessageID = imResponse.data
								.nextReqMessageID; // 用于续拉，分页续拉时需传入该字段。

							const isCompleted = imResponse.data.isCompleted; // 表示是否已经拉完所有消息。

							that.setData({
								nextReqMessageID: nextReqMessageID,
								isCompleted: isCompleted,
								messages: newMessageList.concat(that.messages)
							});
							uni.hideLoading();
							that.setData({
								ScrollLoading: 0
							}); // handlerHistoryMsgs(messageList, that);
						});
					}, 800);
				} // setTimeout(function(){
				//   var date = new Date();
				// },300);

			},

			// 切换
			Audio() {
				this.setData({
					opration: false
				});
			},

			keyboard() {
				this.setData({
					opration: true
				});
			},

			moreClick() {
				if (this.moreShow) {
					this.setData({
						moreShow: false,
						reply_height: 92,
						scroll_height: this.scroll_height - 92
					});
				}
			},

			//失去聚焦(软键盘消失)
			blur: function(e) {
				this.setData({
					scroll_height: uni.getSystemInfoSync().windowHeight - 54,
					reply_height: 0,
					bottomShow: false
				});
				this.setData({
					toView: 'row_' + (this.messages.length - 1)
				});
				// console.log(this.messages);
			},
			//   /**
			//  * 获取聚焦
			//  */
			bindfocus: function(e) {
				// console.log(e)
				keyHeight = e.detail.height;
				this.setData({
					scroll_height: windowHeight - keyHeight
				});
				this.setData({
					toView: 'row_' + (this.messages.length - 1),
					reply_height: keyHeight,
					moreShow: true,
					bottomShow: true // reply_height: 0,

				});
				// console.log(windowHeight - keyHeight, keyHeight, this.toView)
			} // bindfocus(e) {
			//   keyHeight = e.detail.height;
			//   this.setData({
			//     moreShow: true,
			//     reply_height: 0,
			//     scroll_height: (wx.getSystemInfoSync().windowHeight -  keyHeight) +'px'
			//   })
			// }

		}
	};
</script>
<style>
	@import "./index.css";
</style>
