<template>
	<view class="content" ref="showPanel">
		<view class="chat-cont" @click="closeBottom">
			<!-- 大夫 -->
			<view class="chat-item" v-for="(item) in msg" :class="item.from==doctorId?'':'my'">
				<view class="time">{{utils.parseTime(item.time)}}</view>
				<view class="peop-info" v-if="item.from==doctorId">
					<view class="img-box">
						<image :src="item.avatar" mode=""></image>
					</view>
					<view class="info">
						<view class="name">{{item.nick}}</view>
						<view class="words">
							{{item.payload.text}}
						</view>
					</view>
				</view>
				<view class="peop-info" v-if="item.from==user.userId">
					<view class="info">
						<view class="name">{{item.nick}}</view>
						<view class="words">
							{{item.payload.text}}
						</view>
					</view>
					<view class="img-box">
						<image :src="item.avatar" mode=""></image>
					</view>
				</view>
			</view>
			<!-- 我 -->
			<!-- <view class="chat-item my">
				<view class="time">2021-03-02  10:10:10</view>
				<view class="peop-info">
					<view class="info">
						<view class="name">张雪勤</view>
						<view class="words">
							嗯
						</view>
					</view>
					<view class="img-box">
						<image :src="item.avatar" mode=""></image>
					</view>
				</view>
			</view> -->
			<!-- 大夫 -->
			
			<!-- 我 -->
			<!-- <view class="chat-item my">
				<view class="time">2021-03-02  10:10:10</view>
				<view class="peop-info">
					<view class="info">
						<view class="name">张雪勤</view>
						<view class="words">
							嗯
						</view>
					</view>
					<view class="img-box">
						<image src="https://kntobs.jnmyunl.com/shop/images/head.jpg" mode=""></image>
					</view>
				</view>
			</view> -->
		</view>
		<view class="input-box"  id="chatCont" :style="{paddingBottom:bottomBlackLineHeight + 'rpx'}">
			<!-- 常用话术 -->
			<view class="used-phrases">
				<view v-for="(item,index) in 2" :key="index" class="item">换个人问问</view>
			</view>
			<!-- 输入框 -->
			<view class="input-inner">
				<input 
					type="text" 
					value="" 
					placeholder="请向医生详细描述您的症状" 
					:focus='setFocus' 
					placeholder-class="input-place" 
					confirm-type="发送" 
					 v-model="sendText"
					@input="textInput" 
				/>
				<image v-if="!hasSendValue" src="https://kntobs.jnmyunl.com/shop/images/add26.png" mode="" @click="showMoreMenu"></image>
				<view v-if="hasSendValue" class="send-btn" @click="sendMsg">发送</view>
			</view>
			<!-- 功能按钮 -->
			<view :class="showBottomMenu?'bottom-menu show':'bottom-menu'">
				<view class="item">
					<view class="img-box">
						<image src="https://kntobs.jnmyunl.com/shop/images/health.png" mode=""></image>
					</view>
					<text class="text">投诉反馈</text>
				</view>
				<view class="item">
					<view class="img-box">
						<image src="https://kntobs.jnmyunl.com/shop/images/health.png" mode=""></image>
					</view>
					<text class="text">常见问题</text>
				</view>
			</view>
		</view>
		<!-- 图片放大查看 -->
		<popupBottom ref="popup" :visible.sync="imgVisible" title="电子处方"  radius="32"  maxHeight="1200">
			<view class="popup-img-cont">
				<image :src="url" mode="widthFix"></image>
			</view>
		</popupBottom>
		
	</view>
</template>

<script>
	import {getUserInfo} from '@/api/user'
	import {getImOrderDetail} from '@/api/doctorOrder.js'
	import popupBottom from '@/components/px-popup-bottom/px-popup-bottom.vue'
	export default {
		components: {
			popupBottom
		},
		data() {
			return {
				order:null,
				doctor:null,
				user:null,
				// user:{
				// 	userId:'user2',
				// 	avatar:"https://thirdwx.qlogo.cn/mmopen/vi_32/DYAIOgq83eoQkMEXbsBBmgltByzYibp97iaX23nibxKwSyj88yaHoqXS4H7aliaum7G9xbjLxydEtIPa84C5CUwMLA/132",
				// 	nickname:"张三"
				// },
				msg:[],
				doctorId:null,
				orderId:null,
				// 图片放大弹窗
				imgVisible: false,
				// 内容发送框是否有值
				hasSendValue: false,
				// 功能按钮是否显示
				showBottomMenu: false,
				// 聊天输入框是否聚焦
				setFocus: false,
				// 输入框要发送的内容
				sendText: '',
				// iphoneX底部一条黑线，有些页面要避开
				bottomBlackLineHeight: uni.getStorageSync('bottomBlackLineHeight'),
				url: 'https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fc-ssl.duitang.com%2Fuploads%2Fitem%2F202007%2F06%2F20200706230613_ikvtn.thumb.1000_0.jpg&refer=http%3A%2F%2Fc-ssl.duitang.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1650117742&t=f64aa5215aeda871eb9a69a70329f7a0'
			}
		},
		onLoad(option) {
			console.log(option.orderId)
			this.orderId=option.orderId;
			this.getImOrderDetail();
			this.getUserInfo()
			var that=this;
			//登录 可以放到IM外登录 考虑是否按时付费
			uni.$TUIKit.login({
				userID: that.user.userId,
				userSig: "eJwtzE0LgkAUheH-MttCruNcZYR2Qp*kqBC0E2a0S6XDaCJF-z1Tl*d54XxYfsqcXlsWMu4AW0*blK47KmniV6stX0Kr7oUxpFjoCgD0pSe8uejBkNWjIyIHgFk7ev7NFxK5BHfRlqrxtyqP8uG-d4fgVp-TeD-0mZBekgeRKLEp*uQSUyq31xU0G-b9ARDtMKA_"
			}).then((res) => {
				setTimeout(function(){
					let promise = uni.$TUIKit.updateMyProfile({
					  nick: that.user.nickname,
					  avatar: that.user.avatar,
					  gender: uni.$TUIKitTIM.TYPES.GENDER_MALE,
					  selfSignature: '我的个性签名',
					  allowType: uni.$TUIKitTIM.TYPES.ALLOW_TYPE_ALLOW_ANY
					});
					promise.then(function(imResponse) {
					  console.log(imResponse.data); // 更新资料成功
					}).catch(function(imError) {
					  console.warn('updateMyProfile error:', imError); // 更新资料失败的相关信息
					});
					that.getMessageList();
				},1000);
				 
				
			}).catch((error) => {
				 
			});
			uni.$TUIKit.on(uni.$TUIKitTIM.EVENT.MESSAGE_RECEIVED, this.onMessageReceived);
			
		},
		methods: {
			getUserInfo(){
				getUserInfo().then(
					res => {
						if(res.code==200){
							if(res.user!=null){
								this.user=res.user;
							}
							
						}else{
							uni.showToast({
								icon:'none',
								title: "请求失败",
							});
						}
					},
					rej => {}
				);
			},
			getImOrderDetail(){
				let data = {orderId:this.orderId};
				var that=this;
				getImOrderDetail(data).then(
					res => {
						if(res.code==200){
							 this.doctor=res.doctor;
							 this.order=res.order;
							 uni.setNavigationBarTitle({
							 	title:'与'+this.doctor.doctorName+'医生聊天中'
							 })
							 
						}else{
							uni.showToast({
								icon:'none',
								title: "请求失败",
							});
						}
					},
					rej => {}
				);
			},
			onMessageReceived(event){
				console.log(event)
				if(event.name=='onMessageReceived'){
					this.msg=this.msg.concat(event.data);
					console.log(this.msg)
				}
			},
			getMessageList(){
				var that=this;
				let promise = uni.$TUIKit.getMessageList({conversationID: 'C2C'+that.doctorId, count: 15});
				promise.then(function(imResponse) {
				  that.msg = imResponse.data.messageList; // 消息列表。
				  console.log(that.msg)
				  // const nextReqMessageID = imResponse.data.nextReqMessageID; // 用于续拉，分页续拉时需传入该字段。
				  // const isCompleted = imResponse.data.isCompleted; // 表示是否已经拉完所有消息。
				});
			},
			sendMessage(msg){
				var that=this;
				let message = uni.$TUIKit.createTextMessage({
				  to: that.doctorId,
				  conversationType: uni.$TUIKitTIM.TYPES.CONV_C2C,
				  // 消息优先级，用于群聊（v2.4.2起支持）。如果某个群的消息超过了频率限制，后台会优先下发高优先级的消息，详细请参考：https://cloud.tencent.com/document/product/269/3663#.E6.B6.88.E6.81.AF.E4.BC.98.E5.85.88.E7.BA.A7.E4.B8.8E.E9.A2.91.E7.8E.87.E6.8E.A7.E5.88.B6)
				  // 支持的枚举值：TIM.TYPES.MSG_PRIORITY_HIGH, TIM.TYPES.MSG_PRIORITY_NORMAL（默认）, TIM.TYPES.MSG_PRIORITY_LOW, TIM.TYPES.MSG_PRIORITY_LOWEST
				  // priority: TIM.TYPES.MSG_PRIORITY_NORMAL,
				  payload: {
				    text: msg
				  },
				  // 消息自定义数据（云端保存，会发送到对端，程序卸载重装后还能拉取到，v2.10.2起支持）
				  // cloudCustomData: 'your cloud custom data'
				});
				// 2. 发送消息
				let promise = uni.$TUIKit.sendMessage(message);
				promise.then(function(imResponse) {
				  // 发送成功
				  console.log(imResponse);
				  if(imResponse.code==0){
					  that.msg.push(imResponse.data.message);
					  that.hasSendValue = false
					  that.sendText = ''
					  that.setFocus = true
				  }
				  //更新列表
				  
				}).catch(function(imError) {
				  // 发送失败
				  console.warn('sendMessage error:', imError);
				});
			},
			// 查看大图
			showBigImg() {
				this.imgVisible = true
			},
			// 展示更多菜单
			showMoreMenu() {
				if(!this.showBottomMenu) {
					this.showBottomMenu = true
				} else {
					if(this.setFocus) {
						this.setFocus = false
					} else {
						this.setFocus = true
					}
				}
			},
			// 输入框发送消息
			sendMsg() {
				this.sendMessage(this.sendText)
				
				
			},
			// 关闭底部更多菜单
			closeBottom(e) {
				if(e.target.id!=undefined && e.target.id!=="chatCont"){
					this.showBottomMenu = false
				}
			},
			// 监听输入框是否有值
			textInput(e) {
				if(e.detail.value) {
					this.hasSendValue = true
				} else {
					this.hasSendValue = false
				}
			}
		}
	}
</script>

<style lang="scss">
	page{
		height: 100%;
	}
	.content{
		height: 100%;
		display: flex;
		flex-direction: column;
		justify-content: space-between;
		.chat-cont{
			box-sizing: border-box;
			flex: 1;
			overflow-y: auto;
			background-color: #F2F5F9;
			padding: 0 30upx 60upx;
			.chat-item{
				padding-top: 60upx;
				.time{
					font-size: 26upx;
					font-family: PingFang SC;
					font-weight: 500;
					color: #999999;
					line-height: 1;
					margin-bottom: 30upx;
					text-align: center;
				}
				.peop-info{
					display: flex;
					.img-box{
						width: 78upx;
						height: 78upx;
						border-radius: 50%;
						overflow: hidden;
						flex-shrink: 0;
						margin-right: 20upx;
						image{
							width: 100%;
							height: 100%;
						}
					}
					.info{
						.name{
							font-size: 28upx;
							font-family: PingFang SC;
							font-weight: 500;
							color: #666666;
							line-height: 1;
							margin-bottom: 20upx;
						}
						.words{
							box-sizing: border-box;
							max-width: 520upx;
							font-size: 32upx;
							font-family: PingFang SC;
							font-weight: 500;
							color: #111111;
							line-height: 50upx;
							padding: 20upx 30upx;
							background: #FFFFFF;
							border-radius: 0 20upx 20upx 20upx;
							image{
								width: 364upx;
								height: auto;
							}
						}
					}
				}
				&.my{
					.peop-info{
						justify-content: flex-end;
						.img-box{
							margin-right: 0;
							margin-left: 20upx;
						}
						.info {
							.name{
								text-align: right;
							}
							.words{
								background: #2BC7B9;
								color: #FFFFFF;
								border-radius: 20upx 0 20upx 20upx;
							}
						}
					}
				}
			}
		}
		.input-box{
			box-sizing: border-box;
			flex-shrink: 0;
			background: #FFFFFF;
			display: flex;
			flex-direction: column;
			padding: 20upx 30upx 0;
			.used-phrases{
				display: flex;
				flex-wrap: wrap;
				.item{
					height: 64upx;
					line-height: 64upx;
					padding: 0 30upx;
					border-radius: 32upx;
					border: 1px solid #F7F7F7;
					background-color: #FFFFFF;
					font-size: 28upx;
					font-family: PingFang SC;
					font-weight: 500;
					color: #111111;
					margin-right: 20upx;
					margin-bottom: 20upx;
				}
			}
			.input-inner{
				display: flex;
				align-items: center;
				justify-content: space-between;
				input{
					box-sizing: border-box;
					// width: calc(100% - 82upx);
					flex: 1;
					height: 80upx;
					background: #F2F2F2;
					border-radius: 40upx;
					padding: 0 30upx;
					font-size: 28upx;
					font-family: PingFang SC;
					font-weight: 500;
					color: #000000;
				}
				.input-place{
					font-size: 28upx;
					font-family: PingFang SC;
					font-weight: 500;
					color: #999999;
				}
				image{
					flex-shrink: 0;
					width: 52upx;
					height: 52upx;
					margin-left: 30upx;
				}
				.send-btn{
					flex-shrink: 0;
					height: 64upx;
					line-height: 64upx;
					border-radius: 32upx;
					background: #2BC7B9;
					font-size: 28upx;
					font-family: PingFang SC;
					font-weight: 500;
					color: #FFFFFF;
					padding: 0 30upx;
					margin-left: 30upx;
				}
			}
			.bottom-menu{
				height: 0;
				display: flex;
				flex-wrap: wrap;
				overflow: hidden;
				opacity: 0;
				// transition: all 0.5s;
				&.show{
					padding: 30upx 30upx 0;
					height: auto;
					opacity: 1;
				}
				.item{
					display: flex;
					flex-direction: column;
					align-items: center;
					justify-content: center;
					margin-right: 77upx;
					margin-bottom: 30upx;
					&:nth-child(4n) {
						margin-right: 0;
					}
					.img-box{
						width: 100upx;
						height: 100upx;
						background-color: #F5F5F5;
						border-radius: 8upx;
						display: flex;
						align-items: center;
						justify-content: center;
						image{
							width: 40upx;
							height: 40upx;
						}
					}
					.text{
						font-size: 24upx;
						font-family: PingFang SC;
						font-weight: 500;
						color: #333333;
						margin-top: 20upx;
					}
				}
			}
		}
	}
	.popup-img-cont{
		display: flex;
		align-items: center;
		image{
			width: 100%;
		}
	}
</style>
