<template>
	<view :style="{ left: getLeft, right: getRight,'grid-template-columns': `repeat(${menuList.length}, 1fr`  }" class="message_menu_container"  :class="{ message_menu_container_bottom: is_bottom }">
		<view class="message_menu_item" v-for="item in menuList"   @click="menuClick(item)" :key="item.idx">
			<image :src="item.icon"  />
			<text>{{ item.title }}</text>
		</view>
	</view>
</template>

<script>
import { mapGetters, mapActions } from 'vuex';
import { MessageMenuTypes, ContactChooseTypes, PageEvents } from '../../../../../constant';
import IMSDK, { GroupMemberRole, MessageType, SessionType } from 'openim-uniapp-polyfill';
import { parseAt } from '../../../../../util/imCommon';
import { isDoctorAction } from '../../../../../util/common';
import copy from '../../../../../static/images/chating_message_copy.png';
import forward from '../../../../../static/images/chating_message_forward.png';
import reply from '../../../../../static/images/chating_message_reply.png';
import revoke from '../../../../../static/images/chating_message_revoke.png';
import multiple from '../../../../../static/images/chating_message_multiple.png';
import del from '../../../../../static/images/chating_message_del.png';

const canCopyTypes = [MessageType.TextMessage, MessageType.AtTextMessage, MessageType.QuoteMessage, MessageType.GroupAnnouncementUpdated];

export default {
	components: {},
	props: {
		message: {
			type: Object
		},
		is_bottom: {
			type: Boolean,
			default: true
		},
		isSender: Boolean,
		paterWidth: Number
	},
	data() {
		return {
			contentType: null
		};
	},
	computed: {
		...mapGetters(['storeCurrentMemberInGroup', 'storeCurrentUserID',"storeCurrentConversation"]),
		getLeft() {
			// 145 + 145*0.2
			if (this.isSender && this.paterWidth < 174) {
				return 'auto';
			}
			if (!this.isSender && this.paterWidth < 174) {
				return '0';
			}
			return '20%';
		},
		getRight() {
			if (this.isSender && this.paterWidth < 174) {
				return '0';
			}
			return 'auto';
		},
		canRevoke() {
			const interval = this.message.sendTime < Date.now() - 5 * 60 * 1000;
			if (interval) {
				return false;
			}
			if (this.message.sessionType !== SessionType.Single && this.storeCurrentMemberInGroup.roleLevel !== GroupMemberRole.Nomal) {
				return true;
			}

			return this.isSender;
		},
		isGroupAnnouncement() {
			return this.message.contentType === MessageType.GroupAnnouncementUpdated;
		},
		menuList() {
		  // 公共基础菜单（非医生也能看到的项）
		  const baseMenus = [
			 {
				idx: 0, 
				type: MessageMenuTypes.Copy, 
				title: "复制", 
				icon: copy, 
				visible: canCopyTypes.includes(this.message.contentType),
			 },
			 {    idx: 1, 
				 type: MessageMenuTypes.Del, 
				 title: "删除", 
				 icon: del, 
				 visible: true ,
			 },
	
			 {
				  idx: 3, 
				  type: MessageMenuTypes.Reply, 
				  title: "回复", 
				  icon: reply, 
				  visible: !this.isGroupAnnouncement 
			 },
			 {
			      idx: 4, 
			      type: MessageMenuTypes.Revoke, 
			      title: "撤回", 
			      icon: revoke, 
			      visible: this.canRevoke && !this.isGroupAnnouncement 
			 }
		  ];
		  const menus1 = [
				{
				  idx: 2, 
				  type: MessageMenuTypes.Forward, 
				  title: "转发", 
				  icon: forward, 
				  visible: !this.isGroupAnnouncement && this.message.contentType==MessageType.VoiceMessage
				},
				{
				  idx: 5, 
				  type: MessageMenuTypes.Multiple, 
				  title: "多选", 
				  icon: multiple, 
				  visible: !this.isGroupAnnouncement && this.message.contentType==MessageType.VoiceMessage
				}
		  ];
		  let tempMenuArrs=isDoctorAction(this.storeCurrentConversation.userID) ? baseMenus: [...baseMenus, ...menus1];
		  let menuList=[];
		   tempMenuArrs.forEach((item) => {
		  	  if(item.visible){
				  menuList.push(item);
			  }
		   });
		  
		   return menuList;
		}
	},
	mounted() {
		this.contentType = this.message.contentType;
		
	},
	methods: {
		...mapActions('message', ['deleteMessages', 'updateOneMessage', 'updateQuoteMessageRevoke']),
		...mapActions('conversation', ['addRevokedMessage']),
	
		async menuClick({ type }) {
			switch (type) {
				case MessageMenuTypes.Copy:
					uni.setClipboardData({
						data: this.getCopyText(),
						success: () => {
							uni.hideToast();
							this.$nextTick(() => {
								uni.$u.toast('复制成功');
							});
						}
					});
					break;
				case MessageMenuTypes.Del:
					try {
						await IMSDK.asyncApi(IMSDK.IMMethods.DeleteMessage, IMSDK.uuid(), {
							conversationID: this.$store.getters.storeCurrentConversation.conversationID,
							clientMsgID: this.message.clientMsgID
						});
						this.deleteMessages([this.message]);
						uni.$u.toast('删除成功');
					} catch (error) {
						try {
							await IMSDK.asyncApi(IMSDK.IMMethods.DeleteMessageFromLocalStorage, IMSDK.uuid(), {
								conversationID: this.$store.getters.storeCurrentConversation.conversationID,
								clientMsgID: this.message.clientMsgID
							});
							this.deleteMessages([this.message]);
							uni.$u.toast('删除成功');
						} catch (error) {
							uni.$u.toast('删除失败');
						}
					}
					break;
				case MessageMenuTypes.Forward:
					uni.navigateTo({
						url: `/pages_im/pages/common/contactChoose/index?type=${ContactChooseTypes.ForWard}&forwardMessage=${encodeURIComponent(JSON.stringify(this.message))}`
					});
					break;
				case MessageMenuTypes.Multiple:
					uni.$emit(PageEvents.MutipleCheckUpdate, {
						flag: true,
						message: this.message
					});
					break;
				case MessageMenuTypes.Reply:
					this.$store.commit('message/SET_QUOTE_MESSAGE', this.message);
					break;
				case MessageMenuTypes.Revoke:
					IMSDK.asyncApi(IMSDK.IMMethods.RevokeMessage, IMSDK.uuid(), {
						conversationID: this.$store.getters.storeCurrentConversation.conversationID,
						clientMsgID: this.message.clientMsgID
					})
						.then(() => {
							if (canCopyTypes.includes(this.contentType) && this.message.sendID === this.storeCurrentUserID) {
								this.addRevokedMessage(this.message);
							}
							this.updateOneMessage({
								message: {
									...this.message,
									contentType: MessageType.RevokeMessage,
									notificationElem: {
										detail: JSON.stringify({
											clientMsgID: this.message.clientMsgID,
											revokeTime: Date.now(),
											revokerID: this.storeCurrentUserID,
											revokerNickname: '你',
											revokerRole: 0,
											seq: this.message.seq,
											sessionType: this.message.sessionType,
											sourceMessageSendID: this.message.sendID,
											sourceMessageSendTime: this.message.sendTime,
											sourceMessageSenderNickname: this.message.senderNickname
										})
									}
								}
							});
							this.updateQuoteMessageRevoke({
								clientMsgID: this.message.clientMsgID
							});
						})
						.catch(() => uni.$u.toast('撤回失败'));
					break;
				default:
					break;
			}
			this.$emit('close');
		},
		getMenuList(){
			// 公共基础菜单（非医生也能看到的项）
			let baseMenus = [
						 {
							idx: 0, 
							type: MessageMenuTypes.Copy, 
							title: "复制", 
							icon: copy, 
							visible: canCopyTypes.includes(this.message.contentType),
						 },
						 {    idx: 1, 
							 type: MessageMenuTypes.Del, 
							 title: "删除", 
							 icon: del, 
							 visible: true ,
						 },
						 {
							  idx: 3, 
							  type: MessageMenuTypes.Reply, 
							  title: "回复", 
							  icon: reply, 
							  visible: true
						 },
						 {
						      idx: 4, 
						      type: MessageMenuTypes.Revoke, 
						      title: "撤回", 
						      icon: revoke, 
						      visible: this.canRevoke && !this.isGroupAnnouncement 
						 }
			];
			let menus1 = [
							{ 
							  idx: 2, 
							  type: MessageMenuTypes.Forward, 
							  title: "转发", 
							  icon: forward, 
							  visible: !this.isGroupAnnouncement && this.message.contentType==MessageType.VoiceMessage
							},
							{
							  idx: 5, 
							  type: MessageMenuTypes.Multiple, 
							  title: "多选", 
							  icon: multiple, 
							  visible: !this.isGroupAnnouncement && this.message.contentType==MessageType.VoiceMessage
							}
			];
			let tempMenuArrs=isDoctorAction(this.storeCurrentConversation.userID) ? baseMenus: [...baseMenus, ...menus1];
			let menuList=[];
			 for(let i=0;i<tempMenuArrs.length;i++){
				 let item=tempMenuArrs[i];
				 if(item.visible){
				 	 menuList.push(item);
				 }
			 }
			 console.log("qxj menuList:");
			 console.log(menuList);
			 return menuList;
		},
		getCopyText() {
			if (this.isGroupAnnouncement) {
				let detail = {};
				try {
					detail = JSON.parse(this.message.notificationElem.detail);
				} catch (e) {}
				return detail.group?.notification ?? '';
			}
			if (this.message.contentType === MessageType.AtTextMessage) {
				return parseAt(this.message.atTextElem, true);
			}
			if (this.message.contentType === MessageType.QuoteMessage) {
				return this.message.quoteElem.text;
			}
			return this.message.textElem.content;
		}
	}
};
</script>

<style scoped lang="scss">
.message_menu_container {
	display: grid;
	//grid-template-columns: repeat(5, 1fr);
	background-color: #5b5b5b;
	padding: 8rpx 0;
	border-radius: 16rpx;
	position: absolute;
	top: -12px;
	transform: translateY(-100%);
	z-index: 1002;
	width: max-content;  /* 宽度根据内容自适应 */
	&_bottom {
		top: unset;
		bottom: 0;
		transform: translateY(110%);
	}

	.message_menu_item {
		@include colBox(false);
		align-items: center;
		font-size: 12px;
		color: #fff;
		padding: 16rpx 24rpx;
		image {
			width: 14px;
			height: 16px;
			margin-bottom: 4px;
		}
		text {
			min-width: max-content;
		}
	}
}
</style>
