<template>
	<view :class="$store.state.AppStyle" style="background-color: #f6f6f6;">
		<view class="header" :style="[{height:CustomBar + 'px'}]">
			<view class="cu-bar bg-white" :style="{'height': CustomBar + 'px','padding-top':StatusBar + 'px'}">
				<view class="action" @tap="back">
					<text class="cuIcon-back"></text>
				</view>
				<view class="content text-bold" :style="[{top:StatusBar + 'px'}]">
					群聊助手
				</view>
				<view class="action">

				</view>
			</view>
		</view>
		<view :style="[{padding:NavBar + 'px 10px 0px 10px'}]"></view>
		<view class="data-box">
			<view class="no-data" v-if="token==''">

				<view class="full-noLogin">
					<view class="full-noLogin-main">
						<text class="cuIcon-text"></text>
						<view class="full-noLogin-text">
							请先登录账号
						</view>
						<view class="full-noLogin-btn">
							<view class="text-center margin-top-sm">
								<text class="cu-btn bg-blue radius-50" @tap="goLogin()">登录</text>
								<text class="cu-btn margin-left-sm radius-50 zhuce" @tap="goRegister()">注册</text>
							</view>
						</view>
					</view>
				</view>

			</view>
			<view class="cu-list menu-avatar" v-if="token!=''">
				<view class="cu-bar bg-white search">
					<view class="search-form round">
						<text class="cuIcon-search"></text>
						<input type="text" placeholder="搜索群聊" v-model="searchText"></input>
						<view class="search-close" v-if="searchText!=''" @tap="searchClose()"><text
								class="cuIcon-close"></text></view>
					</view>
				</view>
				<view class="no-data" v-if="chatList.length==0">
					<text class="cuIcon-text"></text>
					暂时没有数据
				</view>
				<block v-for="(item,index) in chatList" :key="index">
					<view class="cu-item" @tap="goChat(item)" v-if="item.name.indexOf(searchText)!=-1">
						<block v-if="item.type==1">
							<view class="cu-avatar round lg" :style="'background-image:url('+item.pic+');'"></view>
						</block>
						<block v-else>
							<view class="cu-avatar round lg" :style="'background-image:url('+item.userJson.avatar+');'">
							</view>
						</block>
						<view class="content">
							<view>
								<view class="text-cut">{{item.name}}</view>
							</view>
							<view class="text-gray text-sm flex">
								<view class="text-cut">
									<block v-if="item.lastMsg!=null">

										<block v-if="item.lastMsg.type!=4">
											<block v-if="item.lastMsg.uid==uid">
												我:
											</block>
											<block v-if="item.lastMsg.uid!=uid">
												{{item.name}}:
											</block>
											<block v-if="item.lastMsg.type==0">
												{{item.lastMsg.text}}
											</block>
											<block v-if="item.lastMsg.type==1">
												[图片]
											</block>
										</block>
										<block v-else>
											<block v-if="item.lastMsg.text=='ban'">
												<text class="text-red">[已开启全体禁言]</text>
											</block>
											<block v-else>
												<text class="text-blue">[已解除全体禁言]</text>
											</block>
										</block>
									</block>
									<block v-else>暂无消息</block>
								</view>
							</view>
						</view>
						<view class="action">
							<view class="text-grey text-xs">{{chatFormatDate(item.lastTime)}}</view>
							<block v-if="item.lastMsg!=null">
								<block v-if="item.lastMsg.uid==uid">
									<view class="cu-tag sm" style="background: none;">&nbsp</view>
								</block>
								<block v-else>
									<view class="cu-tag sm" style="background: none;" v-if="item.isNew==0">&nbsp</view>
									<view class="cu-tag round bg-red sm" v-else>{{item.unRead}}</view>
								</block>
							</block>
							<block v-else>
								<view class="cu-tag sm" style="background: none;">&nbsp</view>
							</block>
						</view>
					</view>
				</block>
			</view>
		</view>
		<!--加载遮罩-->
		<view class="loading" v-if="isLoading==0">
			<view class="loading-main">
				<image src="../../static/loading.gif"></image>
			</view>
		</view>
		<!--加载遮罩结束-->
	</view>
</template>

<script>
	import {
		localStorage
	} from '../../js_sdk/mp-storage/mp-storage/index.js'
	import waves from '@/components/xxley-waves/waves.vue';
	// #ifdef APP-PLUS
	import owo from '../../static/app-plus/owo/OwO.js'
	// #endif
	// #ifdef H5
	import owo from '../../static/h5/owo/OwO.js'
	// #endif
	// #ifdef MP
	var owo = [];
	// #endif
	export default {
		data() {
			return {
				StatusBar: this.StatusBar,
				CustomBar: this.CustomBar,
				NavBar: this.StatusBar + this.CustomBar,
				AppStyle: this.$store.state.AppStyle,
				sectionList: [],
				page: 1,
				swiperList: [],
				submitStatus5: false,
				submitStatus3: false,
				submitStatus2: false,
				submitStatus1: false,
				squareid: 0,
				isLogin: 1,
				metaList: [],
				adimage_sl: 0,
				tagList: [],
				recommendList: [],
				shopList: [],
				rzImg: this.$API.SPRz(),
				Rz: false,
				isvip: 0,
				userList: [],
				tabCurTab: 1,
				spaceDataType: 2,
				uid: 0,
				homeStyle: 0,
				swiperHeight: this.$API.SPfindSwiperHeight(),
				swiperBgcolor: "",
				actStyle: 0,
				Hyperlinks: 0,
				Gallery: 0,
				Findtop: 0,
				Code: 0,
				isLoading: 0,
				kuaijie: 2,
				radiusBoxStyle: 0,
				radiusStyle: 0,
				fatherTitle: 2,
				swiperStyle: false,
				swiperType: 0,
				recommendOf: 0,
				ads: "",
				wzof: 0,
				tzof: 0,
				shopof: 0,
				Bannerswitch: 0,
				searchText: "",
				iconimg: [],
				avatarurl: "../../static/user/avatar.png",
				dataLoad: false,
				spaceLoad: false,
				recommendSectionList: [],
				swiperList2: [],
				chatList: [],
				oldChatList: [],
				identifyCompany: 0,
				curIMG: "",
				bannerAds: [],
				bannerAdsInfo: null,
				noticeSumof: false,
				noticeSum: 0,
				spaceList: [],
				token: "",
				isGetChat: null,
				userInfo: null,
				sy_gpt: false,
				noLogin: false

			}
		},

		onPullDownRefresh() {
			var that = this
			clearInterval(that.msgLoading);
			that.msgLoading = null
			that.page = 1;
			that.getMyChat(false);
			setTimeout(function() {
				uni.stopPullDownRefresh();
			}, 1000);
		},
		onBackPress() {
			var that = this
			clearInterval(that.msgLoading);
			that.msgLoading = null;
		},
		onUnload() {
			var that = this
			clearInterval(that.msgLoading);
			that.msgLoading = null;
		},
		onReachBottom() {
			//触底后执行的方法，比如无限加载之类的
			var that = this;
		},
		onShow() {
			var that = this;
			that.page = 1;
			if (localStorage.getItem('userinfo')) {

				var userInfo = JSON.parse(localStorage.getItem('userinfo'));
				that.uid = userInfo.uid;
			}
			if (localStorage.getItem('token')) {

				that.token = localStorage.getItem('token');
				if (that.token != "") {
					that.getMyChat(false);
					that.isGetChat = setInterval(() => {
						that.getMyChat(false);
					}, 4000);
				}
			}
			that.allCache();

			that.unreadNum();
		},
		onLoad() {
			var that = this;
			// #ifdef APP-PLUS || MP
			that.NavBar = this.CustomBar;
			// #endif


		},
		methods: {
			back() {
				var that = this;
				clearInterval(that.msgLoading);
				that.msgLoading = null
				uni.navigateBack({
					delta: 1
				});
			},
			loadMore() {
				var that = this;

				if (that.isLoad == 0) {

					that.moreText = "正在加载中...";
					that.getMyChat(true);
				}
			},
			searchClose() {
			
				var that = this;
				that.searchText = "";
				that.page = 1;
				that.getUserList(false);
			},
			goChat(data) {
				var that = this;
				var chatid = data.id;
				clearInterval(that.chatLoading);
				that.chatLoading = null
				//去除未读标志
				var chatlist = that.chatList;
				for (var i in chatlist) {
					if (chatlist[i].id == chatid) {
						chatlist[i].isNew = 0;
						chatlist[i].unRead = 0;
					}
				}
				that.chatList = chatlist;
				that.oldChatList = that.chatList;
				localStorage.setItem('AllchatList', JSON.stringify(that.chatList));
				//结束
				if (data.type == 0) {
					var name = data.userJson.name;
					var uid = data.userJson.uid;
			
					uni.navigateTo({
						url: '/pages/chat/chat?uid=' + uid + "&name=" + name + "&chatid=" + chatid + "&type=0"
					});
				}
				if (data.type == 1) {
					var name = data.name;
			
					uni.navigateTo({
						url: '/pages/chat/chat?&name=' + name + '&chatid=' + chatid + '&type=1'
					});
				}
			
			},
			setRead() {
				var that = this;
				that.$Net.request({

					url: that.$API.setRead(),
					data: {
						"token": that.token
					},
					header: {
						'Content-Type': 'application/x-www-form-urlencoded'
					},
					method: "get",
					dataType: 'json',
					success: function(res) {
						if (res.data.code == 1) {
							uni.showToast({
								title: "操作成功！",
								icon: 'none'
							})
							localStorage.setItem('noticeSum', 0);
							var chatList = that.chatList;
							for (var i in chatList) {
								chatList[i].myUnRead = 0;
								chatList[i].otherUnRead = 0;
							}
							that.chatList = chatList;
						}
					},
					fail: function(res) {
						uni.showToast({
							title: "网络开小差了哦",
							icon: 'none'
						})
					}
				})
			},
			chatFormatDate(datetime) {
				var datetime = new Date(parseInt(datetime * 1000));
				// 获取年月日时分秒值  slice(-2)过滤掉大于10日期前面的0
				var year = datetime.getFullYear();
				var month = ("0" + (datetime.getMonth() + 1)).slice(-2);
				var date = ("0" + datetime.getDate()).slice(-2);
				var hour = ("0" + datetime.getHours()).slice(-2);
				var minute = ("0" + datetime.getMinutes()).slice(-2);
				var time = year + "" + month + "" + date;

				var result = hour + ":" + minute;
				var curDate = new Date();
				var curYear = curDate.getFullYear(); //获取完整的年份(4位)
				var curMonth = ("0" + (curDate.getMonth() + 1)).slice(-2);
				var curDay = ("0" + curDate.getDate()).slice(-2); //获取当前日(1-31)
				var curTime = curYear + "" + curMonth + "" + curDay;
				if (year == curYear) {
					if (year == curYear) {
						if (date == curDay) {
							result = hour + ":" + minute;
						} else {
							result = month + "-" + date;
						}
					} else {
						result = month + "-" + date;
					}
				} else {
					result = month + "-" + date;
				}
				return result;
			},
			replaceSpecialChar(text) {
				if (!text) {
					return false;
				}
				text = text.replace(/&quot;/g, '"');
				text = text.replace(/&amp;/g, '&');
				text = text.replace(/&lt;/g, '<');
				text = text.replace(/&gt;/g, '>');
				text = text.replace(/&nbsp;/g, ' ');
				return text;
			},
			allCache() {
				var that = this;
				var timer = setTimeout(function() {
					that.isLoading = 1;
					clearTimeout('timer')
				}, 300)
				if (localStorage.getItem('AllchatList')) {
					that.chatList = JSON.parse(localStorage.getItem('AllchatList'));
				}
			},
			//群聊(性能考虑，只加载前30条)
			getMyChat(isPage) {
				var that = this;
				var page = that.page;
				if (isPage) {
					page++;
				}
				if (that.token == "") {
					uni.showToast({
						title: "请先登录",
						icon: 'none',
						duration: 1000,
						position: 'bottom',
					});
					return false
				}
				that.$Net.request({
					url: that.$API.allChat(),
					data: {
						"token": that.token,
						"limit": 30,
						"page": 1,
						"order": "lastTime"
					},
					header: {
						'Content-Type': 'application/x-www-form-urlencoded'
					},
					method: "get",
					dataType: 'json',
					success: function(res) {
						that.isLoad = 0;
						if (res.data.code == 1) {
							var list = res.data.data;
							if (list.length > 0) {
								var chatList = [];
								for (var i in list) {
									var arr = list[i];
									arr.isNew = 0;
									arr.unRead = 0;
									chatList.push(arr);
								}
								if (isPage) {
									that.page++;
									that.chatList = that.chatList.concat(chatList);
								} else {
									var oldChatList = [];
									if (that.oldChatList != null) {
										oldChatList = that.oldChatList;
									}
									if (oldChatList.length > 0) {

										if (!that.arraysEqual(oldChatList, chatList)) {
											console.log("开始对比")
											for (var c in chatList) {
												for (var d in oldChatList) {
													if (oldChatList[d].id == chatList[c].id) {
														if (oldChatList[d].lastTime < chatList[c].lastTime) {
															console.log("赋值完成")
															chatList[c].isNew = 1;

															var unRead = chatList[c].msgNum - oldChatList[d]
																.msgNum;
															if (unRead <= 0) {
																unRead = 0;
															}
															chatList[c].unRead = unRead;
														}
													}

												}
											}
											that.oldChatList = chatList;
											that.chatList = chatList;
											localStorage.setItem('AllchatList', JSON.stringify(chatList));
										}


									} else {
										that.oldChatList = chatList;
										that.chatList = chatList;
										localStorage.setItem('AllchatList', JSON.stringify(chatList));
									}
								}
							} else {
								// that.moreText="没有更多消息了";
							}

						}
					},
					fail: function(res) {
						that.isLoad = 0;
						// that.moreText="加载更多";
					}
				})
			},
			arraysEqual(a, b) {
				if (a === b) return true;
				if (a == null || b == null) return false;
				if (a.length != b.length) return false;
				for (var c in a) {
					for (var d in b) {
						if (b[d].id == a[c].id) {
							if (b[d].lastTime != a[c].lastTime) {
								return false;
							}
						}

					}
				}
			},
			goRegister() {
				uni.navigateTo({
					url: '/pages/user/register'
				});
			},
			goLogin() {
				uni.navigateTo({
					url: '/pages/user/login'
				});
			},
			
			goPage(url) {
				var that = this;

				uni.navigateTo({
					url: url
				});
			},
			unreadNum() {
				var that = this;
				var token = ""
				if (localStorage.getItem('userinfo')) {
					var userInfo = JSON.parse(localStorage.getItem('userinfo'));
					token = userInfo.token;

				}
				that.$Net.request({

					url: that.$API.unreadNum(),
					data: {
						"token": token
					},
					header: {
						'Content-Type': 'application/x-www-form-urlencoded'
					},
					method: "get",
					dataType: 'json',
					success: function(res) {
						if (res.data.code == 1) {
							that.unreadData = res.data.data;
						}
					},
					fail: function(res) {
						uni.showToast({
							title: "网络开小差了哦",
							icon: 'none'
						})
					}
				})
			},


		},
		components: {
			waves
		},
	}
</script>

<style>
</style>