<template>
	<view class="chating_container">
		<SelectHeader v-if="selectFlag" :count="selectItems.length" @leftClick="onUserMessageEvent({type:'cancelSelect'})" ref="selectHeaderRef" />
		<ChatingHeader v-else @click="pageClick" ref="chatingHeaderRef" />
		<ChatingList 
			@userEvent="onUserMessageEvent" 
			@click="pageClick" 
			:selectItems="selectItems"
			:selectFlag="selectFlag"
			ref="chatingListRef" 
			@initSuccess="initSuccess" />
		<SelectFooter v-if="selectFlag" ref="selectFooterRef" @userEvent="onUserMessageEvent"  />
		<ChatingFooter v-else ref="chatingFooterRef" :footerOutsideFlag="footerOutsideFlag"
			@scrollToBottom="scrollToBottom" />
		<u-loading-page :loading="initLoading"></u-loading-page>
	</view>
</template>

<script>
	import {mapActions,mapGetters} from "vuex";
	import {offlinePushInfo} from "@/util/imCommon";
	import {PageEvents,ContactChooseTypes	} from "@/constant";
	import ChatingHeader from "./components/ChatingHeader";
	import ChatingFooter from "./components/ChatingFooter/index";
	import ChatingList from "./components/ChatingList";
	import SelectHeader from "./components/SelectHeader";
	import SelectFooter from "./components/SelectFooter";
	import {markConversationAsRead} from "@/util/imCommon";
	import IMSDK, {MessageType} from "openim-uniapp-polyfill";
	export default {
		components: {
			ChatingHeader,
			ChatingFooter,
			ChatingList,
			SelectHeader,
			SelectFooter
		},
		data() {
			return {
				listHeight: 0,
				footerOutsideFlag: 0,
				initLoading: true,
				back2Tab: false,
				selectFlag: false,
				selectItems: [],
				forwardItems: [],
				forwardMerge: false,
				Audio:null
			};
		},
		computed: {
			...mapGetters([
				"storeCurrentConversation","storeCurrentMsg",'storeCurrentMsgID'
			]),
		},
		created() {
			this.Audio = uni.createInnerAudioContext(); //音频
			/*
			设置音频播放模式，可取值：
			"ambient" - 不中止其他声音播放，不能后台播放，静音后无声音； 
			"soloAmbient" - 中止其他声音播放，不能后台播放，静音后无声音； 
			"playback" - 中止其他声音，可以后台播放，静音后有声音。 
			默认值为"playback"。
			*/
			this.Audio.sessionCategory="soloAmbient";
			this.Audio.onError((r)=>{
				console.log(r);
				this.updateCurrentMsg({});
			})
			this.Audio.onEnded((r)=>{
				console.log(r);
				this.updateCurrentMsg({});
			})
		},
		watch:{
			storeCurrentMsgID(nv,ov){
				if(nv!=ov && nv){
					if(this.storeCurrentMsg.soundElem.soundPath){
						this.Audio.src= this.storeCurrentMsg.soundElem.soundPath;
						this.Audio.play();
						return ;
					}
					this.updateCurrentMsg({});
				}
				console.log(nv,ov,this.Audio,this.storeCurrentMsg);
			}
		},
		onLoad(options) {
			//console.log("onload");
			this.setPageListener();
			if (options?.back2Tab) {
				this.back2Tab = JSON.parse(options.back2Tab);
			}
		},
		onUnload() {
			//console.log("unload");
			this.disposePageListener();
			markConversationAsRead({...this.$store.getters.storeCurrentConversation,},true);
			this.resetConversationState();
			this.resetMessageState();
			// #ifdef APP-PLUS
			if (this.Audio) {
				this.Audio.stop();
				this.Audio.destroy();
			}
			// #endif
		},
		onHide() {
			// #ifdef APP-PLUS
			if (this.Audio) {
				this.Audio.stop();
			}
			// #endif
		},
		methods: {
			...mapActions("message", ["updateCurrentMsg","resetMessageState", "deleteMessages", "pushNewMessage", "updateOneMessage"]),
			...mapActions("conversation", ["resetConversationState"]),
			scrollToBottom(isRecv = false) {
				this.$refs.chatingListRef.scrollToBottom(false, isRecv);
			},
			pageClick(e) {
				this.footerOutsideFlag += 1;
			},
			initSuccess() {
				this.initLoading = false;
			},

			// page event
			setPageListener() {
				uni.$on(PageEvents.ScrollToBottom, this.scrollToBottom);
			},
			disposePageListener() {
				uni.$off(PageEvents.ScrollToBottom, this.scrollToBottom);
			},
			//选择会话列表的回调
			async onForwardTargetSelected(userList, groupList) {
				const _this = this;
				//console.log(userList,groupList);
				if (this.forwardItems.length === 0) {
					return false;
				}
				if (this.forwardMerge && this.forwardItems.length > 1) {
					const res = await IMSDK.asyncApi(IMSDK.IMMethods.CreateMergerMessage, IMSDK.uuid(), {
						messageList: _this.forwardItems,
						title: "转发的消息",
						summaryList: ["summaryList", "summaryList"]
					});
					//console.log(res );
					if (res) {
						await _this.doForwarMsg(userList, groupList, res);
					}
				} else {
					for (var mi = 0; mi < this.forwardItems.length; mi++) {
						var msg = this.forwardItems[mi];
						const res = await IMSDK.asyncApi(IMSDK.IMMethods.CreateForwardMessage, IMSDK.uuid(), msg);
						//console.log(res );
						if (res) {
							await _this.doForwarMsg(userList, groupList, res);
						}
					}
				}
				this.onUserMessageEvent({type: 'cancelSelect'});
			},
			async doForwarMsg(userList, groupList, msgiem) 
			{
				//console.log(userList,groupList);
				const _this = this;
				for (var i = 0; i < userList.length; i++) {
					this.sendMessage(msgiem, userList[i].userID, "");
				}
				for (var i = 0; i < groupList.length; i++) {
					this.sendMessage(msgiem, "", groupList[i].groupID);
				}
			},
			sendMessage(message, user_id, group_id) {
				//this.scrollToBottom();
				//console.log(message);
				//console.log(user_id,group_id);
				IMSDK.asyncApi(IMSDK.IMMethods.SendMessage, IMSDK.uuid(), {
						recvID: user_id,
						groupID: group_id,
						message,
						offlinePushInfo,
					})
					.then(({data}) => {
						console.log(data);
						this.pushNewMessage(message);
					})
					.catch((res = {data,errCode,errMsg}) => {
						console.log(res);
						uni.$u.toast(errMsg);
					});
			},
			onUserMessageEvent(e, data) {
				const _this = this;
				if (e.type == 'select') {
					this.selectFlag = true;
					this.selectItems = [data];
					this.$refs.chatingListRef.scrollToAnchor(`auchor${data.clientMsgID}`);
					return;
				}
				if (e.type == 'cancelSelect') {
					this.selectFlag = false;
					this.selectItems = [];
					return;
				}
				if (e.type == 'selected') {
					if (this.selectFlag == true) {
						let founded = false;
						let arr = [];
						for (var index = 0; index < this.selectItems.length; index++) {
							var v = this.selectItems[index];
							if (v.clientMsgID == data.clientMsgID) {
								founded = true;
							} else {
								arr.push(v);
							}
						}
						if (!founded) {
							arr.push(data);
						}
						this.selectItems = [...arr];
					}
					return;
				}
				if (e.type == 'deleteMsg') {
					let deleteMsgs = [];
					if (!data) {
						deleteMsgs = [...this.selectItems];
					} else {
						deleteMsgs = [{...data}];
					}
					for (let i = 0; i < deleteMsgs.length; i++) {
						let element = deleteMsgs[i];
						IMSDK.asyncApi('deleteMessageFromLocalStorage', IMSDK.uuid(), {
							conversationID: _this.storeCurrentConversation.conversationID,
							clientMsgID: element.clientMsgID
						}).then(res => {
							//console.log(res);
						}).catch(res => {
							//console.log(res);
						}).finally(() => {
							//console.log(arguments);
						})
					}
					this.selectItems = [];
					this.$refs.chatingListRef.loadMessageList();
					return;
				}
				if (e.type == 'forward') {
					if (!data) {
						this.forwardItems = [...this.selectItems];
						let menu = ['逐条转发', '合并转发'];
						uni.showActionSheet({
							itemList: menu,
							success({tapIndex}) {
								if (menu[tapIndex] == '逐条转发') {
									this.forwardMerge = false;
								}
								if (menu[tapIndex] == '合并转发') {
									this.forwardMerge = true;
								}
								uni.navigateTo({
									url: `/pages/common/contactChoose/choose?type=${ContactChooseTypes.GetList}&checkedUserIDList=[]`,
									events: {
										onSelectedConfirm(userList, groupList) {
											//console.log(userList,groupList);
											_this.onForwardTargetSelected(userList, groupList)
										}
									}
								});
							}
						});
					} else {
						this.forwardItems = [{...data}];
						this.forwardMerge = false;
						uni.navigateTo({
							url: `/pages/common/contactChoose/choose?type=${ContactChooseTypes.GetList}&checkedUserIDList=[]`,
							events: {
								onSelectedConfirm(userList, groupList) {
									//console.log(userList,groupList);
									_this.onForwardTargetSelected(userList, groupList)
								}
							}
						});
					}
					return;
				}
				if (e.type == 'revokeMessage') {
					IMSDK.asyncApi('revokeMessage', IMSDK.uuid(), {
						conversationID: _this.storeCurrentConversation.conversationID,
						clientMsgID: data.clientMsgID
					}).then(res => {
						console.log(res);
					}).catch(res => {
						console.log(res);
					}).finally(() => {
						console.log(arguments);
					})
					return;
				}
				if(e.type == 'audio_msg_click'){
					if(_this.storeCurrentMsgID){
						_this.updateCurrentMsg({clientMsgID:""});
					}else{
						_this.updateCurrentMsg(e.message);
					}
					return ;
				}
				if (e.type == 'longtapMsgContent') {
					let menu = [];
					if (data.contentType == MessageType.TextMessage) {
						menu.push('复制')
					}
					menu.push('转发');
					menu.push('多选');
					menu.push('删除');
					let nowTime = new Date().getTime();
					let msgTime = data.createTime;
					let diff = nowTime - msgTime;
					if (this.isSender && diff < 120000) {
						menu.push('撤回')
					}
					uni.showActionSheet({
						itemList: menu,
						success({tapIndex}) {
							const title = menu[tapIndex];
							switch (title) {
								case "撤回":
									_this.onUserMessageEvent({type: 'revokeMessage'}, data);
									break;
								case "复制":
									let content = data.textElem?.content;
									if (content) {
										//let formatStr = this.replaceReseverEmoji(copyContent);
										uni.setClipboardData({
											data: content,
											success: (res) => {
												uni.showToast({
													title: res,
													icon: 'none'
												})
											},
											error: (e) => {
												uni.showToast({
													title: e,
													icon: 'none',
													duration: 3000,
												})
											}
										})
									}
									break;
								case "转发":
									_this.onUserMessageEvent({type: 'forward'}, data);
									break;
								case "多选":
									_this.onUserMessageEvent({type: 'select'}, data);
									break;
								case "删除":
									_this.onUserMessageEvent({type: 'deleteMsg'}, data);
									break;
								default:
									break;
							}
						}
					})
					return;
				}
			}
		},
		onBackPress() {
			uni.switchTab({
				url: "/pages/conversation/conversationList/index",
			});
			return true;
		},
		beforeDestroy() {
			uni.switchTab({
				url: "/pages/conversation/conversationList/index",
			});
		},
	};
</script>

<style lang="scss" scoped>
	.chating_container {
		@include colBox(false);
		height: 100vh;
		overflow: hidden;
		background-color: #ececec !important;
		position: relative;

		.watermark {
			font-size: 16px;
			/* 水印文字大小 */
			color: rgba(0, 0, 0, 0.2);
			/* 水印文字颜色，使用透明度控制可见度 */
			position: absolute;
			/* 水印相对定位 */
			transform: rotate(-45deg);
			pointer-events: none;
			/* 防止水印文字干扰交互 */

			/* 为不同的水印元素设置不同的偏移，以避免重叠 */
			// transform-origin: top right;
			// margin-top: 20px;
			// margin-right: 20px;
		}

		// ::before {
		//   content: "Your Watermark Text"; /* 替换为你想要的水印文字 */
		//   font-size: 16px; /* 水印文字大小 */
		//   color: rgba(0, 0, 0, 0.2); /* 水印文字颜色，使用透明度控制可见度 */
		//   position: absolute; /* 水印相对定位 */
		//   top: 20px; /* 距离顶部的距离 */
		//   right: 20px; /* 距离右侧的距离 */
		//   transform: rotate(-45deg); /* 将水印旋转为倾斜状态 */
		//   pointer-events: none; /* 防止水印文字干扰交互 */
		//   z-index: -1; /* 将水印置于底层 */
		// }

		.mutiple_action_container {
			display: flex;
			border-top: 1px solid #eaebed;
			background: #f0f2f6;
			justify-content: space-evenly;
			padding: 12px 24px;

			.action_item {
				@include centerBox();
				flex-direction: column;

				image {
					width: 48px;
					height: 48px;
				}
			}
		}
	}
</style>