<style>
	.view-pop {
		position: fixed;
		width: 100%;
		height: 100%;
		top: 0;
		left: 0;
		z-index: 999;
	}

	.view-pop .bg {
		background: rgba(0, 0, 0, 0.5);
		width: 100%;
		height: 100%;
		top: 0;
		left: 0;
		position: absolute;
	}

	.view-pop .pop-view {
		background: #fff;
		padding: 10px;
		display: inline-block;
		position: absolute;
		right: 10px;
		top: 40px;
		border-radius: 6px;
	}

	.view-pop .pop-view .item {
		padding: 10px;
	}

	.view-pop .pop-view image {
		width: 20px;
		height: 20px;
		margin-right: 4px;
	}

	.view-pop .pop-view .pop-lv {
		width: 0;
		height: 0;
		border-left: 10px solid transparent;
		border-right: 10px solid transparent;
		border-bottom: 10px solid #fff;
		position: absolute;
		top: -9px;
		right: 3px;
	}
</style>
<template>
	<view class="app">
		<view id="app-top">
			<uni-nav-bar statusBar backgroundColor="#f8f8f8" title="聊天">
				<view slot="right" @tap="isPop = true" v-if="sysData.is_audit == 0">
					<image style="width: 20px;" src="/static/chat/chat-add.png" mode="widthFix"></image>
				</view>

				<view class="fx-r fx-bc fx-ac" style="width: 100%;">
					<view class="fx-r fx-bc fx-ac" v-if="isNetwork">
						<u-loading-icon size="18"></u-loading-icon>
						<text style="font-size: 14px;margin-left: 4px;">链接中..</text>
					</view>
					<text v-else style="text-overflow: ellipsis;white-space: nowrap;overflow: hidden;font-size: 14px;">
						聊天
					</text>
				</view>

			</uni-nav-bar>

			<view class="lists fx-r" v-if="sysData.is_audit == 0">
				<view class="item fx-h fx-bc" @tap="tapOpen" data-url="apply/list">
					<image src="/static/chat/ic_add_friend.png" mode="widthFix"></image>
					<view class="info fx-h fx-ac">
						<view class="title">申请列表</view>
					</view>
					<view class="flg" v-if="txbagenum != null && txbagenum.applyCount > 0">{{txbagenum.applyCount}}
					</view>
				</view>
				<view class="item fx-h fx-bc" @tap="$refs.customer.open()">
					<image src="/static/chat/ic_customer_chat.png" mode="widthFix"></image>
					<view class="info fx-h fx-ac">
						<view class="title">我的客服</view>
					</view>
				</view>
				<view class="item fx-h fx-bc" @tap="tapOpen" data-url="group/list">
					<image src="/static/chat/ic_me_group_chat.png" mode="widthFix"></image>
					<view class="info fx-h fx-ac">
						<view class="title">我的群聊</view>
					</view>
				</view>
				<view class="item fx-h fx-bc" @tap="tapOpen" data-url="friend/index">
					<image src="/static/chat/ic_customer_chat.png" mode="widthFix"></image>
					<view class="info fx-h fx-ac">
						<view class="title">我的好友</view>
					</view>
				</view>

			</view>


			<view v-if="data.length > 0" class="tb-search fx-r fx-bc" @tap="tapOpen" data-url="search">
				<image src="/static/chat/tb-seach.png"></image>
				<view>搜索联系人</view>
			</view>
		</view>
		<view class="view-pop" v-if="isPop">
			<view class="bg" @tap="isPop = false"></view>
			<view class="pop-view">
				<view class="pop-lv"></view>
				<view class="item fx-r fx-bc" @tap="tapOpen" data-url="group/add">
					<image src="/static/chat/news_icon_initiategroupchat.png"></image>创建群聊
				</view>
				<view class="item fx-r fx-bc" @tap="tapOpen" data-url="./friend/add">
					<image src="/static/chat/news_icon_addfriend.png"></image>
					添加好友
				</view>
				<view class="item fx-r fx-bc" @tap="tapSan">
					<image src="/static/chat/news_icon_saoyisao.png"></image>
					扫一扫
				</view>
			</view>
		</view>

		<scroll-view v-if="user != null" scroll-y
			:style="'height: calc(100vh - 50px - ' +  barheight + 'px - ' +  footHeight + 'px);'">


			<view v-if="data.length > 0">
				<view @tap.stop="tapOpenChat(item)" @longtap="taploogView" :data-id="index"
					:class="{topchat : item.is_top == 1}" class="chat-list fx-r fx-bc" v-for="(item,index) in data">
					<view class="dot" v-if="item.read_count > 0">{{item.read_count}}</view>
					<view class="hot" v-if="item.type == 'group_chat'">群</view>
					<view class="avatar">
						<image mode="aspectFill" :src="utils.getAvatar(item.img,item.type)"></image>
					</view>


					<view class="chat-info fx-r">
						<view class="info fx-h">
							<view class="fx-r">
								<text class="nickname">{{item.name}}</text>
								<view class="fx-g1"></view>
								<view class="time" v-if="item.time != ''">{{utils.timeLastdate(item.msg_time,true)}}
								</view>
							</view>

							<view class="tag_value" v-if="item.type == 'chat'">
								<text class="value" v-if="item.msg_type == 'tip'">
									{{item.msg_data}}
								</text>
								<!-- //消息红包 -->
								<text class="value" v-if="item.msg_type == 'red_envelope'">
									<rich-text class="title" :nodes="unDataChat(item,'red_envelope')"></rich-text>
								</text>
								<!-- //红包领取情况 -->
								<text class="value" v-if="item.msg_type == 'red_envelope_tip'">
									<rich-text class="title" :nodes="unDataChat(item,'red_envelope_tip')"></rich-text>
								</text>


								<!-- //文字聊天 -->
								<text class="value" v-if="item.msg_type == 'voice'">
									[语音文件]
								</text>

								<!-- //红包转账 -->
								<text class="value" v-if="item.msg_type == 'red_envelope_transfer'">
									<rich-text class="title"
										:nodes="unDataChat(item,'red_envelope_transfer')"></rich-text>
								</text>

								<!-- //文字聊天 -->
								<text class="value" v-if="item.msg_type == 'withdraw'">
									撤回消息
								</text>

								<!-- //红包退回 -->
								<text class="value" v-if="item.msg_type == 'red_envelope_transfer_back'">
									<rich-text class="title"
										:nodes="unDataChat(item,'red_envelope_transfer_back')"></rich-text>
								</text>

								<!-- //文字聊天 -->
								<text class="value" v-if="item.msg_type == 'text'">
									{{item.msg_text}}
								</text>

								<!-- //语音聊天 -->
								<text class="value" v-if="item.msg_type == 'voice'">
									<rich-text class="title" :nodes="unDataChat(item,'voice')"></rich-text>
								</text>

								<!-- //图片 -->
								<text class="value" v-if="item.msg_type == 'img'">[图片]</text>
							</view>

							<view class="tag_value" v-if="item.type == 'group_chat'">
								<text class="value" v-if="item.msg_type == 'tip'">
									{{item.msg_data}}
								</text>
								<!-- //消息红包 -->
								<text class="value" v-if="item.msg_type == 'red_envelope'">
									<rich-text class="title" :nodes="unDataGroupChat(item,'red_envelope')"></rich-text>
								</text>
								<!-- //红包领取情况 -->
								<text class="value" v-if="item.msg_type == 'red_envelope_tip'">
									<rich-text class="title"
										:nodes="unDataGroupChat(item,'red_envelope_tip')"></rich-text>
								</text>

								<!-- //红包转账 -->
								<text class="value" v-if="item.msg_type == 'red_envelope_transfer'">
									<rich-text class="title"
										:nodes="unDataGroupChat(item,'red_envelope_transfer')"></rich-text>
								</text>

								<!-- //红包退回 -->
								<text class="value" v-if="item.msg_type == 'red_envelope_transfer_back'">
									<rich-text class="title"
										:nodes="unDataGroupChat(item,'red_envelope_transfer_back')"></rich-text>
								</text>

								<!-- //文字聊天 -->
								<text class="value" v-if="item.msg_type == 'text'">
									{{item.msg_text}}
								</text>

								<!-- //文字聊天 -->
								<text class="value" v-if="item.msg_type == 'withdraw'">
									撤回消息
								</text>

								<!-- //文字聊天 -->
								<text class="value" v-if="item.msg_type == 'group_text'">
									[群公告]{{item.msg_data}}
								</text>


								<!-- //语音聊天 -->
								<text class="value" v-if="item.msg_type == 'voice'">
									<rich-text class="title" :nodes="unDataGroupChat(item,'voice')"></rich-text>
								</text>

								<!-- //图片 -->
								<text class="value" v-if="item.msg_type == 'img'">[图片]</text>
								<view class="tipat" v-if="item.is_remind > 0">[有人@你]</view>

							</view>

							<view class="item-tip" v-if="item.not_red > 0">未领{{item.not_red}}个</view>


						</view>
					</view>
				</view>
				<view style="height: 10px;"></view>
			</view>
			<view class="user-hg fx-h fx-bc fx-ac" v-else>
				<image src="/static/chat/default_img_bud.png" mode="widthFix"></image>
				<view class="text">暂无消息内容</view>
			</view>



		</scroll-view>


		<view v-else :style="'height: calc(100vh - 50px - ' +  barheight + 'px);'" class="user-bann fx-h fx-bc fx-ac">
			<view class="tips">你还未登录，请点击登录查看</view>
			<view class="btn" @tap="tapLogin" style="margin-top: 10px;">立即登录</view>
		</view>
		<view class="mb2-tip" v-if="showIndex >= 0">
			<view class="bg" @tap="showIndex = -1"></view>
			<view class="pop-view" :style="'left:' + showLeft+ 'px;top:' + showTop + 'px'">
				<view class="pop-lv"></view>
				<view class="item fx-r fx-bc" @tap="tapZding">{{ data[showIndex].is_top == 1 ? '取消置顶' : '置顶该聊天' }}
				</view>
				<view class="item fx-r fx-bc" @tap="tapRead">标记已读</view>
				<view class="item fx-r fx-bc" @tap="tapDel">删除该聊天</view>
			</view>
		</view>

		<customer-wiget ref="customer"></customer-wiget>
	</view>
</template>
<style lang="scss">
	.mb2-tip {
		position: fixed;
		width: 100%;
		height: 100%;
		top: 0;
		left: 0;
		z-index: 999;
	}

	.mb2-tip .bg {
		width: 100%;
		height: 100%;
		top: 0;
		left: 0;
		position: absolute;
	}

	.mb2-tip .pop-view {
		position: absolute;
		background: #fff;
		border-radius: 6px;
		border: 1px solid #f1f1f1;
		padding: 10px 20px;
		top: 56px;
		z-index: 9;
		left: 20px;
	}

	.mb2-tip .pop-view .item {
		padding: 10px 0;
	}

	.mb2-tip .pop-view .item:active {
		background: #f1f1f1;
	}

	.tb-search {
		margin: 10px;
		background: #fff;
		padding: 5px 10px;
		border-radius: 8px;
		color: $ic-default-text;
		font-size: 14px;
	}

	.tb-search image {
		width: 30px;
		height: 30px;
	}

	.user-hg {
		height: 100%;
	}

	.user-hg image {
		width: 200px;
	}

	.user-hg .text {
		font-size: 14px;
		margin: 10px;
	}


	.lists {
		margin-top: 10px;
		background: #fff;
	}

	.lists .item {
		padding: 10px 0;
		position: relative;
		width: 25%;
	}

	.lists .item:active {
		background: #f1f1f1;
	}

	.lists .item image {
		width: 50px;
		height: 50px;
		border-radius: 50%;
	}

	.lists .item .info {
		font-size: 12px;
		color: #787878;
		margin-top: 5px;
	}

	.lists .item .flg {
		background: #ff5857;
		width: 20px;
		height: 20px;
		border-radius: 50%;
		font-size: 10px;
		text-align: center;
		line-height: 20px;
		color: #fff;
		right: 14px;
		top: 0;
		position: absolute;
	}





	.chat-list {
		background: #fff;
		padding: 10px 15px;
		position: relative;
	}

	.chat-list .hot {
		position: absolute;
		border: 1px solid #faac06;
		border-radius: 6px;
		font-size: 10px;
		padding: 0px;
		color: #faac06;
		background: #fff;
		width: 15px;
		text-align: center;
		z-index: 9;
		top: 12px;
	}

	.chat-list:active {
		background: #f1f1f1;
	}

	.chat-list.topchat {
		background: #f1f1f1;
	}

	.chat-list .avatar {
		width: 45px;
		height: 45px;
		border-radius: 6px;
		background: #f1f1f1;
	}

	.chat-list .avatar image {
		width: 100%;
		height: 100%;
		border-radius: 6px;
	}

	.chat-list .chat-info {
		width: calc(100% - 55px);
		margin-left: 10px;
		height: 45px;
		padding-bottom: 4px;
	}

	.chat-list:last-child .chat-info {
		border-bottom: 0;
	}

	.chat-list .dot {
		overflow: hidden;
		text-overflow: ellipsis;
		-webkit-line-clamp: 1;
		position: absolute;
		z-index: 9;
		text-align: center;
		width: 20px;
		height: 20px;
		font-size: 10px;
		color: #fff;
		background: orangered;
		border-radius: 20px;
		line-height: 20px;
		top: 2px;
		left: 45px;
	}

	.chat-list text.nickname {
		color: #3b4144;
		font-size: 14px;
	}

	.chat-list .tag_value {
		margin-top: 3px;
		overflow: hidden;
		text-overflow: ellipsis;
		display: flex;
		-webkit-line-clamp: 1;
		-webkit-box-orient: vertical;
	}

	.chat-list text.value {
		color: #999;
		font-size: 12px;
		font-weight: normal;
	}

	.chat-list .chat-info .info {
		width: 100%;
	}

	.chat-list .chat-info .time {
		font-size: 12px;
		color: #999;
	}

	.tips {
		font-size: 14px;
		color: #787878;
	}

	.btn {
		background: $ic-appcolor;
		font-size: 14px;
		color: #fff;
		width: 160px;
		border-radius: 20px;
		height: 40px;
		text-align: center;
		line-height: 40px;
	}

	.item-tip {
		position: absolute;
		font-size: 12px;
		bottom: 16px;
		right: 10px;
		color: orange;
	}

	.tipat {
		font-size: 12px;
		color: orange;
	}
</style>


<script>
	let reqrcode = require("@/components/scancode/reqrcode.js");
	import customerWiget from '@/components/ui-public/customer-wiget.vue';
	import {
		mapState,
		mapMutations
	} from 'vuex';
	export default {
		computed: mapState(['user', 'sysData', 'txbagenum']),
		components: {
			customerWiget
		},
		data() {
			return {
				isNetwork: false,
				data: [],
				barheight: 0,
				isPop: false,
				showIndex: -1,
				showLeft: 0,
				showTop: 0,
				footHeight: 0,
				clickItem: {}, //点击栏目的项目
				customer: {},
				isLoad: false
			}
		},

		onLoad(option) {
			this.$nextTick(() => {
				uni.createSelectorQuery().select("#app-top").boundingClientRect(res => {
					this.barheight = res.height + 20;
				}).exec();
			});
			// #ifdef H5
			this.footHeight = 60;
			// #endif
			uni.$on('socketMessage', this.socketMessage);
			uni.$on('h5San', this.h5San);
			uni.$on('chatClear', this.chatClear);
			uni.$on('chatRead', this.chatRead);
			uni.$on('socketOpen', this.socketOpen);
			uni.$on('socketClose', this.socketClose);
		},

		onShow() {
			if (this.user != null) {
				this.getData();
			}
		},
		onUnload() {
			uni.$off('socketMessage', this.socketMessage);
			uni.$off('h5San', this.h5San);
			uni.$off('chatClear', this.chatClear);
			uni.$off('socketOpen', this.socketOpen);
			uni.$off('socketClose', this.socketClose);
		},
		methods: {
			...mapMutations(['checkUserLogin', 'setSys', 'setTxbagenum']),
			getData: function() {
				if (this.user == null) {
					return;
				}
				if (this.isLoad) {
					return;
				}
				this.isLoad = true;
				this
					.request
					.get("chatList")
					.then(res => {
						this.isLoad = false;
						if (res.code == 200) {
							this.data = res.data;
							this.inBagr();
						}
					});
			},
			/**
			 * 扫二维码
			 */
			tapSan: function() {

				this.isPop = false;
				// #ifdef H5
				uni.navigateTo({
					url: "../scan/h5scan?type=chat"
				});
				// #endif

				// #ifndef H5
				const that = this;
				let p = uni.getSystemInfoSync().platform;
				if (p === "ios") {
					uni.scanCode({
						success: (res) => {
							that.h5San({
								type: 'chat',
								text: res.result
							});
						}
					});
				} else {
					that.$store.dispatch('permission/requestPermissions', 'WRITE_EXTERNAL_STORAGE').then(res => {
						uni.scanCode({
							success: (res) => {
								that.h5San({
									type: 'chat',
									text: res.result
								});
							}
						});
					});
				}
				// #endif

			},
			h5San: function(data) {
				if (data.type == 'chat') {
					if (data.text.toLowerCase().indexOf("/api/pub/chat_invitation") >= 0) {
						var strCode = data.text.substr(data.text.indexOf("/api/pub/chat_invitation"), data.text
						.length);
						strCode = strCode.replace("/api/pub/chat_invitation?token=", "");
						uni.navigateTo({
							url: "group/groupInvite?code=" + encodeURIComponent(strCode)
						})
						return;
					}

					if (data.text.toLowerCase().indexOf("cb:") >= 0) {
						var strCode = data.text.substr(3, data.text.length);
						console.log(strCode);
						uni.showLoading({
							title: "加载中.."
						});
						this
							.request
							.post("FriendFindCode", {
								usercode: strCode
							})
							.then(res => {
								if (res.code == 200) {
									uni.navigateTo({
										url: "../book/friend/info?usercode=" + res.msg
									})
								} else {
									uni.showModal({
										title: '系统提示',
										content: res.msg,
										showCancel: false
									});
								}
							});
					}
				}
			},
			/**
			 * 处理数据
			 * @param {Object} item 
			 * @param {Object} type 
			 */
			unDataChat: function(item, type) {

				let dataAr = JSON.parse(item.msg_data);
				//红包转账
				if (type == 'red_envelope_transfer') {
					return `<font style="color:#ec7259">${dataAr['name']}</font>`;
				}
				//普通红包
				if (type == 'red_envelope') {
					return `<font style="color:#ec7259">[红包]${dataAr['name']}</font>`;
				}

				//普通红包
				if (type == 'red_envelope_transfer_back') {
					return `来${dataAr['send']['name']}[转账]`;
				}

				//领取状态
				if (type == 'red_envelope_tip') {
					if (dataAr.send.uid == this.user.uid) {
						return dataAr.lq.name + "领取您的红包";
					} else {
						return "你领取" + dataAr.send.name + "红包";
					}
				}
			},
			/**
			 * 群聊数据	
			 * @param {Object} item
			 * @param {Object} type
			 */
			unDataGroupChat: function(item, type) {

				//红包转账
				if (type == 'red_envelope_transfer') {
					let dataAr = JSON.parse(item.msg_data);
					return `<font style="color:#ec7259">${dataAr['name']}</font>`;
				}
				//普通红包
				if (type == 'red_envelope') {
					let dataAr = JSON.parse(item.msg_data);
					return `<font style="color:#ec7259">[红包]${dataAr['name']}</font>`;
				}

				//普通红包
				if (type == 'red_envelope_transfer_back') {
					let dataAr = JSON.parse(item.msg_data);
					return `来${dataAr['send']['name']}[转账]`;
				}
				//领取状态
				if (type == 'red_envelope_tip') {
					let dataAr = JSON.parse(item.msg_data);
					if (dataAr.send.uid == this.user.uid) {
						return dataAr.lq.name + "领取您的红包";
					} else {
						return "你领取" + dataAr.send.name + "红包";
					}
				}

				if (type == 'voice') {
					return '<font style="color:#ec7259">[语音文件]</font>';
				}
			},
			/**
			 * 打开  
			 * @param {Object} ev
			 */
			tapOpen: function(ev) {
				if (this.user == null) {
					this.tapLogin();
					return;
				}
				let url = ev.currentTarget.dataset.url;
				console.log(url);
				this.isPop = false;
				this.utils.navigateTo(url);
			},
			taploogView: function(ev) {
				var index = ev.currentTarget.dataset.id;
				var left = ev.touches[0].pageX;
				var top = ev.touches[0].clientY;
				this.showIndex = index;
				var leftW = this.$device.screenWidth - left;
				var topW = this.$device.screenHeight - top;
				this.showLeft = leftW < 190 ? (left - (190 - leftW)) : left;
				this.showTop = topW < 250 ? (top - (250 - topW)) : top;
			},
			/**
			 * 置顶设置
			 */
			tapZding: function() {
				var item = this.data[this.showIndex];
				this
					.request
					.post("chatUpdateChat", {
						groupId: item.group_id,
						code: "is_top",
						val: item.is_top == 1 ? 0 : 1
					})
					.then(res => {
						if (res.code == 200) {
							this.getData();
							this.utils.Tip("操作成功");
						} else {
							uni.showModal({
								title: '系统提示',
								content: res.msg,
								showCancel: false
							});
						}
					});
				this.showIndex = -1;
			},
			/**
			 * 数据阅读
			 */
			tapRead: function() {
				var item = this.data[this.showIndex];
				this
					.request
					.post("chatRead", {
						groupId: item.group_id
					})
					.then(res => {
						if (res.code == 200) {
							this.getData();
							this.utils.Tip("操作成功");
						} else {
							uni.showModal({
								title: '系统提示',
								content: res.msg,
								showCancel: false
							});
						}
					});
				this.showIndex = -1;
			},
			//删除
			tapDel: function() {
				var item = this.data[this.showIndex];
				this
					.request
					.post("chatDel", {
						groupId: item.group_id
					})
					.then(res => {
						if (res.code == 200) {
							this.getData();
							this.utils.Tip("操作成功");
						} else {
							uni.showModal({
								title: '系统提示',
								content: res.msg,
								showCancel: false
							});
						}
					});
				this.showIndex = -1;
			},
			/**
			 * 打开chat
			 * @param {Object} ev
			 */
			tapOpenChat: function(item) {
				this.clickItem = item;
				if (item.type == 'chat') {
					uni.navigateTo({
						url: 'chat?groupId=' + item.group_id + '&usercode=' + item.f_uid
					})
				}

				if (item.type == 'group_chat') {
					uni.navigateTo({
						url: 'chatGroup?groupId=' + item.group_id + '&usercode=' + item.f_uid
					})
				}
			},
			/**
			 * 通讯数据
			 * @param {Object} res
			 */
			socketMessage: function(res) {
				if (res.code == null) return;
				var uData = JSON.parse(res.data);

				var bool = false;
				for (var i in this.data) {
					var data = this.data[i];
					if (data.group_id == uData.group_id) {
						bool = true;
						data.msg_data = uData['data'];
						data.msg_type = uData['type'];
						data.msg_time = uData['time'];
						data.read_count += 1;
						this.$set(this.data, i, data);
					}
				}
				this.getData();
			},

			socketOpen: function() {
				this.isNetwork = false;
				this.getData();
			},
			/**
			 * 网络关闭 | 需重新链接
			 */
			socketClose: function() {
				this.isNetwork = true;
			},
			/**
			 * 【清理】预读消息
			 */
			chatRead: function(data) {
				let txbagenum = this.txbagenum;
				var read_count = 0;
				for (var i in this.data) {
					var inAr = this.data[i];
					if (inAr.group_id == data.groupId) {
						read_count = inAr.read_count;
						inAr.read_count = 0;
						this.$set(this.data, i, inAr);
						break;
					}
				}
				txbagenum.chatCount -= read_count;
				if (txbagenum.chatCount <= 0) txbagenum.chatCount = 0;
				console.log(txbagenum);
				this.setTxbagenum(txbagenum);
			},

			chatClear: function(group_id) {
				for (var i in this.data) {
					var data = this.data[i];
					if (data.group_id == group_id) {
						data.data = "";
						this.$set(this.data, i, data);
					}
				}
			},

			tapLogin: function() {
				uni.navigateTo({
					url: "../login/index"
				});
			},

			inBagr: function() {
				//消息提示值
				this.request.get("chatBagenum").then(res => {
					if (res.code == 200) {
						this.setTxbagenum(res.data);
					}
				}).catch(err => {});
			},
			tapKf: function() {
				if (this.user == null) {
					this.tapLogin();
					return;
				}
				if (this.customer != null) {

					if (this.customer.group_id > 0) {
						uni.navigateTo({
							url: 'chat?groupId=' + this.customer.group_id + '&usercode=' + this.customer.uid
						})
					} else {
						uni.navigateTo({
							url: "friend/info?usercode=" + this.customer.uid
						});
					}
				}

			}
		}
	}
</script>