<template>
	<view class="chatroom" :style="'padding-top: '+ (keyboardHeight ? keyboardHeight + 24 + 'rpx' : 0) +'; padding-bottom: '+ (doctorData && doctorData.mark === 'Y' ? (newMessage ? '168rpx' : '120rpx') : '208rpx')">
		<!-- chats -->
		<nav-bar 
			:navbar-data="navbarData" 
			@handleSend="handleSend($event, { tagId: 'nav-bar' })"
			@handleMessageReceived="handleMessageReceived($event, { tagId: 'nav-bar' })" 
			id="nav-bar"
			ref="nav-bar"
		></nav-bar>
		<view class="header" v-if="!hideHeader">
			<view>下拉刷新中……</view>
		</view>
		<scroll-view 
			id="body"
			class="body"
			:scroll-y="true"
			:scroll-into-view="scrollPosition"
			:scroll-with-animation="true"
			@scrolltoupper="onScrollToUpper"
			@scrolltolower="handleScrolltolower"
			@scroll="handleScroll"
		>
			<view id="viewHight">
				<view v-if="symptom ? true : false" class="col-4">
					<view class="col-4-content">
						<view class="col-4-text ellipsis">【咨询内容】 {{ symptom }}</view>
						<view class="col-4-btn" @tap="getConsultationDetail">查看详情 >></view>
					</view>
				</view>
				<view class="system-alert">
					{{
                        doctorData.toUser === 'userKF001'
                            ? '请将您遇到的问题发送给我们，我们将在第一时间为您解决。'
                            : '系统提示：本次咨询自医生接诊起有效期为24小时，有效期内您可以对咨询内容进行追问。若医生未接诊，您可以随时申请取消订单。医生超过24小时未接诊，系统将自动取消订单。'
                    }}
				</view>
				<view 
					:id="'message'+ item.msgID" 
					:class="
                        item.msgType == '1' && item.direction == 'right'
                            ? 'mw-content mw-content-right mw-message'
                            : item.msgType == '1' && item.direction == 'left'
                            ? 'mw-content mw-message'
                            : 'mw-message mw-content-content'
					"
					v-for="(item, index) in chats" 
					:key="index"
				>
					<view class="col-1" :style="
                            'display: ' +
                            (item.msgType === '1' ? 'block' : 'none') +
                            '; background: url(' +
                            (item.direction === 'left' ? (doctorData && doctorData.toUser === 'userKF001' ? kefuLogo : doctorData.docImg) : doctorData.patImg) +
                            ') no-repeat;background-size: 100% auto;'
                        ">
						<!-- {{item.direction === "left" ? (doctorData.toUserName || "他") : (userData.patDesc || "我")}} -->
					</view>

					<view class="col-2" :style="'display: ' + (item.msgType === '1' ? 'block' : 'none')">
						<view :class="
                                item.direction === 'left' && item.picture
                                    ? 'message-content message-received background-color-fff'
                                    : item.direction === 'right' && (item.picture || item.pictureLoading)
                                    ? 'message-content message-send background-color-fff'
                                    : item.direction === 'left'
                                    ? 'message-content message-received'
                                    : 'message-content message-send'
                            ">
							<text v-if="item.consultText ? true : false">{{ item.consultText }}</text>
							<image 
								@tap.stop.prevent="viewOriginal" 
								:data-page="item" class="image" 
								:src="item.picture"
								alt="" v-if="item.picture ? true : false" 
								mode="widthFix"
							/>
							<view v-if="item.pictureLoading" class="image img-loading">
								<van-loading size="24px" type="spinner" vertical>图片加载中...</van-loading>
							</view>
						</view>
					</view>

					<view class="col-3" :style="'display: ' + (item.msgType === '2' || item.msgType === '3' ? 'block' : 'none')">
						<view v-if="item.msgType === '2' ? true : false">
							{{ item.direction === 'left' ? '对方撤回了一条消息' : '你撤回了一条消息' }}
							<text class="re-edit" :style="'display: ' + (item.direction === 'right' && item.isModity ? 'inline-block' : 'none')">重新编辑</text>
						</view>
						<text v-if="item.msgType === '3' ? true : false">{{ item.sendTime }}</text>
					</view>
				</view>
			</view>
		</scroll-view>

		<!-- message sender -->
		<view
			v-if="doctorData && doctorData.mark === 'Y' ? true : false" 
			class="footer"
			:style="'min-height: ' + (newMessage ? '168rpx' : '120rpx')"
		>
			<view class="new-message-alert" v-if="newMessage ? true : false" @tap="handleNewMessage">{{ newMessage }}</view>
			<view class="footer-content">
				<input 
					class="text-input" 
					type="text" 
					maxlength="-1" 
					confirm-type="send" 
					cursor-spacing="10"
					:value="textInputValue"
					:hold-keyboard="true"
					@input="getTextInputVal"
					@focus="fieldFocus"
					@blur="fieldBlur" 
				/>
				<i class="iconfont icon-tupian" @tap="onChooseImage"></i>
				<van-button
					type="primary"
					class="send-btn"
					:loading="btnLoading"
					@tap.native="handleSend"
				>发送</van-button>
			</view>
		</view>
		<view v-if="doctorData && doctorData.type" class="footer footer-system-alert" style="height: 208rpx">
			<view class="footer-system-alert-title">
				<text v-if="doctorData.type === '03'">咨询/问诊已取消</text>
				<text v-if="doctorData.type === '04'">医生已取消您的咨询/问诊</text>
				<text v-if="doctorData.type === '05'">咨询/问诊已过时</text>
			</view>
			<view class="footer-system-alert-btn">
				<van-button @tap.native="handleGoHome">{{ doctorData && doctorData.appraiseMark === 'Y' ? '评价' : '返回首页' }}</van-button>
				<van-button @tap.native="handleGoMyConsultation" type="info">再次预约</van-button>
			</view>
		</view>
		<van-popup :show="visible" type="center" @close="onClickHide">
			<view class="original-img" :style="'margin-top: '+ navHeight +'px; height: calc(100vh - '+ navHeight +'px)'">
				<image :src="originalImg" mode="widthFix" :style="'max-height: calc(100vh - ' + navHeight + 'px)'" />
			</view>
		</van-popup>
	</view>
</template>

<script>
	import NavBar from '@/components/navbar/index';
	import VanPopup from '@/components/popup/index';
	// #ifdef H5
	import TIM from 'tim-js-sdk';
	// #endif
	// #ifdef MP-WEIXIN
	import TIM from 'tim-wx-sdk';
	// #endif
	import GenerateTestUserSig from '@/debug/GenerateTestUserSig';
	import $http from '@/utils/https';
	import httpConfig from '@/utils/httpConfig';
	import Utils from '@/utils/utils';
	const app = getApp();
	export default {
		components: {
			NavBar,
			VanPopup
		},
		data() {
			return {
				option: {},
				userData: this.$cache.get('userData'),
				imgHost: httpConfig && httpConfig.imgHost ? httpConfig.imgHost : '',
				windowHost: httpConfig && httpConfig.ipDeault ? httpConfig.ipDeault : '',
				chats: [],
				textInputValue: '',
				scrollTop: 0,
				scrollPosition: '',
				isScroll: false,
				moreMsgFlag: 'Y',
				hideHeader: true,
				lastMsgID: '',
				doctorData: {
					mark: '',
					toUser: '',
					docImg: '',
					patImg: '',
					type: '',
					appraiseMark: ''
				},
				isKickedOut: true,
				newMessage: '',
				scrollHeight: 0,
				navHeight: app.globalData.navHeight,
				spaceHeight: app.globalData.spaceHeight,
				navTitleHeight: app.globalData.navTitleHeight,
				statusBarHeight: app.globalData.statusBarHeight,
				navbarData: {
					isGoHome: true,
					isGoBack: true,
					title: 'none',
					isMonitorNewMessage: 'im'
				},
				visible: false,
				originalImg: '',
				genderMale: httpConfig.imgHost + '/images/icon/gender-male.png',
				// 男
				genderFemale: httpConfig.imgHost + '/images/icon/gender-female.png',
				// 女
				unknownGender: httpConfig.imgHost + '/images/icon/unknown-gender.png',
				// 未知性别
				keyboardHeight: 0,
				btnLoading: false,
				kefuLogo: httpConfig.imgHost + '/images/icon/kefu-logo.png',
				symptom: ''
			};
		},
		onLoad: function(option) {
			let title = option && option.toUserName ? option.toUserName : '图文咨询';
			uni.setNavigationBarTitle({
				title: title
			});
			let {
				imgHost,
				userData,
				genderMale,
				genderFemale,
				unknownGender
			} = this;
			option.patImg = userData && userData.patSexDesc === '男' ? genderMale : userData.patSexDesc === '女' ?
				genderFemale : unknownGender;
			option.docImg =
				option.docImg && option.docImg !== 'undefined' ?
				option.docImg.indexOf('http') !== -1 ?
				option.docImg : this.windowHost + option.docImg : imgHost + '/images/icon/avatar_doctor_act.png';
			if (option && option.toUser === 'userKF001') {
				option.mark = 'Y';
				this.setData({
					doctorData: option
				},() => {
					this.getChatData('bottom'); // 获取消息
				});
			} else {
				this.option = option;
				this.getMarkStatus(option);
			}
		},
		/**
		 * 生命周期函数--监听页面显示
		 */
		onShow: function() {
			let pages = getCurrentPages();
			let currentPage = pages[pages.length - 1];
			console.log('当前页面====', currentPage)
			let homeMsgData = this.$cache.get('homeMsgData');
			let mesIndex = '';
			if (homeMsgData && homeMsgData.length > 0) {
				homeMsgData.forEach(function(item, index) {
					if (item && (item.type === 'M' || item.type === 'H') && item.timetamp == currentPage
						.options) {
						mesIndex = index;
					}
				});
			}
			if (mesIndex != '') {
				homeMsgData.remove(mesIndex);
				this.$cache.set('homeMsgData', homeMsgData);
			}
		},
		onHide: function() {
			// console.log("onHide函数触发了")
			// 在组件实例被从页面节点树移除时执行
			// this.modifyMessageStatus();
			// this.signOut();
		},
		onUnload: function() {
			// console.log("onUnload函数触发了")
			// 在组件实例被从页面节点树移除时执行
			this.modifyMessageStatus();
			// this.signOut();
		},
		methods: {
			// 查询患者是否有就诊权限
			getMarkStatus(option) {
				let data = {
					params: [{
						admID: option.admID || ''
					}]
				};
				$http.post('urlS', this, {
					code: '03100108',
					data: data,
					namespace: 'Y',
					success: function(res) {
						// type  04 -- 医生已经拒绝；05 -- 咨询时间已经过了
						if (+res.errorCode === 0) {
							option.mark = res.mark;
							option.type = res.type;
							option.appraiseMark = res.appraiseMark;
							option.locID = res.locID;
						} else {
							option.mark = 'N';
						}
						this.setData({
								doctorData: option
							},
							() => {
								// if (this.data.doctorData && this.data.doctorData.type) {
								//   let dTitle = this.data.doctorData.type === "04" ? "（已拒绝）" : (this.data.doctorData.type === "05" ? "（已过时）" : "（已取消）");
								//   title = title + dTitle
								// }
								this.getOneMessage(option);
								this.getChatData('bottom'); // 获取消息
							}
						);
					}
				});
			},

			// 获取就诊详情
			getOneMessage: function(options) {
				console.log(options);
				let admID = options.admID;
				let consultID = options.consultID;
				let consultTypeID = options.consultTypeID;
				let payFlag = options.payFlag;
				var typeCode = [];
				if (payFlag == 1) {
					var typeCode = ['01'];
				} else if (payFlag == 2) {
					var typeCode = ['02'];
				} else if (payFlag == 3) {
					var typeCode = ['05'];
				} else if (payFlag == 4) {
					var typeCode = ['03', '04'];
				} else {
					var typeCode = [];
				}
				let data = {
					params: [{
						patID: this.$cache.get('userData').hisPatID,
						typeCode: typeCode ? typeCode : undefined,
						admID: admID ? admID : undefined,
						consultID: consultID ? consultID : undefined,
						consultTypeID: consultTypeID ? consultTypeID : undefined
					}]
				};
				//获取我的问诊列表
				$http.post('urlS', this, {
					code: '02090009',
					data: data,
					namespace: 'Y',
					success: function(res) {
						if (+res.errorCode === 0) {
							// res.result.rows[0].patSymptomInfo.symptom
							let symptom = res.result.rows && res.result.rows.length > 0 ? res.result.rows[
								0].patSymptomInfo.symptom : '';
							this.setData({
								symptom
							});
						}
					}
				});
			},

			getConsultationDetail: Utils.debounce(function(e) {
				let {
					admID,
					consultID,
					consultTypeID,
					payFlag,
					toUser
				} = this.doctorData;
				console.log(admID, consultID, consultTypeID, payFlag, this.doctorData);
				uni.navigateTo({
					url: '/pages/mine/myConsultation/consultationDetail/consultationDetail?admID=' +
						(admID ? admID : '') +
						'&consultID=' +
						(consultID ? consultID : '') +
						'&consultTypeID=' +
						(consultTypeID ? consultTypeID : '') +
						'&payFlag=' +
						(payFlag ? payFlag : '') +
						'&doctorID=' + 
						(toUser.slice(4)) +
						'&doctorName=' + 
						(this.option.toUserName ? this.option.toUserName : '')

				});
			}),

			// 登录
			login(userID, isSignOut) {
				let {
					doctorData
				} = this;
				console.log('login == ', GenerateTestUserSig)
				let userData = GenerateTestUserSig.genTestUserSig(userID || '');
				let promise = app.globalData.tim.login({
					userID: userID || '',
					userSig: userData && userData.userSig ? userData.userSig : ''
				});
				promise
					.then((imResponse) => {
						console.log('登录成功', userID); // 登录成功
						this.setData({ isKickedOut: true }, () => {
							app.globalData.tim.on(TIM.EVENT.MESSAGE_RECEIVED, this.handleMessageReceived);
							app.globalData.tim.on(TIM.EVENT.KICKED_OUT, this.monitorKickedOut);
						})
						if (isSignOut === 'signOut') {
							setTimeout(() => {
								this.signOut(isSignOut); // 登录成功后退出
							}, 500);
						}
						this.getChatData('bottom'); // 获取消息
					})
					.catch(function(imError) {
						console.warn('登录失败:', imError); // 登录失败的相关信息
					});
			},

			// 监听消息接收
			handleMessageReceived: function(event, _dataset) {
				/* ---处理dataset begin--- */
				this.handleDataset(event, _dataset);
				/* ---处理dataset end--- */
				console.log(event);
				const { data } = event
				let {
					doctorData,
					scrollHeight
				} = this;
				let from = event.data[0].from;
				// console.log("信息消息：", doctorData.toUser, from)
				if (doctorData.toUser === from) {
					let newMessageJSON = data && data.length > 0 ? JSON.parse(data[0].payload.text) : {};
					try {
						const query = uni.createSelectorQuery();
						query.select('#viewHight').boundingClientRect();
						query.selectViewport().scrollOffset();
						query.exec((viewRes) => {
							let viewHeight = viewRes && viewRes[0] && viewRes[0].height ? viewRes[0].height : 0;
							uni.getSystemInfo({
								success: (res) => {
									console.log(newMessageJSON);
									if (newMessageJSON && (newMessageJSON.type === 'M' ||
											newMessageJSON.type === 'H')) {
										if (res.windowHeight < viewHeight + 60) {
											// 存在滚动条
											if (viewHeight - (res.windowHeight - 60 +
												scrollHeight) > this.getLastViewHeight()) {
												this.setData({
													newMessage: newMessageJSON.text
												});
											} else {
												this.getChatData('bottom');
											}
										} else {
											this.getChatData('bottom');
										}
									} else if (newMessageJSON && newMessageJSON.type === 'R') {
										doctorData.type = '04';
										doctorData.mark = 'N';
										doctorData.appraiseMark = 'N';
										console.log(doctorData);
										this.setData({
											doctorData
										});
									}
								}
							});
						});
					} catch (error) {
						console.log('CatchClause', error);
						console.log('CatchClause', error);
						console.log(error);
					}
				}
			},

			// 获取消息列表数据
			getChatData: function(scroll, newMessage) {
				let {
					doctorData,
					lastMsgID
				} = this;
				let data = {
					params: [{
						admID: doctorData.toUser === 'userKF001' ? '' : doctorData.admID,
						frUser: doctorData.userID,
						toUser: doctorData.toUser,
						lastMsgID
					}]
				};
				$http.post('urlS', this, {
					code: '02090005',
					data: data,
					namespace: 'Y',
					success: function(res) {
						// console.log(res)
						if (+res.errorCode === 0) {
							let chatData = res.result && res.result.msgData instanceof Array ? res.result.msgData : [];
							for (var i = 0; i < chatData.length; i++) {
								chatData[i].navBarVisible = false;
								chatData[i].key = i + 1;
							}
							this.setData({
									chats: chatData,
									moreMsgFlag: res.result.moreMsgFlag,
									hideHeader: true,
									newMessage: newMessage ? newMessage : ''
								},
								() => {
									let scrollPosition = '';
									if (scroll === 'bottom') {
										if (!(this.chats && this.chats.length > 0)) {
											return;
										}
										scrollPosition = 'message' + this.chats[this.chats.length - 1].msgID;
									} else if (scroll === 'noBottom') {
										scrollPosition = 'message' + lastMsgID;
									}
									this.setData({
										scrollPosition
									});
								}
							);
						} else {
							this.setData({
								chats: [],
								moreMsgFlag: 'N',
								hideHeader: true,
								newMessage: newMessage ? newMessage : ''
							});
						}
					}
				});
			},

			// 点击消息提示重新查询数据
			handleNewMessage: function() {
				this.setData({
						newMessage: ''
					},
					() => {
						this.getChatData('bottom');
					}
				);
			},

			// 获取当前滚动高度
			handleScroll: function(event) {
				let {
					scrollTop
				} = event.detail;
				this.setData({
					scrollHeight: scrollTop
				});
			},

			// 滚动到底部触发事件
			handleScrolltolower: function() {
				let {
					newMessage
				} = this;
				if (newMessage) {
					this.setData({
							newMessage: ''
						},
						() => {
							this.getChatData('bottom');
						}
					);
				}
			},

			// 获取前十条数据的高度
			getGobackScroll: function() {
				let {
					chats
				} = this;
				let height = 0;
				for (var i = 0; i < 10; i++) {
					if (chats[i].msgType === '1' && chats[i].consultText) {
						height += 43;
					} else if (chats[i].msgType === '1' && chats[i].picture) {
						height += 144;
					} else if (chats[i].msgType === '3' || chats[i].msgType === '2') {
						height += 39;
					}
				}
				return height;
			},

			// 获取最后一条记录的高度
			getLastViewHeight: function() {
				let {
					chats
				} = this;
				let height = 0;
				if (chats[chats.length - 1].msgType === '1' && chats[chats.length - 1].consultText) {
					height = 43;
				} else if (chats[chats.length - 1].msgType === '1' && chats[chats.length - 1].picture) {
					height = 144;
				} else if (chats[chats.length - 1].msgType === '3' || chats[chats.length - 1].msgType === '2') {
					height = 39;
				}
				return height;
			},

			// 获取输入框文本
			getTextInputVal(e) {
				// console.log(e)
				this.setData({
					textInputValue: e.detail.value
				});
			},

			handleSend: Utils.debounce(function() {
				let val = this.textInputValue;
				if (!val) {
					uni.showToast({
					    title: '发送内容不能为空',
					    icon: 'none',
					})
					return;
				}
				console.log(app.globalData)
				if (!app.globalData.isLogOut) {
					// 判断是否离线
					console.log(this.zpSelectComponent('#nav-bar'))
					this.zpSelectComponent('#nav-bar').handleLoginShow();
					return;
				}
				let {
					doctorData,
					btnLoading
				} = this;
				this.setData({
						btnLoading: true
					},
					() => {
						setTimeout(() => {
							if (this.btnLoading) {
								this.setData({
									btnLoading: false
								});
								uni.showToast({
								    title: '网络异常，请稍后再试。',
								    icon: 'none',
								})
							}
						}, 10000);
					}
				);
				if (btnLoading) {
					return;
				}
				this.tryFun(async () => {
					let data = {
						params: [{
							admID: doctorData.admID,
							frUser: doctorData.userID,
							toUser: doctorData.toUser,
							consultText: val,
							picture: ''
						}]
					};
					$http.post('urlS', this, {
						code: '02090004',
						data: data,
						namespace: 'Y',
						success: function(res) {
							console.log(res);
							if (+res.errorCode === 0) {
								let obj = {
									consultText: this.textInputValue,
									direction: 'right',
									msgType: '1',
									isWithdraw: true,
									key: this.chats.length + 1,
									msgID: res.result && res.result.msgID ? res.result
										.msgID : ''
								};
								this.setData({
										textInputValue: '',
										btnLoading: false,
										chats: [
											...this.chats,
											{
												...obj
											}
										]
									},
									() => {
										let scrollPosition = 'message' + this.chats[
											this.chats.length - 1].msgID;
										this.setData({
											scrollPosition
										});
										this.handleSendText();
									}
								);
							} else {
								uni.showToast({
								    title: res.errorMessage,
								    icon: 'none',
								})
								this.setData({
									btnLoading: false
								});
							}
						},
						error: function(error) {
							console.log(error);
							this.setData({
								btnLoading: false
							});
						}
					});
				}, '发送文字失败');
			}),

			// 文字发送
			async handleSendText() {
				let {
					doctorData
				} = this;
				let messageContent = {
					userID: doctorData.toUser && doctorData.toUser === 'userKF001' ? 'KF001' : doctorData.toUser
						.slice(4),
					admID: doctorData.admID || '',
					patID: doctorData.userID ? doctorData.userID : '',
					patName: doctorData.patName || '',
					userName: doctorData.toUserName || '',
					type: doctorData.toUser && doctorData.toUser === 'userKF001' ? 'H' : 'M',
					text: this.textInputValue
				};
				let message = app.globalData.tim.createTextMessage({
					to: doctorData.toUser,
					conversationType: TIM.TYPES.CONV_C2C,
					payload: {
						text: JSON.stringify(messageContent)
					}
				});
				// 2. 发送消息
				let promise = app.globalData.tim.sendMessage(message);
				if (promise) {
					promise
						.then((imResponse) => {
							// 发送成功
							if (imResponse && imResponse.code === 0) {
								console.log('IM发送成功。');
							}
						})
						.catch((imError) => {
							// 发送失败
							uni.showToast({
							    title: '网络异常，请稍后再试。',
							    icon: 'none',
							})
							console.log(imError);
							this.setData({
								btnLoading: false
							});
						});
				} else {
					console.log('网络异常，请稍后再试。');
					this.setData({
						btnLoading: false
					});
				}
			},
			
			// 图片发送
			async onChooseImage(e) {
				let {
					doctorData
				} = this;
				uni.chooseImage({
					count: 1,
					sizeType: ['original', 'compressed'],
					sourceType: ['album', 'camera'],
					success: async (res) => {
						console.log(res);
						// 图片loading
						let len = this.chats && this.chats.length ? this.chats.length : 0;
						let obj = {
							pictureLoading: true,
							direction: 'right',
							msgType: '1',
							isWithdraw: true,
							key: len + 1,
							msgID: 'loading' + (len + 1)
						};
						this.setData({
								chats: [
									...this.chats,
									{
										...obj
									}
								]
							},
							() => {
								let scrollPosition = 'message' + this.chats[this.chats.length - 1].msgID;
								this.setData({
										scrollPosition
									},
									() => {
										console.log('图片上传准备完成')
										this.handleUploadFile(res);
									}
								);
							}
						);

						// 保存图片 /images/consult/34fdee766a6a937be3b33101884f1d26.png
						// let fileData = res;
						// let path = fileData.tempFilePaths instanceof Array && fileData.tempFilePaths.length > 0 ? fileData.tempFilePaths[0] : "";
						// let base64 = 'data:image/png;base64,' + wx.getFileSystemManager().readFileSync(path, 'base64');
					}
				});
			},

			// 图片上传
			handleUploadFile: function(fileData) {
				console.log('进入图片上传', fileData)
				let { doctorData } = this;
				let newUserData = this.$cache.get('userData');
				let path = fileData.tempFilePaths instanceof Array && fileData.tempFilePaths.length > 0 ? fileData.tempFilePaths[0] : '';
				let imgType
				// #ifdef MP
				imgType = path.split('.')[path.split('.').length - 1];
				// #endif
				// #ifdef H5
				imgType = fileData.tempFiles instanceof Array && fileData.tempFiles.length > 0 ? fileData.tempFiles[0].type : '';
				imgType = imgType.split('/')[1]
				// #endif
				console.log('图片类型===', imgType, path)
				if (imgType === 'jpg' || imgType === 'png' || imgType === 'jpeg' || imgType === 'gif') {
					// console.log("触发了")
					console.log('newUserData.consultFileUpload', newUserData.consultFileUpload);
					let url = newUserData && newUserData.consultFileUpload ? newUserData.consultFileUpload.indexOf('http') !== -1 ? newUserData.consultFileUpload : this.windowHost + newUserData.consultFileUpload : this.windowHost + '/uploadFile?fileType=consult';
					// #ifdef H5
					// url = url.replace(this.windowHost, '/fileUp') // 测试开启
					// #endif
					uni.uploadFile({
						url: url,
						//仅为示例，非真实的接口地址
						filePath: path,
						name: 'file',
						success: (unloadres) => {
							if (unloadres.statusCode === 200) {
								let imgName = JSON.parse(unloadres.data).filePath;
								let data = {
									params: [{
										admID: doctorData.admID,
										frUser: doctorData.userID,
										toUser: doctorData.toUser,
										consultText: '',
										picture: imgName
									}]
								};

								$http.post('urlS', this, {
									code: '02090004',
									data: data,
									namespace: 'Y',
									success: (res) => {
										if (+res.errorCode === 0) {
											let imgPath = (newUserData && newUserData.consultFile 
												? (newUserData.consultFile.indexOf('http') !== -1 ? newUserData.consultFile : this.windowHost + newUserData.consultFile) 
												: this.windowHost + '/images/consult/') + imgName;
											let imgKey = this.chats.length;
											let obj = {
												picture: imgPath,
												direction: 'right',
												msgType: '1',
												isWithdraw: true,
												key: imgKey,
												msgID: res.result && res.result.msgID ? res
													.result.msgID : ''
											};
											this.setData({
													chats: this.replaceLoading([...this
														.chats
													], obj),
													scrollPosition: 'message' + obj.message
												},
												() => {
													this.handleSendImg();
												}
											);
											// console.log("发送图片成功");
										} else {
											this.deleteLoading();
											uni.showToast({
											    title: '网络异常，请稍后再试。',
											    icon: 'none',
											})
										}
									},
									error: () => {
										this.deleteLoading();
										uni.showToast({
										    title: '网络异常，请稍后再试。',
										    icon: 'none',
										})
									}
								});
							} else {
								this.deleteLoading();
								uni.showToast({
								    title: '网络异常，请稍后再试。',
								    icon: 'none',
								})
							}
						},
						fail: () => {
							this.deleteLoading();
							uni.showToast({
							    title: '网络异常，请稍后再试。',
							    icon: 'none',
							})
						}
					});
				} else {
					uni.showToast({
					    title: '发送失败：图片类型有误或图片图片太大。',
					    icon: 'none',
					})
					setTimeout(() => {
						this.deleteLoading();
						// 发送失败
					}, 1000);
				}
			},

			// 过滤发送失败的图片loading
			deleteLoading() {
				if (this.chats && this.chats.length > 1) {
					let obj = {};
					this.setData({
							chats: this.replaceLoading([...this.chats], obj)
						},
						() => {
							let scrollPosition = 'message' + this.chats[this.chats.length - 1].msgID;
							this.setData({
								scrollPosition
							});
						}
					);
				}
			},

			// 图片加载成功之后替换加载中占位图
			replaceLoading(arr, obj) {
				let newArr = JSON.parse(JSON.stringify(arr));
				if (obj && obj.key) {
					let msgID = 'loading' + obj.key;
					// console.log(newArr, msgID)
					newArr = newArr.map((item) => (item.msgID === msgID ? obj : item));
					return newArr;
				} else {
					let key = newArr[newArr.length - 1].key;
					return newArr.filter((item) => item.key !== key);
				}
			},

			// 提交图片
			handleSendImg() {
				let {
					doctorData
				} = this;
				let messageContent = {
					userID: doctorData.toUser && doctorData.toUser === 'userKF001' ? 'KF001' : doctorData.toUser.slice(
						4),
					admID: doctorData.admID || '',
					patID: doctorData.userID ? doctorData.userID : '',
					patName: doctorData.patName || '',
					userName: doctorData.toUserName || '',
					type: doctorData.toUser && doctorData.toUser === 'userKF001' ? 'H' : 'M',
					text: '',
					image: 'Y'
				};
				let message = app.globalData.tim.createTextMessage({
					to: doctorData.toUser,
					conversationType: TIM.TYPES.CONV_C2C,
					payload: {
						text: JSON.stringify(messageContent)
					}
				});
				// 2. 发送消息
				let promise = app.globalData.tim.sendMessage(message);
				if (promise) {
					promise
						.then((imResponse) => {
							// 发送成功
							console.log('IM发送成功。');
						})
						.catch((imError) => {
							this.deleteLoading();
							// 发送失败
							uni.showToast({
							    title: '网络异常，请稍后再试。',
							    icon: 'none',
							})
							console.log(imError);
						});
				} else {
					uni.showToast({
					    title: '网络异常，请稍后再试。',
					    icon: 'none',
					})
					console.log('网络异常，请稍后再试。');
				}
			},

			modifyMessageStatus: function() {
				let {
					doctorData
				} = this;
				let data = {
					params: [{
						admID: doctorData.admID,
						frUser: doctorData.userID,
						toUser: doctorData.toUser
					}]
				};
				$http.post('urlS', this, {
					code: '02090006',
					data: data,
					namespace: 'Y',
					success: function(res) {
						if (+res.errorCode === 0) {
							console.log(res);
						}
					}
				});
			},

			async onScrollToUpper() {
				let {
					moreMsgFlag,
					chats
				} = this;
				if (moreMsgFlag === 'N') {
					if (chats && chats[0].sendTime === '没有更多消息记录了。') {
						return;
					}
					let obj = {
						direction: 'right',
						msgType: '3',
						sendTime: '没有更多消息记录了。'
					};
					chats.unshift(obj);
					this.setData({
						chats
					});
					return;
				} else {
					this.setData({
							hideHeader: false,
							lastMsgID: chats.length > 0 ? chats[0].msgID : ''
						},
						() => {
							this.getChatData('noBottom');
						}
					);
				}
			},

			async tryFun(fn, title) {
				try {
					await fn();
				} catch (e) {
					console.log('CatchClause', e);
					console.log('CatchClause', e);
					this.showError(title, e);
				}
			},

			showError(title, content, confirmText, confirmCallback) {
				console.error(title, content);
				uni.showModal({
					title,
					content: content.toString(),
					showCancel: confirmText ? true : false,
					confirmText,
					success: (res) => {
						if (res.confirm) {
							confirmCallback();
						}
					}
				});
			},

			// 查看原图
			viewOriginal(e) {
				let {
					chats
				} = this;
				let {
					picture
				} = e.currentTarget.dataset.page;
				let urls = [];
				for (var i = 0; i < chats.length; i++) {
					if (chats[i].picture && chats[i].msgType === '1') {
						urls.push(chats[i].picture);
					}
				}
				// console.log(urls)
				uni.previewImage({
					current: picture,
					// 当前显示图片的http链接
					urls // 需要预览的图片http链接列表
				});
			},

			onClickHide() {
				this.setData({
					visible: false
				});
			},

			// 输入框获取焦点事件
			fieldFocus(event) {
				let scrollPosition = this.chats && this.chats.length > 0 ? 'message' + this.chats[this.chats.length - 1]
					.msgID : '';
				this.setData({
					scrollPosition
				});
				this.setData({
					keyboardHeight: event.detail.height * 2,
					scrollPosition
				});
			},

			// 输入框失去焦点事件
			fieldBlur(event) {
				this.setData({
					keyboardHeight: 0
				});
			},

			// 返回首页 -- 或者 如果是已结束的未评价则进入评价界面
			handleGoHome() {
				let {
					doctorData
				} = this;
				if (doctorData && doctorData.appraiseMark === 'Y') {
					uni.navigateTo({
						url: '/pages/mine/evaluate/evaluate?admID=' + doctorData.admID + '&doctorname' + '=' +
							doctorData.toUserName + '&doctorID' + '=' + doctorData.toUser.slice(4)
					});
				} else {
					uni.switchTab({
						url: '/pages/tabBar/index/index'
					});
				}
			},

			// 我的问诊 - (继续咨询--跳转到该医生主页)
			handleGoMyConsultation() {
				let {
					doctorData
				} = this;
				let docObj = {};
				docObj.doctorID = doctorData.toUser.slice(4);
				app.globalData.docObj = docObj;
				app.globalData.locObj.locID = doctorData.locID;
				app.globalData.schDate = '';
				uni.navigateTo({
					url: '/pages/index/pages/doctorInfo/doctorInfo'
				});
			}
		},
		onShareAppMessage: function(res) {
			if (res.from === 'button') {
				// 来自页面内转发按钮
				console.log(res.target);
			}
		},
	};
</script>
<style>
	.header {
		height: 64rpx;
		line-height: 64rpx;
		width: 100%;
		text-align: center;
	}

	.header .header-gif {
		background: transparent;
		width: 60rpx;
		height: 32rpx;
		line-height: 32rpx;
	}

	.chatroom {
		width: 100%;
		height: 100vh;
		display: flex;
		flex-direction: column;
		box-sizing: border-box;
		overflow: hidden;
		position: relative;
	}

	.chatroom .footer {
		width: 100%;
		position: absolute;
		bottom: 0;
		left: 0;
		min-height: 60px;
		background-color: #f2f2f2;
	}

	.chatroom .footer-system-alert {
		background-color: #fff;
		padding: 24rpx;
		box-sizing: border-box;
	}

	.footer-system-alert-title {
		width: 100%;
		text-align: center;
		color: #333;
		font-size: 32rpx;
	}

	.footer-system-alert-btn {
		margin-top: 24rpx;
		display: flex;
		justify-content: space-around;
	}

	.footer-system-alert-btn .van-button {
		width: 40vw;
		border-radius: 10rpx;
	}

	.chatroom .footer .footer-content {
		width: 100%;
		flex-basis: fit-content;
		display: flex;
		flex-direction: row;
		padding: 20rpx 24rpx;
		background: #f2f2f2;
		box-sizing: border-box;
		min-height: 120rpx;
		align-items: center;
		justify-content: space-around;
	}

	.chatroom .footer .new-message-alert {
		height: 48rpx;
		line-height: 48rpx;
		background-color: #5cadff3d;
		padding-left: 24rpx;
		box-sizing: border-box;
		font-size: 24rpx;
		color: #666;
	}

	.chatroom .footer .text-input {
		height: 64rpx;
		padding: 0rpx 12rpx;
		width: 480rpx;
		border: none;
		border-radius: 24rpx;
		background-color: #fff;
		font-size: 32rpx !important;
		color: #666;
		box-sizing: border-box;
		transition: all 0.2s;
	}

	.chatroom .footer .van-cell {
		padding: 0;
		border-radius: 10rpx;
	}

	.chatroom .footer .iconfont {
		font-size: 60rpx;
		color: #999;
	}

	.chatroom .send-btn .van-button {
		padding: 0 24rpx;
		height: 56rpx;
		line-height: 56rpx;
		text-align: center;
		font-size: 28rpx;
		color: #fff;
		background-color: #4dc182;
		border-radius: 8rpx;
		display: flex;
	}

	.body {
		width: 100%;
		height: 100%;
	}

	.mw-content {
		margin: 24rpx;
		padding: 24rpx 0;
		margin-top: 0;
		display: flex;
	}

	.mw-content .col-1 {
		height: 84rpx;
		width: 84rpx;
		background-color: #5cadff;
		border-radius: 56rpx;
		text-align: center;
		line-height: 84rpx;
		font-size: 28rpx;
		color: #fff;
	}

	.mw-content .col-1 image {
		width: 84rpx;
		height: 84rpx;
		border-radius: 56rpx;
	}

	.mw-content .col-2 {
		position: relative;
		margin-top: 8rpx;
	}

	.mw-content .col-2 .icon-juxingbeifen {
		position: absolute;
		right: 0;
		top: -2rpx;
		color: #5cadff;
		display: inline-block;
		width: 32rpx;
		height: 32rpx;
	}

	.mw-content .col-2 .icon-juxingbeifen.icon-color-fff {
		color: #fff;
	}

	.mw-content .col-2 .icon-juxingbeifen.icon-left {
		left: 0;
		top: 0;
		transform: rotate(90deg);
	}

	.mw-content-right {
		flex-direction: row-reverse;
	}

	.mw-content-content {
		text-align: center;
	}

	.mw-content-content .col-3 text {
		display: inline-block;
		padding: 8rpx 24rpx;
		border-radius: 12rpx;
		background-color: #fff;
		margin: 12rpx 0;
		color: #a5b5c1;
	}

	.mw-content-content .re-edit {
		color: #66b1ff;
		margin-left: 16rpx;
		font-weight: normal;
	}

	.message-content {
		display: flex;
		outline: none;
		font-size: 28rpx;
		position: relative;
		max-width: 700rpx;
		word-wrap: break-word;
		word-break: break-all;
		padding: 20rpx;
		align-items: center;
		-webkit-box-shadow: 0 10rpx 10rpx 0 rgba(0, 0, 0, 0.1);
		box-shadow: 0 10rpx 10rpx 0 rgba(0, 0, 0, 0.1);
	}

	.body .col-4 {
		width: 100%;
		padding: 0 24rpx;
		box-sizing: border-box;
	}

	.col-4-content {
		width: 100%;
		height: 100%;
		padding: 8rpx 24rpx;
		margin: 12rpx 0;
		box-sizing: border-box;
		background: rgba(0, 0, 0, 0.1);
	}

	.col-4 .col-4-btn {
		color: #5cadff;
		text-align: center;
		font-size: 30rpx;
	}

	.col-4 .col-4-text {
		text-align: left;
		color: #666;
		/* text-indent: 2rem; */
	}

	.message-content .image {
		min-width: 300rpx;
		max-width: 300rpx;
		max-height: 600rpx;
	}

	.message-content .img-loading {
		text-align: center;
		line-height: 240rpx;
	}

	.message-content img.img-expression {
		width: 40rpx;
		height: 40rpx;
	}

	.message-received {
		background-color: #fff;
		margin-left: 24rpx;
		border-radius: 0 8rpx 8rpx 8rpx;
	}

	.message-send {
		background-color: #5cadff;
		margin-right: 24rpx;
		border-radius: 8rpx 0 8rpx 8rpx;
		color: #fff;
	}

	.background-color-fff {
		background-color: transparent;
		padding: 0;
	}

	.original-img {
		width: 100%;
		display: flex;
		margin: auto 0;
		align-items: center;
		overflow: hidden;
	}

	.original-img image {
		width: 100%;
	}

	.system-alert {
		width: 100%;
		padding: 12rpx 24rpx;
		color: #f76a24;
		box-sizing: border-box;
		font-size: 24rpx;
		text-align: center;
	}
</style>