<template>
	<u-navbar @click="click" placeholder class="chating_header">
		<view @click="routeBack" class="u-nav-slot back_view x-c"  slot="left">
			<image class="back_icon" src="https://bjyjb-1362704775.cos.ap-chongqing.myqcloud.com/shop/image/common_left_arrow.png"  alt="" srcset="" />
		</view>
		<view class="u-nav-slot" slot="center">
			<view class="chating_info" :class="{ chating_info_single: isSingle }">
				<view class="conversation_info">
					<view class="title">{{ storeCurrentConversation.showName }}</view>
					<view v-if="!isSingle && !isNotify" class="sub_title">{{ groupMemberCount }}</view>
					<image style="width: 16px; height: 16px" v-if="isRecvMsgOpt" src="https://bjyjb-1362704775.cos.ap-chongqing.myqcloud.com/shop/image/conversation_not_accept.png" />
				</view>
				<view v-if="isSingle" class="online_state">
					<!-- <view v-if="isSingle && onlineStr" class="dot" :style="{ backgroundColor: isOnline ? '#10CC64' : '#999' }" />
					<view class="online_str" v-if="isSingle">{{ onlineStr }}</view> -->
					<text v-show="isTyping">正在输入...</text>
				</view>
			</view>

			<view v-if="showGroupAnnouncement" @click="toGroupAnnouncement(true)" class="group_announcement_tab">
				<view class="announcement_header">
					<view class="announcement_header_left">
						<image src="https://bjyjb-1362704775.cos.ap-chongqing.myqcloud.com/shop/image/chating_message_notice.png" mode=""></image>
						<text style="margin-left: 8rpx">群公告</text>
					</view>
					<view @click.stop="toGroupAnnouncement(false)">
						<image src="https://bjyjb-1362704775.cos.ap-chongqing.myqcloud.com/shop/image/announcement_close.png" mode=""></image>
					</view>
				</view>
				<view class="announcement_content">
					{{ getGroupAnnouncementContent }}
				</view>
			</view>
			<view class="group_calling_tab" v-if="callingData">
				<view class="base_row" @click="showMoreMember = !showMoreMember">
					<image src="https://bjyjb-1362704775.cos.ap-chongqing.myqcloud.com/shop/image/group_calling_icon.png" />
					<text>{{ `${callingData.participant.length}人正在${callingData.invitation.mediaType === 'video' ? '视频' : '语音'}通话` }}</text>
					<image class="arrow" src="https://bjyjb-1362704775.cos.ap-chongqing.myqcloud.com/shop/image/group_calling_arrow.png" />
				</view>
				<view class="member_row" v-show="showMoreMember">
					<my-avatar
						size="42"
						:src="item.userInfo.faceURL"
						:desc="item.userInfo.nickname"
						v-for="item in callingData.participant.slice(0, 11)"
						:key="item.userInfo.userID"/>
				</view>
				<view class="action_row" v-show="showMoreMember" @click="joinRtc">
					<text>加入</text>
				</view>
			</view>
		</view>
		<view class="u-nav-slot" slot="right">
			<view class="right_action">
				<!-- <image
					v-if="inThisGroup || !isBlack"
					@click="routeCall"
					class="action_item"
					style="width: 23px;height: 23px;"
					src="https://bjyjb-1362704775.cos.ap-chongqing.myqcloud.com/shop/image/common_call.png"
					srcset=""/> -->
				<u-icon @click="goSetting" class="action_item" name="more-dot-fill" size="23" color="#333"></u-icon>
			</view>
		</view>
	</u-navbar>
</template>

<script>
import { mapGetters } from 'vuex';
import { PageEvents } from '../../../../constant';
import IMSDK, { IMMethods, GroupAtType, SessionType, MessageReceiveOptType } from 'openim-uniapp-polyfill';
import { Platform } from '../../../../constant/im';
import MyAvatar from '../../../../components/MyAvatar/index.vue';
import { callingModule } from '../../../../util/imCommon';

export default {
	name: 'ChatingHeader',
	components: {
		MyAvatar
	},
	props: {
		mutipleCheckVisible: Boolean
	},
	data() {
		return {
			isOnline: false,
			isTyping: false,
			onlineStr: '',
			callingData: null,
			showMoreMember: false,
			joinLock: false,
			inThisGroup: false
		};
	},
	computed: {
		...mapGetters(['storeCurrentConversation', 'storeCurrentGroup', 'storeCurrentMemberInGroup', 'storeSelfInfo', 'storeBlackList']),
		isRecvMsgOpt() {
			return this.storeCurrentConversation.recvMsgOpt !== MessageReceiveOptType.Nomal;
		},
		isSingle() {
			return this.storeCurrentConversation.conversationType === SessionType.Single;
		},
		isBlack() {
			if (!this.isSingle) {
				return true;
			}
			return this.storeBlackList.some((black) => black.userID === this.storeCurrentConversation.userID);
		},
		isNotify() {
			return this.storeCurrentConversation.conversationType === SessionType.Notification;
		},
		groupMemberCount() {
			return `(${this.storeCurrentGroup?.memberCount ?? 0})`;
		},
		showGroupAnnouncement() {
			return this.$store.getters.storeCurrentConversation.groupAtType === GroupAtType.AtGroupNotice;
		},
		getGroupAnnouncementContent() {
			if (this.showGroupAnnouncement) {
				return this.$store.getters.storeCurrentGroup.notification;
			}
			return '';
		},
		canGoSetting() {
			if (this.isSingle) {
				return true;
			}
			return this.storeCurrentMemberInGroup.groupID === this.storeCurrentConversation.groupID;
		}
	},
	mounted() {
		this.setIMListenter();
		if (this.storeCurrentConversation.groupID) {
			this.joinedGroupChangeHandler({
				data: { groupID: this.storeCurrentConversation.groupID }
			});
		} else {
			this.getOnlineState();
		}
	},
	beforeDestroy() {
		this.disposeIMListener();
		IMSDK.asyncApi('unsubscribeUsersStatus', IMSDK.uuid(), [this.storeCurrentConversation.userID]);
	},
	methods: {
		click(e) {
			this.$emit('click', e);
		},
		routeBack() {
			if (this.mutipleCheckVisible) {
				this.$emit('mutipleCheckUpdate');
				return;
			}
			uni.switchTab({
				url: '/pages/im/conversationList/index'
			});
		},
		goSetting() {
			const url = this.isSingle ? '/pages_im/pages/conversation/singleSettings/index' : '/pages_im/pages/conversation/groupSettings/index';
			uni.navigateTo({url});
		},
		joinRtc() {
			callingModule.joinRoomLiveChat(this.callingData);
		},
		routeCall() {
			if (!this.$store.getters.storeCurrentConversation.groupID) {
				uni.$emit(PageEvents.RtcCall);
				return;
			}
			IMSDK.asyncApi('signalingGetRoomByGroupID', IMSDK.uuid(), this.$store.getters.storeCurrentConversation.groupID).then(({ data }) => {
				if (data.invitation) {
					uni.showModal({
						title: '提示',
						content: '群通话进行中，是否直接加入？',
						confirmText: '确认',
						cancelText: '取消',
						success: (res) => {
							if (res.confirm) {
								callingModule.joinRoomLiveChat(data);
							}
						}
					});
				} else {
					uni.$emit(PageEvents.RtcCall);
				}
			});
		},
		getOnlineState() {
			IMSDK.asyncApi('subscribeUsersStatus', IMSDK.uuid(), [this.storeCurrentConversation.userID])
				.then(({ data }) => {
					console.log('getOnlineState', data);
					this.isOnline = !!data[0].status;
					if (data[0].status) {
						const platformStr = data[0].platformIDs.map((id) => Platform[id]).join('/');
						this.onlineStr = platformStr + '在线';
					} else {
						this.onlineStr = '离线';
					}
				}).catch((err) => {
					console.log('getOnlineStateErr', err);
				});
		},
		updateTyping() {
			if (this.isTyping) {
				return;
			}
			this.isTyping = true;
			setTimeout(() => {
				this.isTyping = false;
			}, 1500);
		},
		updateCallingData(data) {
			this.callingData = data;
		},
		checkOnline() {
			if (!this.isOnline && this.isSingle) {
				this.getOnlineState();
			}
		},
		toGroupAnnouncement(toPage) {
			IMSDK.asyncApi(IMSDK.IMMethods.ResetConversationGroupAtType, IMSDK.uuid(), this.$store.getters.storeCurrentConversation.conversationID);
			if (toPage) {
				uni.navigateTo({
					url: `/pages_im/pages/conversation/groupAnnouncement/index`
				});
			}
		},
		userStatusChangeHandler({ data }) {
			if (data.userID === this.storeCurrentConversation.userID) {
				this.isOnline = !!data.status;
				if (data.status) {
					const platformStr = data.platformIDs.map((id) => Platform[id]).join('/');
					this.onlineStr = platformStr + '在线';
				} else {
					this.onlineStr = '离线';
				}
			}
		},
		joinedGroupChangeHandler({ data }) {
			if (data.groupID === this.storeCurrentConversation.groupID) {
				IMSDK.asyncApi(IMMethods.IsJoinGroup, IMSDK.uuid(), data.groupID).then((res) => {
					this.inThisGroup = res.data;
				});
			}
		},
		setIMListenter() {
			IMSDK.subscribe(IMSDK.IMEvents.OnUserStatusChanged, this.userStatusChangeHandler);
			uni.$on(IMSDK.IMEvents.OnJoinedGroupDeleted, this.joinedGroupChangeHandler);
			uni.$on(IMSDK.IMEvents.OnJoinedGroupAdded, this.joinedGroupChangeHandler);
		},
		disposeIMListener() {
			IMSDK.unsubscribe(IMSDK.IMEvents.OnUserStatusChanged, this.userStatusChangeHandler);
			uni.$off(IMSDK.IMEvents.OnJoinedGroupDeleted, this.joinedGroupChangeHandler);
			uni.$off(IMSDK.IMEvents.OnJoinedGroupAdded, this.joinedGroupChangeHandler);
		}
	}
};
</script>

<style lang="scss" scoped>
	
.chating_header {
	display: inherit;
	border: 2rpx solid #e8eaef;
	::v-deep .u-navbar__content__left {
		padding: 0;
	}

	.chating_info {
		@include vCenterBox();
		flex-direction: column;

		&_single {
			margin-bottom: 24rpx;
		}

		.conversation_info {
			flex-direction: row;
			justify-content: center;
			@include vCenterBox();

			.title {
				@include nomalEllipsis();
				max-width: 280rpx;
				font-size: 14px;
				font-weight: 500;
			}

			.sub_title {
				margin-left: 8rpx;
			}
		}

		.online_state {
			@include vCenterBox();
			flex-direction: row;
			margin-top: 6rpx;
			// position: absolute;
			// top: 2px;
			// left: 50%;
			// transform: translateX(-50%);
			font-size: 20rpx;
			color: #999;

			.dot {
				background-color: #10cc64;
				width: 12rpx;
				height: 12rpx;
				border-radius: 50%;
				margin-right: 12rpx;
			}

			.online_str {
				@include nomalEllipsis();
				max-width: 280rpx;
			}
		}
	}

	::v-deep .u-navbar__content__right {
		padding: 0;
	}

	.right_action {
		@include vCenterBox();
		flex-direction: row;
		margin-right: 24rpx;

		.action_item {
			padding: 12rpx;
		}

		.u-icon {
			margin-left: 12rpx;
		}
	}
}

.back_view{
	width:45px;
	height: 40px;
}

.back_icon {
	padding: 24rpx;
	padding-left: 0;
	width: 12px; 
	height: 20px
}


.group_announcement_tab {
	display: flex;
	flex-direction: column;
	align-items: flex-start;
	width: 80%;
	position: absolute;
	left: 6%;
	// bottom: -44px;
	margin-top: 40rpx;
	padding: 14rpx 32rpx;
	background-color: #f0f6ff;
	border-radius: 12rpx;

	.announcement_header {
		@include vCenterBox();
		width: 100%;
		flex-direction: row;
		justify-content: space-between;
		margin-bottom: 16rpx;

		&_left {
			@include vCenterBox();
		}
	}

	.announcement_content {
		@include ellipsisWithLine(2);
		margin: 0 12rpx;
		font-size: 24rpx;
		color: #617183;
	}

	image {
		width: 16px;
		height: 16px;
		min-width: 16px;
	}
}

.group_calling_tab {
	position: absolute;
	left: 0;
	width: 80%;
	margin-top: 12px;
	margin-left: 5%;
	padding: 24rpx;
	background-color: #f4f9ff;
	border-radius: 8rpx;
	color: #5496eb;
	font-size: 24rpx;

	.base_row {
		display: flex;
		align-items: center;

		image {
			width: 10px;
			height: 10px;
		}

		text {
			margin-left: 16rpx;
		}

		.arrow {
			width: 9px;
			height: 6px;
			position: absolute;
			right: 24rpx;
		}
	}

	.member_row {
		display: flex;
		// justify-content: space-between;
		flex-wrap: wrap;
		padding: 24rpx 28rpx;
		margin-top: 24rpx;
		background-color: #fff;
		border-bottom: 1px solid rgba(151, 151, 151, 0.16);
		border-top-left-radius: 8rpx;
		border-top-right-radius: 8rpx;

		.u-avatar {
			margin-bottom: 16rpx;

			&:not(:nth-child(6n)) {
				margin-right: calc(6% / 2);
			}
		}
	}

	.action_row {
		display: flex;
		justify-content: center;
		padding: 24rpx;
		background-color: #fff;
		font-size: 28rpx;
		border-bottom-left-radius: 8rpx;
		border-bottom-right-radius: 8rpx;
	}
}


</style>