<template>
	<view :style="{paddingTop: statusBarHeight+88+'upx',paddingBottom:scrollInputh+'upx'}">

		<!-- 顶部状态栏 -->
		<view class="mynavbar " :style="{paddingTop: statusBarHeight+'upx'}">
			<view class="mynavbarbox ali-c flex jua-a">
				<view @tap="goback" class="breaksbtn ali-c ">
					<image class="breakiconss" src="/static/chat/breakiconss2.png" mode=""></image>
				</view>
				<view class="navbartitle oneline">
					<text v-if="type==1">{{IMtitle}}</text>
					<view v-else-if="type==2" class="userlistss flex ali-c jus-c">
						<view v-show="Merchantinfo.userAvatar" class="itemusers">
							<image class="utxs" :src="Merchantinfo.userAvatar" mode=""></image>
							<view class="utxstag">商家</view>
						</view>
						<view v-show="riderinfo.userAvatar" class="itemusers">
							<image class="utxs" :src="riderinfo.userAvatar" mode=""></image>
							<view class="utxstag"></view>
							<view class="utxstag">骑手</view>
						</view>
						<view v-show="Userinformation.userAvatar" class="itemusers">
							<image class="utxs" :src="Userinformation.userAvatar" mode=""></image>
							<view class="utxstag">用户</view>
						</view>
						<view v-show="serviceinfo.userAvatar" class="itemusers">
							<image class="utxs" :src="serviceinfo.userAvatar" mode=""></image>
							<view class="utxstag">客服</view>
						</view>
					</view>
				</view>
				<view class="mynavbarbtn flex ali-c jus-a">
					<view @tap="catphone" class="iconsbtn">
						<image class="iconsimg" src="/static/chat/telephony.png" mode=""></image>
					</view>
					<view v-if="type==2" @tap="toorderinfo" class="iconsbtn">
						<image class="iconsimg" src="/static/chat/ordericonss.png" mode=""></image>
					</view>
				</view>
			</view>
		</view>
		<!-- 顶部状态栏end -->


		<!-- 单聊 type=1  群聊 type=2 -->
		<!-- push 发出 pull 收到 -->
		<scroll-view :style="{height: scrollheight+'px'}" class="scrollview" scroll-y :scroll-top="scrollTop"  :scroll-with-animation="false">
			<view class="chatboxtwo" id="list-box" @tap.stop="listboxtap">
				<view class="talk-list">
					<view v-for="(item,index) in msgslist" :key="index" :id="`msg-${item.msgId}`">
						<view v-if="item.elemType==1" class="item flex_col" :class="item.isSelf == true ? 'push':'pull' ">
							<image :src="item.userAvatar" mode="aspectFill" class="pic"></image>
							<view>
								<view class="contentss">{{item.textElem.msg}}</view>
								<view v-if="item.isSelf == true && item.isPeerRead && type==1" class="isread">已读</view>
							</view>
						</view>

						<!-- 2 自定义消息 -->
						<view v-if="item.elemType==2 && item.customdata">
							<!-- 1发送的产品消息 -->
							<view v-if="item.customdata.type==1" class="item flex_col"
								:class="item.isSelf == true ? 'push':'pull' ">
								<image :src="item.userAvatar" mode="aspectFill" class="pic "></image>
								<view class="" v-if="item.customdata.img">
									<view  class="kjsendproduct goodscard flex"
										:class="item.isSelf == true ? 'push':'pull' ">
										<image class="thumbnails" :src="staticUrl+item.customdata.img" mode="">
										</image>
										<view class="showgoodsinfo flex1">
											<view class="flex  jus-b">
												<view class="goods_names twoline flex1">{{item.customdata.title}}</view>
											</view>
											<view class="isprice flex ali-c jus-b">
												<view class="price"><text class="fuhao">￥</text>{{item.customdata.price}}</view>
											</view>
										</view>
									</view>
									<view v-if="item.isSelf == true && item.isPeerRead && type==1" class="isread">已读</view>
								</view>
							</view>
						
							<!-- 2 订单状态通知 -->
							<view class="ordernoticebox" v-else-if="item.customdata.type==2">
								<view class="msgstime">{{item.time|dateFormat}}</view>
								<view class="ordernotice">
									<view class="orderstatit">温馨提示</view>
									<view class="ordertextets">您已成功下单,可与商家及骑手在此群联系,快速了解出餐进度及修改备注信息。</view>
								</view>
							</view>
							
							<view class="ordernoticebox" v-else-if="item.customdata.type==3">
								<view class="msgstime">{{item.time|dateFormat}}</view>
								<view class="ordernotice">
									<view class="orderstatit">温馨提示</view>
									<view class="ordertextets">亲,群创建成功了,有问题可以在群里咨询哦。</view>
								</view>
							</view>
							
							
							<view @tap="tomsglink(item)" class="ordernoticebox" v-else-if="item.customdata.type==4">
								<view class="msgstime">{{item.time|dateFormat}}</view>
								<view class="ordernotice">
									<view class="orderstatit">{{item.customdata.title}}</view>
									<view class="ordertextets">{{item.customdata.content}}</view>
									<view class="tovieews" v-show="item.customdata.s_link">点击查看 > ></view>
								</view>
							</view>
						
							<view v-else class="item flex_col" :class="item.isSelf == true ? 'push':'pull' ">
								<image :src="item.userAvatar" mode="aspectFill" class="pic"></image>
								<view>
									<view class="contentss">[自定义消息 暂时无法识别]</view>
									<view v-if="item.isSelf == true && item.isPeerRead && type==1" class="isread">已读</view>
								</view>
							</view>
						
						</view>
						<!-- 自定义消息end -->


						<!-- 图片消息 elemType==3 -->
						<view v-if="item.elemType==3" class="item flex_col" :class="item.isSelf == true ? 'push':'pull' ">
							<image :src="item.userAvatar" mode="aspectFill" class="pic"></image>
							<view class="contentss">
								<view class="xiaoxineir" >
									<image @load="loadimgbefor"  @tap="showimgdetaile(item)" class="xiaoxiimgs" style="width: 100upx;"
										:src="item | geturlfun" mode="widthFix">
									</image>
								</view>
							</view>
						</view>
						<!-- 语音消息 4 -->
						<view v-if="item.elemType==4" class="item flex_col" :class="item.isSelf == true ? 'push':'pull' ">
							<image :src="item.userAvatar" mode="aspectFill" class="pic"></image>
							<view class="contentss flex">
								<text v-if="item.isSelf == true"
									class="timess">{{item.soundElem.duration==0?1:item.soundElem.duration}}''</text>
								<image @tap="bofangmp3(item)" class="yuyingicons"
									:src="mp3msgId==item.msgId?'/static/chat/mp3fileicon1.gif':'/static/chat/mp3fileicon1.png'"
									mode=""></image>
								<text v-if="item.isSelf == false"
									class="timess">{{item.soundElem.duration==0?1:item.soundElem.duration}}''</text>
							</view>
						</view>

					</view>
				</view>

			</view>
		</scroll-view>
	
		<view class="chatboxinps" id="chatboxinps">
			<view class="flex_col lineinputboxs textbox">
				<view @tap="taggleisVoice" class="leftnavicons">
					<image v-if="!isVoice" class="icons2" src="/static/chat/voice.png" mode=""></image>
					<image v-if="isVoice" class="icons2" src="/static/chat/keyboard.png" mode=""></image>
				</view>
				<view v-if="!isVoice" class="flex_grow inputcontentss">
					<textarea placeholder-class="" class="uni-input contentss pt-10" style="width: auto;"
						cursor-spacing="10" placeholder="请输入聊天内容" v-model="content" @focus="textareaFocus" />
				</view>
				<view class="info-words voice-mode" v-show="isVoice"
					style="font-size: 28upx;padding: 10upx 30upx;border-bottom: 1px solid #EEEEEE;"
					@touchstart="voiceBegin" @touchmove.stop.prevent="voiceIng" @touchend="voiceEnd">{{voiceTis}}</view>
				<view class="rightnavicons flex ali-c">
					<image @tap="tagglecamera(1)" class="icons2" src="/static/chat/expression.png" mode=""></image>
					<image @tap="tagglecamera(2)" class="icons2" src="/static/chat/quick.png" mode=""></image>
					<image @tap="tagglecamera(3)" v-show="content==''" class="icons2" src="/static/chat/allicons.png"
						mode=""></image>
					<button v-show="content!=''" class="send" @tap="send">发送</button>
				</view>
				<!-- 发送产品消息 -->
				<view v-if="isshowtisgoods" class="kjsendproduct abso flex">
					<image class="thumbnails" src="https://kazuma.jxdsy.cn/attachs/2021/09/30/a482f2383fa07efdfc.jpg"
						mode=""></image>
					<view class="showgoodsinfo flex1">
						<view class="flex  jus-b">
							<view class="goods_names twoline flex1">
								美之魂20年窖酒原价美之魂20年窖酒原价1688一瓶500ml限购价688美之魂20年窖酒原价1688一瓶500ml限购价688</view>
							<image @tap="imcleargoods" class="imclearicon" src="/static/chat/imclearicon.png" mode="">
							</image>
						</view>
						<view class="isprice flex ali-c jus-b">
							<view class="price"><text class="fuhao">￥</text>688</view>
							<view @tap="sendC2CCustomMessagefun(1)" class="sendgoodsbtn">发送给客服</view>
						</view>
					</view>
				</view>
			</view>

			<view v-if="showcamera" class="popup-layer dibuboxss " @touchmove.stop.prevent="discard">
				<!-- 表情 -->
				<swiper v-if="showtype==1" class="emoji-swiper" indicator-dots="true" duration="150">
					<swiper-item v-for="(page,pid) in emojiList" :key="pid">
						<view v-for="(em,eid) in page" :key="eid" @tap="addEmoji(em)">
							<!-- #ifndef APP-PLUS -->
							<image mode="widthFix" :src="em.url"></image>
							<!-- #endif -->
							<!-- #ifdef APP-PLUS -->
							<text class="s50">{{em.alt}}</text>
							<!-- #endif -->
						</view>
					</swiper-item>
				</swiper>

				<!-- 常用语 -->
				<view v-if="showtype==2" class="commonwords">
					<view class="scrollviewh">
						<scroll-view class="" :scroll-x="true" :scroll-y="true">
							<view style="height: 42vw;">
								<view @tap="shendkjy(item)" v-for="(item,index) in commonwords" :key="index"
									class="cyyitems">{{item.name}}</view>
							</view>
						</scroll-view>
					</view>
				</view>

				<view v-if="showtype==3" class="more-layer">
					<view class="list operation_foots flex ali-c jus-a">
						<view @tap="chooseImagefun(1)" class="xitonnavitem">
							<image class="navimgs" src="/static/chat/xiangjiicon.png" mode=""></image>
							<view class="navnames">打开相机</view>
						</view>

						<view @tap="chooseImagefun(2)" class="xitonnavitem">
							<image class="navimgs" src="/static/chat/xiangce.png" mode=""></image>
							<view class="navnames">打开相册</view>
						</view>
						
						<navigator hover-class="none" url="/pages/chat/report/report" class="xitonnavitem">
							<image class="navimgs" src="/static/chat/reporticon.png" mode=""></image>
							<view class="navnames">投诉举报</view>
						</navigator>
						
					</view>
				</view>
			</view>

			<!-- 录音UI效果 -->
			<view class="record" :class="recording?'':'hidden'">
				<view class="ing" :class="willStop?'hidden':''">
					<view class="icon luyin2"></view>
				</view>
				<view class="cancel" :class="willStop?'':'hidden'">
					<view class="icon chehui"></view>
				</view>
				<view class="tis" :class="willStop?'change':''">{{recordTis}}</view>
			</view>
			<!-- 录音UI效果end -->

		</view>
	</view>
</template>

<script>
	/**
	 * elemType
		 消息值	含义
		 1	文本消息
		 2	自定义消息
		 3	图片消息
		 4	语音消息
		 5	视频消息
		 6	文件消息
		 7	地址位置消息
		 8	表情消息
		 9	群 Tips 消息
	 * 
	 * */
	let txIm = {};
	// #ifdef APP-PLUS
	txIm = uni.requireNativePlugin('TX-TencentIM');
	// #endif
	import commen from "@/utils/commen.js";
	import {timestampToTime} from "@/utils/yicode.js";
	let innerAudioContext = {
		stop: () => {}
	};
	export default {
		components: {

		},
		filters: {
			parsepath(val) {
				if (val == null || val == undefined) {
					return "/static/chat/imgloaderr.png";
				}

				if (val.indexOf('http') != -1) {
					return val;
				}
				var urls = 'file://' + String(val);
				return urls;
			},
			dateFormat(value) {
				return timestampToTime(value);
			},
			//过滤器加载图片
			geturlfun(item) {
				try {
					let url = "";
					// #ifndef APP-PLUS
					if (item.payload.imageInfoArray) {
						url = item.payload.imageInfoArray[0].url
					};
					// #endif
					// #ifdef APP-PLUS
					//两种形式的图片
					if (item.imageElem) {
						if (item.imageElem.path) {
							if (item.imageElem.path.indexOf("http") != -1) {
								url = item.imageElem.path;
							} else {
								url = "file://" + item.imageElem.path;
							}
						}
					}
					//网络资源图片
					if(item.url_imageList){
						if(item.url_imageList.length!=0){
							url = item.url_imageList[0].url;
							if(item.url_imageList.length>1){
								url = item.url_imageList[1].url;
							}
						}
					}
					// #endif
					
					// console.info("url",url);
					return url;
				} catch (err) {
					return "/static/chat/imgloaderr.png";
				}
			}
		},
		data() {
			return {
				statusBarHeight: 0,
				talkList: [],
				content: '',

				type: '', //1单聊 2群聊
				userId: '', //对方的用户id
				groupId: '', //群聊id


				groupInfodata: {}, //群信息
				qunmembers: [], //群成员

				showcamera: false,
				showtype: 1, //1表情 2快捷常用语 3相机 

				emojiList: commen.emojiList, //表情列表
				currentMsgId: "", //最后一条消息的ID 用于获取更多最新的消息

				//语音消息
				//录音相关参数
				// #ifndef H5
				//H5不能录音
				RECORDER: uni.getRecorderManager(),
				// #endif
				isVoice: false,
				voiceTis: '按住 说话',
				recordTis: "手指上滑 取消发送",
				recording: false,
				willStop: false,
				initPoint: {
					identifier: 0,
					Y: 0
				},
				recordTimer: null,
				recordLength: 0,

				mp3msgId: "", //正在播放的语音消息id
				scrollInputh: 0, //底部的高度

				commonwords: [{
						name: "你好,我们的出餐速度很快的"
					},
					{
						name: "你好,您的订单骑手已经取餐。"
					},
					{
						name: "你好,店铺主页有优惠券可以领取。"
					},
					{
						name: "我们的店铺是支持配送的"
					},
					{
						name: "好的，收到"
					},
					{
						name: "你好，请问要微辣还是中辣？"
					},
				],
				isshowtisgoods: false, //是否显示提示产品


				qunusermelist: [],
				//群内关键人物信息
				Userinformation: {}, //用户
				Merchantinfo: {}, //商家
				riderinfo: {}, //骑手信息
				serviceinfo: {}, //客服信息
				
				dftype:1,//对方的身份 1 用户 2商家 3骑手 4 客服
				IMtitle:"聊天",
				dfuinfo:{},//单聊对方的信息
				
				scrollTop:0,
				scrollheight:513,
			}
		},
		computed: {
			//单聊消息列表
			msgslist() {
				if (this.type == 1) {
					return this.$store.state.msgslist;
				} else if (this.type == 2) {
					return this.$store.state.qunmsgslist;
				}
			},
			staticUrl() { //静态资源地址
				return this.$store.state.staticUrl;
			}
		},
		watch: {
			msgslist() {
				if (this.type == 1) {
					if(this.msgslist.length!=0){
						setTimeout(()=>{
							this.ToTheBottom();
						}, 200);
					}
					this.markC2CMessageAsReadfun();
				} else if (this.type == 2) {
					if(this.msgslist.length!=0){
						setTimeout(()=>{
							this.ToTheBottom();
						}, 200);
					}
					this.markGroupMessageAsRead();
				}

			}
		},
		onLoad(options) {
			
			try{
				//获取设备信息
				let resinfo = uni.getSystemInfoSync();
				console.info(resinfo,"resinfo");
				let windowHeight = resinfo.windowHeight;//可使用窗口高度	768
				//上面的是95 下面的是56
				//上面44 下面 42
				let scrollheight = windowHeight-44-43-resinfo.statusBarHeight;
				this.scrollheight = scrollheight;//可滑动区域的高度 计算出来是
			}catch(error){
				console.error("error",error);
			}

			setTimeout(() => {
				this.statusBarHeight = uni.getSystemInfoSync().statusBarHeight * 2;
			}, 10)

			this.type = options.type;
			this.userId = options.userId;
			this.groupId = options.groupId;

			//单聊
			if (this.type == 1) {
				this.$store.commit("setdfuserId", this.userId); //修改正在聊天的用户id
				this.geIMtUsersInfofun([this.userId]);
				this.baseloadmsg();
			} else if (this.type == 2) {
				this.$store.commit("SetgroupId", this.groupId); //修改正在聊天的用户id
				this.baseloadmsg(); //获取群历史消息
				this.getGroupsInfofun(); //获取群信息
				this.getGroupMemberListfun(); //获取群成员
			}


			//处理语音消息
			setTimeout(() => {
				//发送语音消息
				this.RECORDER.onStart((e) => {
					//开始发送语音消息
					this.recordBegin(e);
				})
				//录音结束事件
				this.RECORDER.onStop((e) => {
					//结束发送语音消息
					this.recordEnd(e);
				})
			}, 2000)

		},
		mounted() {

		},
		onHide() {
			innerAudioContext.stop(); //结束语音播放
			this.mp3msgId = "";
		},
		onUnload() {
			innerAudioContext.stop(); //结束语音播放
			this.mp3msgId = "";

			//删除缓存消息
			//......
			this.$store.commit("setqunmsgslist", []);
			this.$store.commit("Setmsgslist", []);
		},
		onPageScroll(e) {
			if (e.scrollTop < 5) {
				this.getHistoryMsg();
			}
		},
		methods: {
			//图片加载完成
			loadimgbefor(){
				// console.info('图片加载完成');
				this.ToTheBottom();
			},
			//发送快捷语
			shendkjy(item) {
				this.content = item.name;
				this.send();
				this.showcamera = false; //关闭常用语选择
			},
			//通用加载更多消息
			baseloadmsg() {
				//单聊
				if (this.type == 1) {
					this.$store.dispatch("getC2CHistoryMessageList", {
						msgId: this.currentMsgId
					}).then((res) => {
						this.ToTheBottom();
					});
				} else if (this.type == 2) {
					this.$store.dispatch("getGroupHistoryMessageList", {
						msgId: this.currentMsgId
					}).then((res) => {
						this.ToTheBottom();
					}); //获取群历史消息
				}
			},
			//语音和文字输入切换
			taggleisVoice() {
				this.isVoice = !this.isVoice;
				if (this.isVoice) {
					// this.tagglecamera();
					this.showcamera = false;
				}
			},
			tagglecamera(type) {
				this.showtype = type;
				// this.showcamera = !this.showcamera;
				this.showcamera = true;
				if (this.showcamera) {
					if (type == 1 || type == 2) {
						this.isVoice = false;
					}
					this.getscrollviewmain();
				} else {
					this.scrollInputh = 0;
					this.ToTheBottom();
				}
			},
			//空白位置被点击
			listboxtap(e) {
				this.showcamera = false;
				this.scrollInputh = 0;
				// this.ToTheBottom();
			},
			//输入框获取到焦点
			textareaFocus() {
				this.showcamera = false;
				this.imcleargoods();
				
				this.ToTheBottom();//置底
			},
			imcleargoods() {
				this.isshowtisgoods = false; //关闭提示产品
			},
			//测试删除消息
			delmsg() {
				txIm.deleteMessages({
					"msgIdList": ["144115232869100554-1633600403-30701550",
						"144115232869100554-1633599731-4275448668", "144115232869100554-1633599558-3175235063"
					]
				}, result => {
					//消息删除成功
				})
			},
			discard(e) {
				return;
			},
			//页面置底
			ToTheBottom() {
				console.info("置底");
				// this.$nextTick(() => {
				// 	// dom元素更新后执行，因此这里能正确打印更改之后的值
				// 	let curRoute = this.$mp.page.route;
				// 	if(curRoute=='pages/chat/chat/chat'){
				// 		uni.pageScrollTo({
				// 			scrollTop: 9999999999, // 设置一个超大值，以保证滚动条滚动到底部
				// 			duration: 0
				// 		});
				// 	}else{
				// 		console.info("不在当前页面了 不能置底");
				// 	}
				// })
				
				this.$nextTick(() => {
					// dom元素更新后执行，因此这里能正确打印更改之后的值
					let view = uni.createSelectorQuery().select(".chatboxtwo");
					view.boundingClientRect((data)=> {
						//获取固定尾部的高度=data.height
						// that.style.footViewHeight = data.height
						// console.info(" data.height", data.height);
						if(data){
							this.scrollTop = data.height+460;
						}else{
							console.info("加载快了");
							this.scrollTop = 999999999;
						}
						
					}).exec();
				})
			},
			// 获取历史消息
			getHistoryMsg() {

			},
			// 拼接历史记录消息，正式项目可替换为请求历史记录接口
			joinHistoryMsg() {

			},
			// 设置页面滚动位置
			setPageScrollTo(selector) {
				let view = uni.createSelectorQuery().in(this).select(selector);
				view.boundingClientRect((res) => {
					uni.pageScrollTo({
						scrollTop: res.top - 30, // -30 为多显示出大半个消息的高度，示意上面还有信息。
						duration: 0
					});
				}).exec();
			},
			// 发送信息
			send() {
				if (!this.content) {
					uni.showToast({
						title: '请输入有效的内容',
						icon: 'none'
					})
					return;
				}
				uni.showLoading({
					title: '正在发送'
				})
				if (this.type == 1) {
					//单聊
					let user = this.userId;
					txIm.sendC2CTextMessage({
						"textMsg": this.content,
						"userId": user,
						"title": "新消息",
						"desc": this.content,
						"ext": this.content
					}, result => {
						//发送成功
						this.currentMsgId = result.msgId;
						uni.hideLoading();
						// 清空内容框中的内容
						this.content = '';
						//后面要改
						this.baseloadmsg(); //获取单聊历史消息
					});
				} else if (this.type == 2) {
					//群聊
					//发送群文本消息
					txIm.sendGroupTextMessage({
						"textMsg": this.content,
						"groupId": this.groupId,
						"priority": 0
					}, result => {
						//群消息获取成功
						uni.hideLoading();
						// 清空内容框中的内容
						this.content = '';
						this.currentMsgId = result.msgId;
						this.baseloadmsg(); //获取群历史消息
					})

				}
			},
			//获取群信息
			getGroupsInfofun() {
				this.$store.dispatch("getGroupsInfo", {}).then((res) => {
					if (res.groupInfoList.length != 0) {
						this.groupInfodata = res.groupInfoList[0].info;
					}
				});
			},
			//获取群成员列表
			getGroupMemberListfun() {
				this.$store.dispatch("getGroupMemberList", {}).then((res) => {
					if (res.code == 0) {
						this.qunmembers = res.members;
						let isarr = []; //获取id集合

						this.qunmembers.forEach((item, index) => {
							isarr.push(item.userId);
						})
						this.geIMtUsersInfofun(isarr);
					}
				});
			},
			//获取指定用的信息
			geIMtUsersInfofun(isarr){
				this.$store.dispatch("geIMtUsersInfo", {
					userIdList: isarr
				}).then((resa) => {
					this.qunusermelist = resa.members;
					let qunusermelist = this.qunusermelist;
					qunusermelist.forEach((item, index) => {
						if (item.customInfo.identity != undefined && item.customInfo
							.identity != null) {
							//用户信息 1 用户 2商家 3骑手 4 客服
							if (item.customInfo.identity == '1') {
								this.Userinformation = item;
								if(this.type==1){//单聊
									this.dftype = 1;
									this.IMtitle = item.userName+' [用户]';
									this.dfuinfo = item;
								}
							} else if (item.customInfo.identity == '2') {
								this.Merchantinfo = item;
								if(this.type==1){//单聊
									this.dftype = 2;
									this.IMtitle = item.userName+' [商家]';
									this.dfuinfo = item;
								}
							} else if (item.customInfo.identity == '3') {
								this.riderinfo = item;
								if(this.type==1){//单聊
									this.dftype = 3;
									this.IMtitle = item.userName+' [骑手]';
									this.dfuinfo = item;
								}
							} else if (item.customInfo.identity == '4') {
								this.serviceinfo = item;
								if(this.type==1){//单聊
									this.dftype = 4;
									this.IMtitle = item.userName+' [客服]';
									this.dfuinfo = item;
								}
							}
						}
					});
				});
			},
			//打电话
			catphone() {
				if(this.type==1){//单聊
					let dfuinfo = this.dfuinfo;
					let callphone = "";
					switch (this.dftype) {
						case 2:
							callphone = dfuinfo.customInfo.stel;
							break;
						case 3:
							callphone = dfuinfo.customInfo.rtel;
							break;
						case 4:
							callphone = dfuinfo.customInfo.utel;
							break;
						case 1:
							callphone = dfuinfo.customInfo.utel;
							break;
						default:
					};
					if (callphone) {
						uni.makePhoneCall({
							phoneNumber: callphone,
						})
					} else {
						uni.showToast({
							title: '未设置电话,获取电话失败',
							icon: "none"
						})
					}
				}else if(this.type==2){
					uni.showActionSheet({
						itemList: ['用户电话','客服电话','骑手电话'],
						success: (res) => {
							let sleectindex = res.tapIndex;
							let callphone = '';
							switch (sleectindex) {
								case 2:
									let riderinfo = this.riderinfo;//骑手
									if (riderinfo.customInfo) {
										if (riderinfo.customInfo.identity == '3') {
											callphone = riderinfo.customInfo.rtel;
										}
									}
									break;
								case 1:
									let serviceinfo = this.serviceinfo;//客服
									if (serviceinfo.customInfo) {
										if (serviceinfo.customInfo.identity == '4') {
											callphone = serviceinfo.customInfo.utel;
										}
									}
							  break;
								case 0:
									let Userinformation = this.Userinformation;//用户
									if (Userinformation.customInfo) {
										if (Userinformation.customInfo.identity == '1') {
											callphone = Userinformation.customInfo.utel;
										}
									}
									break;
								default:
							};
							if (callphone) {
								uni.makePhoneCall({
									phoneNumber: callphone,
								})
							} else {
								this.$api.msg('未设置电话,获取电话失败');
							}
						},
						fail: (res) => {
							
						}
					});
				}
				
			},
			//查看订单
			toorderinfo() {
				console.info('查看订单详情');
				let order_id = this.groupInfodata.customInfo.order_id;
				let order_type = this.groupInfodata.customInfo.order_type;
				let tourl = "";
				if (order_id) {
					switch(order_type) {
						case 'ele':
						  tourl = `/pages/order/detail/detail?id=${order_id}`
						  break;
						case 'goods':
						  tourl = `/pages/order/shoporderdetail/shoporderdetail?order_id=${order_id}`
						  break;
						case 'hotel':
						  tourl = '/pages/hotelOrderDetaile/hotelOrderDetaile?order_id='+order_id+'&shop=shop'
						  break;
						default:
					}
					if(tourl==''){
						return false;
					}
					wx.navigateTo({
						url: tourl,
					})
				}else{
					this.$api.msg("信息有误");
				}
			},
			//返回上一页
			goback() {
				uni.navigateBack({})
			},
			//选中表情后 加入输入框内
			addEmoji(emgi) {
				this.content += emgi.alt;
			},
			//发送图片消息 选择图片
			chooseImagefun(type) {
				// #ifdef H5
				this.$api.msg("H5暂不支持图片消息");
				return false;
				// #endif
				//type 1 相机 2 相册
				//album 从相册选图，camera 使用相机，默认二者都有。如需直接开相机或直接选相册，请只使用一个选项
				let sourceType = type == 1 ? "camera" : "album";
				uni.chooseImage({
					count: 6,
					sourceType: [sourceType],
					success: (res) => {
						//----------循环发送图片 开始------------------
						for (let i = 0; i < res.tempFilePaths.length; i++) {
							// var imgPath = res.tempFilePaths[0];
							var imgPath = res.tempFilePaths[i];
							let tempFilePaths = res;
							//#ifdef APP-PLUS
							let imagePath = plus.io.convertLocalFileSystemURL(imgPath); //原始路径
							if (this.type == 1) {
								//发送图片消息方法 （单聊）
								txIm.sendImageMessage({
									"path": imagePath, //这个要传 ?
									"userId": this.userId,
								}, result => {
									if (result.progress == 100) {
										//图片发送成功
										this.currentMsgId = result.msgId;
										//重新获取消息
										this.baseloadmsg(); //获取单聊历史消息
									} else {
										//result发送图片怎么样了
									}
									//刷新消息...
								});
							} else if (this.type == 2) {
								//发送群聊图片消息
								txIm.sendImageMessage({
									"path": imagePath,
									"groupId": this.groupId
								}, result => {
									if (result.progress == 100) {
										//群聊图片消息发送完成
										this.currentMsgId = result.msgId;
										this.baseloadmsg(); //获取群历史消息
									} else {
										//result发送图片怎么样了
									}
								});
							}
							// #endif
						}
						//----------循环发送图片 结束------------------
					}
				});
			},
			// 发送图片消息end

			//查看图片消息
			showimgdetaile(item) {
				try {
					let url = "";
					// #ifndef APP-PLUS
					if (item.payload.imageInfoArray) {
						url = item.payload.imageInfoArray[0].url
					};
					// #endif
					// #ifdef APP-PLUS
					//两种形式的图片
					//item.imageElem.path
					//item.imageElem.path
					if (item.imageElem) {
						if (item.imageElem.path) {
							if (item.imageElem.path.indexOf("http") != -1) {
								url = item.imageElem.path;
							} else {
								url = "file://" + item.imageElem.path;
							}
						}

					}
					//网络资源图片
					if(item.url_imageList){
						if(item.url_imageList.length!=0){
							url = item.url_imageList[0].url;
						}
					}
					// #endif

					uni.previewImage({
						urls: [url],
					});
				} catch (err) {
					this.$api.msg(String(err))
				}
			},
			// 查看图片end
			//APP 设置消息未已读
			markC2CMessageAsReadfun() {
				txIm.markC2CMessageAsRead({
					"userId": this.userId,
				}, result => {
					//APP单聊消息设置已读成功
				})
			},
			//设置群里为已读
			markGroupMessageAsRead() {
				txIm.markGroupMessageAsRead({
					"groupId": this.groupId
				}, result => {
					//群聊消息设置已读成功
				})
			},
			//----------------------语音消息-----------------------------
			//录音开始UI效果
			recordBegin(e) {
				this.recording = true;
				this.voiceTis = '松开 结束';
				this.recordLength = 0;
				this.recordTimer = setInterval(() => {
					this.recordLength++;
				}, 1000)
			},
			// 录音被打断
			voiceCancel() {
				this.recording = false;
				this.voiceTis = '按住 说话';
				this.recordTis = '手指上滑 取消发送'
				this.willStop = true; //不发送录音
				this.RECORDER.stop(); //录音结束
			},
			// 录音开始
			voiceBegin(e) {
				if (e.touches.length > 1) {
					return;
				}
				this.initPoint.Y = e.touches[0].clientY;
				this.initPoint.identifier = e.touches[0].identifier;
				this.RECORDER.start({
					format: "mp3"
				}); //录音开始,

			},
			// 录音中(判断是否触发上滑取消发送)
			voiceIng(e) {
				if (!this.recording) {
					return;
				}
				let touche = e.touches[0];
				//上滑一个导航栏的高度触发上滑取消发送
				if (this.initPoint.Y - touche.clientY >= uni.upx2px(100)) {
					this.willStop = true;
					this.recordTis = '松开手指 取消发送'
				} else {
					this.willStop = false;
					this.recordTis = '手指上滑 取消发送'
				}
			},
			//录音结束(回调文件) 结束语音
			recordEnd(e) {
				//录音结束(回调文件) 结束语音
				clearInterval(this.recordTimer);
				if(this.recordLength<2){
					this.$api.msg("说话时间太短！");
					this.willStop = false;
					return false;
				}
				
				
				if (!this.willStop) {
					let eee = e;
					//#ifdef APP-PLUS
					let msg = {
						length: 0,
						url: e.tempFilePath,
						upurl: plus.io.convertLocalFileSystemURL(e.tempFilePath)
					}
					// #endif

					//#ifndef APP-PLUS
					let msg = {
						length: 0,
						url: e.tempFilePath,
						upurl: e.tempFilePath, //不是app不用
					}
					// #endif

					let min = parseInt(this.recordLength / 60);
					let sec = this.recordLength % 60;
					min = min < 10 ? '0' + min : min;
					sec = sec < 10 ? '0' + sec : sec;
					// msg.length = min+':'+sec;
					msg.length = this.recordLength;
					//把发送的消息同步到数据库
					// #ifdef APP-PLUS
					let obj = {};
					if (this.type == 1) {
						//单聊
						obj.userId = this.userId;
					} else if (this.type == 2) {
						//群聊
						obj.groupId = this.groupId;
					}
					//发送语音消息
					txIm.sendSoundMessage({
						"path": msg.upurl,
						...obj,
						"duration": msg.length
					}, result => {
						//同步消息
						if (result.code == 0) {
							//发送语音消息完成
							this.currentMsgId = result.msgId;
							this.baseloadmsg();

						}
					});

					// #endif
				} else {
					this.$api.msg("取消发送录音");
				}
				this.willStop = false;
			},
			// 结束录音
			voiceEnd(e) {
				if (!this.recording) {
					return;
				}
				this.recording = false;
				this.voiceTis = '按住 说话';
				this.recordTis = '手指上滑 取消发送'
				this.RECORDER.stop(); //录音结束
			},
			//播放mp3 APP的
			bofangmp3(item) {
				let url = '';
				if (item.mp3file) {
					url = item.mp3file.path;
				}

				if (item.SoundUrl) { //网络资源
					url = item.SoundUrl.url;
				}
				let mp3url = "";
				if (url.indexOf("http") != -1) {
					//连接
					mp3url = url;
				} else {
					mp3url = "file://" + String(url);
				}
				let src = mp3url;
				if (item.payload) {
					if (item.payload.remoteAudioUrl) {
						src = item.payload.remoteAudioUrl
					}
				}
				innerAudioContext.stop(); //结束之前的播放
				if (this.mp3msgId) {
					this.mp3msgId = "";
					return false;
				}
				innerAudioContext = uni.createInnerAudioContext();
				innerAudioContext.autoplay = true;
				innerAudioContext.src = src;
				innerAudioContext.onPlay(() => {
					//开始播放
					// #ifdef APP-PLUS
					this.mp3msgId = item.msgId;
					// #endif
					// #ifndef APP-PLUS
					this.mp3msgId = item.ID;
					// #endif
				});
				innerAudioContext.onError((res) => {
					//播放错误
					this.mp3msgId = "";
					// this.$api.msg("消息文件已经丢失");
				});
				innerAudioContext.onEnded((res) => {
					//播放完成
					this.mp3msgId = "";
				});

			},
			//----------------------语音消息 end-----------------------------
			//获取消息的高度
			getscrollviewmain() {
				setTimeout(() => {
					let view = uni.createSelectorQuery().select(".chatboxinps");
					view.boundingClientRect((data) => {
						//获取固定尾部的高度=data.height
						// that.style.footViewHeight = data.height
						this.scrollInputh = data.height * 2 + 20;
						this.ToTheBottom();
					}).exec();
				}, 500)
			},
			//发送自定义消息
			sendC2CCustomMessagefun(sendtype) {
				/**
				 * type
				 * 1.发送产品信息
				 * 2.订单结束消息 不可在聊天
				 * 3.邀请用户去评价消息
				 * 
				 * */

				let objcan = {};
				let sendstr = "";
				if (sendtype == 1) {
					objcan.goods_id = 0;
					objcan.shop_id = 0;
					objcan.type = sendtype;
					sendstr = JSON.stringify(objcan);
				} else if (sendtype == 2) {
					objcan.type = sendtype;
					objcan.order_id = 0; //订单id
					objcan.order_status = 0; //状态
					objcan.ordertype = 1; //区分商城还是外卖
					sendstr = JSON.stringify(objcan);
				}

				//转成字符串格式 两种格式  一种是字符串格式 一种是字符串json
				var parsestar = "";
				for (var i in objcan) {
					parsestar += (i + '|' + objcan[i] + ';');
				}

				if (this.type == 1) {
					//发送单聊自定义消息
					txIm.sendC2CCustomMessage({
						"customMsg": String(sendtype),
						"userId": this.userId,
						desc: sendstr,
						extension: parsestar
					}, result => {
						if (result.code == 0) {
							this.currentMsgId = result.msgId;
							this.baseloadmsg();
						}
					});
				} else if (this.type == 2) {
					//发送群自定义消息
					txIm.sendGroupCustomMessage({
						"customMsg": String(sendtype),
						"groupId": this.groupId,
						"priority": 0,
						desc: sendstr,
						extension: parsestar
					}, result => {
						if (result.code == 0) {
							this.currentMsgId = result.msgId;
							this.baseloadmsg();
						}
					})
				}
			},
			//通过自定义消息进入链接
			tomsglink(item){
				//item.customdata.applink 
				//item.customdata.wechatlink
				//s_link
				if(item.customdata.istab==1){
					uni.switchTab({
						url:item.customdata.s_link
					})
				}else{
					uni.navigateTo({
						url:item.customdata.s_link ,
					})
				}
			}
		}
	}
</script>

<style lang="scss">
	@import "./global.scss";
</style>
