<template>
	<view v-if="isMute">
		<view class="forbidden_footer">
			<view class="mute_tip" v-if="storeCurrentGroup.status === 3">全群禁言中</view>
			<view class="mute_tip" v-else>您被禁言至{{date(storeCurrentMemberInGroup.muteEndTime)}}</view>
		</view>
	</view>
	<view v-else-if="!isSingle && !storeCurrentMemberInGroup.userID">
		<view class="forbidden_footer">
			<view class="mute_tip">您不是群成员</view>
		</view>
	</view>
	<view v-else>
		<view class="chat_footer">
			<!-- 语音信息 -->
			<image class="action_btn" v-show="inputType == 'keyboard'" @click.prevent="swtichInputType('record')" mode="heightFix" src="@/static/images/chating_footer_audio.png" alt="" srcset="" />
			<image class="action_btn" v-show="inputType == 'record'" @click.prevent="swtichInputType('keyboard')" mode="heightFix" src="@/static/images/chating_footer_audio_recording.png" alt="" srcset="" />
			<view class="input_content">
				<Recoder v-if="inputType == 'record'" @RecodEvent="onRecodEvent"></Recoder>
				<SimpleEditor 
					v-if="inputType == 'keyboard'" 
					class="custom_editor" 
					ref="customEditor" 
					@onUserEvent="onEditorEvent"
					:value="inputHtml"/>
			</view>

			<view class="footer_action_area" v-show="inputType == 'keyboard'">
				<image class="action_btn" @click.prevent="updateActionBar(true)" src="@/static/images/chating_footer_emoji.png" alt="" srcset="" />
				<image v-show="!hasContent" class="action_btn" @click.prevent="updateActionBar(false)" src="@/static/images/chating_footer_add.png" alt="" srcset="" />
				<button class="send_btn" type="primary" v-show="hasContent" @touchend.prevent="sendTextMessage">发送</button>
			</view>
		</view>
		<chating-action-bar :isEmoji="isEmoji" @onUserEvent="onUserEvent" v-show="actionBarVisible" />
		<u-action-sheet :safeAreaInsetBottom="true" round="12" :actions="actionSheetMenu" @select="selectClick"
			:closeOnClickOverlay="true" :closeOnClickAction="true" :show="showActionSheet"
			@close="showActionSheet = false">
		</u-action-sheet>
		<!-- 录音动画 -->
		<!-- #ifdef APP-PLUS -->
		<view class="voice_an" v-if="recording">
			<view class="voice_an_icon">
				<view id="one" class="wave"></view>
				<view id="two" class="wave"></view>
				<view id="three" class="wave"></view>
				<view id="four" class="wave"></view>
				<view id="five" class="wave"></view>
				<view id="six" class="wave"></view>
				<view id="seven" class="wave"></view>
			</view>
			<view class="text">
				<text>{{voiceIconText}}</text>
			</view>
		</view>
		<!-- #endif -->
	</view>

</template>

<script>
	import {mapGetters,mapActions} from "vuex";
	import {getPurePath,html2Text,getVideoCover,getVideoInfo} from "@/util/common";
	import {offlinePushInfo,date} from "@/util/imCommon";
	import {ChatingFooterActionTypes,UpdateMessageTypes,} from "@/constant";
	import IMSDK, {IMMethods,MessageStatus,MessageType,SessionType} from "openim-uniapp-polyfill";
	import CustomEditor from "./CustomEditor";
	import SimpleEditor from "./SimpleEditor";
	import ChatingActionBar from "./ChatingActionBar";
	import Recoder from "./Recoder";
	import {upload} from "@/api/login.js"
	import IM from "@/util/im.js";
	import permision from "@/js_sdk/wa-permission/permission.js"
	const needClearTypes = [MessageType.TextMessage];

	const rtcChoose = [
		{
			name: "视频通话",
			type: 'video',
			idx: 0,
		},
		{
			name: "语言通话",
			type: 'voice',
			idx: 1,
		},
	];

	export default {
		components: {
			CustomEditor,SimpleEditor,
			ChatingActionBar,
			Recoder,
		},
		props: {
			footerOutsideFlag: Number,
		},
		data() {
			return {
				recording:false,
				voiceIconText : "正在录音...",
				inputType:"keyboard",
				isEmoji:false,
				inputHtml: '',
				actionBarVisible: false,
				isInputFocus: false,
				actionSheetMenu: [],
				showActionSheet: false,
				isInsertingEmoji: false, // 标记是否正在插入表情
				
				fileSelectedArray:[]
			};
		},
		computed: {
			...mapGetters([
				"storeCurrentConversation",
				"storeCurrentGroup",
				"storeBlackList",
				"storeCurrentUserID",
				"storeCurrentMemberInGroup"
			]),
			isSingle() {
				return (
					this.storeCurrentConversation.conversationType === SessionType.Single
				);
			},
			hasContent() {
				return html2Text(this.inputHtml) !== "";
			},
			isAdminOrOwner(){
				return this.storeCurrentMemberInGroup && this.storeCurrentMemberInGroup?.roleLevel>20;
			},
			isMute(){
				if(this.isSingle){
					return false;
				}
				if(this.storeCurrentGroup && this.storeCurrentGroup.status === 3 && !this.isAdminOrOwner){
					return true;
				}
				if (this.storeCurrentMemberInGroup && this.storeCurrentMemberInGroup?.muteEndTime>0){
					return true;
				}
				return false;
			}
		},
		watch: {
			footerOutsideFlag(newVal) {
				this.onClickActionBarOutside();
			},
		},
		mounted() {
			//console.log(this.storeCurrentGroup)
			//console.log(this.storeCurrentMemberInGroup)
			this.setKeyboardListener();
		},
		beforeDestroy() {
			this.disposeKeyboardListener();
		},
		methods: {
			...mapActions("message", ["pushNewMessage", "updateOneMessage"]),
			date,
			async createTextMessage() {
				let message = "";
				const text = html2Text(this.inputHtml);
				message = await IMSDK.asyncApi(
					IMMethods.CreateTextMessage,
					IMSDK.uuid(),
					text
				);
				//console.log(message);
				return message;
			},
			async sendTextMessage() {
				if (!this.hasContent) return;
				const message = await this.createTextMessage();
				this.sendMessage(message,this.storeCurrentConversation.userID,this.storeCurrentConversation.groupID);
			},
			sendMessage(message,user_id,group_id) {
				this.pushNewMessage(message);
				if (needClearTypes.includes(message.contentType)) {
					this.$refs.customEditor.clear();
				}
				let method = IMMethods.SendMessage;
				if([MessageType.PictureMessage,MessageType.VoiceMessage,MessageType.VideoMessage,MessageType.FileMessage].includes(message.contentType)){
					method = IMMethods.SendMessageNotOss;
				}
				this.$emit("scrollToBottom");
				IMSDK.asyncApi(method, IMSDK.uuid(), {
						recvID: user_id,
						groupID: group_id,
						message,
						offlinePushInfo,
					})
					.then(({data}) => {
						//console.log(data);
						this.updateOneMessage({
							message: data,
							isSuccess: true,
						});
					})
					.catch(({data,errCode,errMsg}) => {
						console.log(errCode,errMsg,data);
						uni.$u.toast(errMsg);
						this.updateOneMessage({
							message: data,
							type: UpdateMessageTypes.KeyWords,
							keyWords: [
								{
									key: "status",
									value: MessageStatus.Failed,
								},
								{
									key: "errCode",
									value: errCode,
								},
							],
						});
					});
			},
			recordAudioMsg(){
				if (uni.getSystemInfoSync().platform == "android") {
					permission.requestAndroid("android.permission.RECORD_AUDIO"); //Android请求录音权限
				} else {
					permission.requestIOS("record"); //ios请求录音权限
				}
			},
			// action
			onClickActionBarOutside() {
				// 如果正在插入表情，不隐藏表情栏
				if (this.isInsertingEmoji) {
					return;
				}
				if (this.actionBarVisible) {
					this.actionBarVisible = false;
				}
			},
			updateActionBar(isEmoji) {
				if(this.actionBarVisible){
					if(this.isEmoji!== !!isEmoji){
						this.isEmoji = !!isEmoji;
					}else{
						this.actionBarVisible = false;
					}
				}else{
					this.actionBarVisible = true;
					this.isEmoji = !!isEmoji;
				}
			},
			swtichInputType(type){
				console.log(type);
				this.inputType = type;
				if(this.inputType == 'record'){
					this.actionBarVisible = false;
					this.isEmoji = false;
				}
			},

			async sendLocationMessage(res){
				console.log(res);
                const _this = this;
				const message = await IMSDK.asyncApi(
					IMMethods.CreateLocationMessage,
					IMSDK.uuid(),
					{
						latitude:res.lat,
						longitude:res.lng,
						description:res.address
					}
				);
				_this.sendMessage(message,_this.storeCurrentConversation.userID,_this.storeCurrentConversation.groupID);
				
			},
			async sendVoiceMessage(audio){
				const _this = this;
				const message = await IMSDK.asyncApi(
					IMMethods.CreateSoundMessageFromFullPath,
					IMSDK.uuid(),
					{
						soundPath:getPurePath(audio.tempFilePath),
						duration:audio.contentDuration
					}
				);
				_this.sendMessage(message,_this.storeCurrentConversation.userID,_this.storeCurrentConversation.groupID);
				
			},
			// from comp
			sendMediaMesage(paths) {
				const _this = this;
				paths.forEach(async (item) => {
					console.log(item);
					try {
                        let message = null;
						if(item.search('.mp4')>0){
							message = await IM.createVideoMessage(item);
						}else{
							message = await IM.createImageMessage(item);
						}
						console.log(message);
						if(message){
							_this.sendMessage(message,_this.storeCurrentConversation.userID,_this.storeCurrentConversation.groupID);
						}
					} catch (error) {
						console.log(error);
					}
				});
			},
			selectClick({idx}) {
				if (idx === 0) {
					uni.$u.toast('根据相关政策,暂时禁用视频通话');
					//发送视频通话
				} else {
					uni.$u.toast('根据相关政策,暂时禁用音频通话');
					//发送音频通话
				}
			},
			// keyboard
			keyboardChangeHander({height}) {
				//console.log(height);
				// 如果正在插入表情，不隐藏表情栏
				if (this.isInsertingEmoji) {
					return;
				}
				if (height > 0) {
					if (this.actionBarVisible) {
						this.actionBarVisible = false;
					}
				}
			},
			setKeyboardListener() {
				uni.onKeyboardHeightChange(this.keyboardChangeHander);
			},
			disposeKeyboardListener() {
				uni.offKeyboardHeightChange(this.keyboardChangeHander);
			},
			onEditorEvent(e){
				const _this = this;
				if(e.type=="atevent" && this.storeCurrentConversation.groupID){
					uni.navigateTo({
						url: `/pages/common/contactChoose/chooseGroupMember?groupID=${this.storeCurrentConversation.groupID}&checkedUserIDList=[]&hideUserIDList=[${this.storeCurrentUserID}]`,
						events: {
							onSelectedConfirm(userList) {
								userList.forEach((user)=>{
									_this.$refs.customEditor.insertMention(user.remark || user.nickname || user.showName,user.userID);
									_this.$refs.customEditor.focus();
								})
							}
						}
					});
					return ;
				}
				if(e.type=="ready"){
					return ;
				}
				if(e.type=="focus"){
					this.isInputFocus = true;
					this.$emit("scrollToBottom");
					return ;
				}
				if(e.type=="blur"){
					this.isInputFocus = false;
					return ;
				}
				if(e.type=="onChange"){
					return ;
				}
				if(e.type=="input"){
					// SimpleEditor 返回的是纯文本，直接使用
					this.inputHtml = e.html || e.text || "";
					return ;
				}
				console.log(e);
			},
			onRecodEvent(e){
                const _this = this;
				switch(e.type){
					case "voiceIconTextChange":
						_this.voiceIconText = e.text;
						break;
					case "sendVoiceMessage":
						_this.sendVoiceMessage(e.audio);
						break;
					case "recordingStateChange":
						_this.recording = e.state;
						break;
					default:
						break;
				}
			},
			pickMedia(){
				const _this = this;
				plus.gallery.pick(({files})=>{
					console.log(files);
					_this.sendMediaMesage(files);
				}, (error )=>{
					console.log(error); 
				}, {
					animation:true,
					confirmText:"确定",
					//crop:null,
					editable:true,
					filename:"_doc/",
					//filter:"none",//image,none,video
					filter:"image",
					maximum:9,
					multiple:true,
					permissionAlert:true,
					//popover:{},
					//selected:[""],
					onmaxed(){
						console.log("超出最大选择数");
					},
				});
			},
			onUserEvent(e){
                const _this = this;
				switch(e.type){
					case "clearSendStr":
						this.$refs.customEditor.clear();
						break;
					case "delSendStr":
						this.$refs.customEditor.delete();
						break;
					case "insertEmoji":
                        //TODO 在光标处插入文字extra
                        //editorContext.insertImage(
                        // 标记正在插入表情（先设置标志，保护表情栏不被隐藏）
                        this.isInsertingEmoji = true;
                        
                        // 确保表情栏显示（只在真正需要时才更新状态，避免不必要的响应式触发）
                        const wasVisible = this.actionBarVisible;
                        const wasEmoji = this.isEmoji;
                        
                        if (!wasVisible || !wasEmoji) {
                            // 只有在需要时才更新状态，减少响应式触发
                            if (!wasVisible) {
                                this.actionBarVisible = true;
                            }
                            if (!wasEmoji) {
                                this.isEmoji = true;
                            }
                        }
                        
                        // 直接插入文本，不等待 nextTick，减少延迟
                        this.$refs.customEditor.insertText(e.emoji,() =>{
                            //console.log("插入文字成功");
                            // 延迟重置标志，确保其他事件不会隐藏表情栏
                            setTimeout(() => {
                                this.isInsertingEmoji = false;
                            }, 300);
                        },(err) => {
                            //console.log("插入文字失败", err);
                            this.isInsertingEmoji = false;
                        });
						break;
					case "prepend_image_message":
                        if(e.source == "camera"){
                            var cmr = plus.camera.getCamera();   
                            cmr.captureImage((src) =>{   
                                _this.sendMediaMesage([plus.io.convertLocalFileSystemURL(src)]);
                            }, (err) =>{  
                                console.log(err); 
                            }, {
                                filename:"_doc/camera/"
                            });
                            return ; 
                        }
                        if(e.source == "album"){
							_this.pickMedia();
						}
						break;
                    case "prepend_call_message":
                        this.actionSheetMenu = [...rtcChoose];
                        this.showActionSheet = true;
						break;
                    case "prepend_file_message":
                        uni.chooseFile({
                            count:9,
                            multiple: true,
                            success: (res) => {
                                console.log('选择文件成功', res);
                                //const filePaths = res.tempFiles.map(file => file.path);
                                //_this.sendMediaMesage(filePaths);
                            },
                            fail: (err) => {
                                console.log('选择文件失败', err);
                            }
                        });
                        break;
                    case "prepend_location_message":
						uni.navigateTo({
							url:"/pages/common/map",
							events:{
								onConfirm(res) {
									_this.sendLocationMessage(res);
								}
							}
						})
						break;
                    default:
				        console.log(e);
                        break;
				}
			}
		},
	};
</script>

<style lang="scss" scoped>
	.custom_editor {
		min-height: 60rpx;
		max-height: 240rpx;
	}
	
	.forbidden_footer {
		width: 100%;
		height: 112rpx;
		color: #8e9ab0;
		display: flex;
		flex-direction: row;
		justify-content: center;
		align-items: center;
		background: #f0f2f6;
	}
	
	.chat_footer {
		display: flex;
		align-items: flex-end;
		// background-color: #e9f4ff;
		background: #f6f6f6;
		// height: 50px;
		max-height: 120px;
		padding: 10rpx 20rpx;
		gap: 20rpx;
		.mute_tip{
			
		}
	
		.input_content {
			flex: 1;
			border-radius: 8rpx;
			position: relative;
	
			.record_btn {
				// background-color: #3c9cff;
				background: #fff;
				color: black;
				height: 30px;
				font-size: 24rpx;
			}
		}
	
		.action_btn{
			width: 50rpx;
			height: 50rpx;
			margin-bottom: 6rpx;
		}
		.footer_action_area {
			display: flex;
			align-items: center;
			gap: 20rpx;
		}
	
		.send_btn {
			height: 50rpx;
			line-height: 50rpx;
			background-color: $uni-color-success;
			padding: 0 8px;
			border-radius: 4px;
			color: #fff;
		}
	}
	
	/* 语音动画 */
	.voice_an {
		width: 300rpx;
		height: 300rpx;
		position: fixed;
		top: 50%;
		left: 50%;
		transform: translate(-50%, -55%);
		background-color: rgba(41, 41, 41, 0.7);
		color: white;
		display: flex;
		flex-direction: column;
		align-items: center;
		text-align: center;
		border-radius: 10rpx;

		.text {
			padding-top: 30rpx;
		}

		@keyframes runVoice {
			0% {
				height: 10%;
			}

			20% {
				height: 50%;
			}

			50% {
				height: 100%;
			}

			80% {
				height: 50%;
			}

			100% {
				height: 0%;
			}
		}

		.wave {
			width: 6rpx;
			height: 100%;
			margin-left: 10rpx;
			border-radius: 50rpx;
			background-color: #999;
			vertical-align: middle;
			display: inline-block;
		}

		.voice_an_icon {
			width: 200rpx;
			height: 100rpx;
			line-height: 50rpx;
			margin: 50rpx 0;
		}

		.voice_an_icon #one {
			animation: runVoice 0.6s infinite 0.1s;
		}

		.voice_an_icon #two {
			animation: runVoice 0.6s infinite 0.3s;
		}

		.voice_an_icon #three {
			animation: runVoice 0.6s infinite 0.6s;
		}

		.voice_an_icon #four {
			animation: runVoice 0.6s infinite 0.1s;
		}

		.voice_an_icon #five {
			animation: runVoice 0.6s infinite 0.3s;
		}

		.voice_an_icon #six {
			animation: runVoice 0.6s infinite 0.6s;
		}

		.voice_an_icon #seven {
			animation: runVoice 0.6s infinite 0.1s;
		}
	}
</style>