<template>
	<view>
		<!-- <cu-custom bgImage='/static/bg.png' :isBack='true' v-if="user.deptId=='103'">
			<template v-slot:content>
				<text v-if='chat'>{{ chat.name }}</text>
				<text v-if='chat && chat.type === ChatType.GROUP'>（{{ count }}人）</text>
			</template>
			<template v-slot:right>
				<text class='cuIcon cuIcon-more' @tap='chatInfo'></text>
			</template>
		</cu-custom> -->
		<scroll-view :scroll-y='true' class='cu-chat' style="background-color: #e4e4e4;" :style="'height: calc(93vh)'"  @scroll='handleScroll'
			scroll-with-animation="true" :scroll-into-view='last' id='messageBox'>
			<checkbox-group @change="checkboxChange">
				<template v-for='(item) in messageList' :key="item.id">
					<load-map-user :userId="item.fromId" />
					<view v-if="item.messageType === MessageType.event" class="text-center">
						<MessageEvent :message="item"></MessageEvent>
					</view>
					<view v-else :id="`m-${item.id}`">
						<view v-if='item.mine' class='cu-item self'>
							<view class='main' style='display: block;'>
								<view class='text-gray text-sm padding-bottom-sm'>
									<view class='margin-right inline'>
										<Time :time='item.timestamp'></Time>
									</view>
									<text>{{ userMap.get(item.fromId)?.name }}</text>
								</view>
								<view class='content shadow break-word'>
									<message-view :item='item'></message-view>
								</view>
								<quote-message :message="item" v-if="item.extend?.quoteMessage" />
								<view v-if="chat && chat.type === ChatType.FRIEND && item.fromId === user?.id"
									class="read-tips"
									:class='!chat.lastReadTime || item.timestamp > chat.lastReadTime?"":"read"'>
									{{ !chat?.lastReadTime || item.timestamp > chat?.lastReadTime ? '未读' : '已读' }}
								</view>
							</view>
							<view>
								<vim-avatar :size="'small'" :img="userMap.get(item.fromId)?.avatar"
									:name="userMap.get(item.fromId)?.name" />
							</view>
							<view v-if="showMultipleCheck" class="padding-left">
								<checkbox :value="item" style="transform:scale(0.7)" />
							</view>
						</view>
						<view v-if='!item.mine' class='cu-item' :id="`m-${item.id}`">
							<view v-if="showMultipleCheck" class="padding-right">
								<checkbox :value="item" style="transform:scale(0.7)" />
							</view>
							<view class='flex flex-direction'>
								<vim-avatar :size="'small'" :img="userMap.get(item.fromId)?.avatar"
									:name="userMap.get(item.fromId)?.name" />
							</view>
							<view class='main' style='display: block;'>
								<view class='text-gray text-sm padding-bottom-sm'>
									<text>{{ userMap.get(item.fromId)?.name }}</text>
									<view class='margin-left inline'>
										<Time :time='item.timestamp'></Time>
									</view>
								</view>
								<view class='content shadow break-word'>
									<message-view :item='item'></message-view>
								</view>
								<quote-message :message="item" v-if="item.extend?.quoteMessage" />
							</view>
						</view>
					</view>
				</template>
				<view v-if='messageList' :id="'m-last'"></view>
			</checkbox-group>
		</scroll-view>
		<view class="im-chat-details" v-if="details.show&&chat.id=='1'">
			<view class="im-chat-details-left">
				<image class="imageIm" :src="details.webUrl"  @tap="preImg(details.webUrl)"></image>
				<q-preview-image ref="previewImage" :urls="[details.webUrl]"></q-preview-image>
			</view>
			<view class="im-chat-details-right">
				<p>{{details.goodsName.slice(0,35)}}</p>
				<p class="details-line"> <span class="details-price">￥{{details.price}}</span><span class="details-send"
						@click="detailsSend()">发送商品</span></p>
			</view>
			<view class="im-chat-details-center">
				<span class="im-chat-details-center-span" @click="details.show=false">X</span>
			</view>
		</view>
		<view class="kjy" v-if="form.show">
			<view class="kjy-main">
				<view class="dwzx" @click="showlist()">
					<p>点我</p>
					<p>咨询</p>
				</view>
				<span>
					<img alt="摇头玩偶" class="doll"	src="/static/renou.png">
				</span>
				
				<uni-transition ref="ani" custom-class="transition" mode-class="fade" :show="listShow">
					<view class="kjy-list" v-if="listShow">
						<p @click="kjhf(item.id)" v-for="item in form.kjmessageList" class="kjxx">
							{{item.title}}
						</p>
					</view>
				</uni-transition>
			</view>
		</view>

		<view class='cu-bar foot input' style="background-color: #dcdada;" v-if="isValidatedUser" :style="chatStore.quoteMessage?'min-height:5rem':''">
			<!-- #ifdef APP-PLUS -->
			<view class='action' @tap='changeSendType'>
				<text class='text-grey'
					:class="{'cuIcon-sound':sendType === 'keyboard','cuIcon-keyboard':sendType === 'voice'}"></text>
			</view>
			<!-- #endif -->
			<view class="flex-sub" v-if="sendType === 'keyboard'">
				<input :always-embed='true' :adjust-position='true' cursor-spacing='30' v-model='messageContent'
					class='solid-bottom' :focus='false' maxlength='300' @input='handleShowAt' />
				<handle-quote-message v-if="chatStore.quoteMessage" :message="chatStore.quoteMessage" />
			</view>
			<view v-if="sendType === 'keyboard'" class='action'>
				<text v-if="huawei" class='cuIcon-add text-grey' @tap='showFace=true'></text>
			</view>
			<button v-if="sendType === 'keyboard' && isValidatedUser" class='cu-btn bg-green shadow'
				@tap='mineSend'>发送</button>
			
			<voice v-if="sendType === 'voice'" @uploadCallback='uploadCallback'></voice>
		</view>
		<view class="cu-modal bottom-modal" :class="showKjy?'show':''" @tap="showKjy=false">
			<view class="cu-dialog" style="padding: 20rpx;">
				<p style="font-weight: 700;">{{form.details}}</p>
				<image show-menu-by-longpress="true" @click="preview(form.pictures)" v-if="form.pictures"
					style="margin-top: 20rpx;" :src="form.pictures" mode=""></image>
			</view>
		</view>
		<view class='cu-bar foot input' v-if="!isValidatedUser">
			<view class="text-center" style="flex: 1">已退群</view>
		</view>

		<view class='cu-modal bottom-modal' :class="showFace?'show':''" @tap='showFace=false'>
			<view class='cu-dialog'>
				<Faces @click='showFace = true' class='faces-box' @insertFace='insertFace'></Faces>
				<vim-upload v-if="chat" :chat-type="chat.type" :chat-id="chat.id"></vim-upload>
			</view>
		</view>

		<view class='cu-modal bottom-modal' :class="showAt?'show':''" @tap.stop='handleHideAt'>
			<view class='cu-dialog'>
				<view>
					<input type="text" v-model="keyword" placeholder="请输入过滤条件" style="height: 80upx" />
				</view>
				<view class='cu-list menu menu-margin at-box'>
					<view v-if='isMaster' class='cu-item' @tap="handleAtUser('所有人')">
						<view class='content'>
							<text class='text-grey'>所有人</text>
						</view>
					</view>
					<view class='cu-item' v-for='(user, index) in  keywordFilter([...userMap.values()],keyword)'
						:key='index' @tap="handleAtUser(user.name)">
						<view class='content'>
							<text class='text-grey'>{{ user.name }}</text>
						</view>
					</view>
				</view>
			</view>
		</view>
		<multiple-forward v-if="showMultipleCheck"></multiple-forward>
	</view>
</template>

<script setup lang='ts'>
	import {
		useChatStore
	} from '@/store/chatStore'
	import {
		useUserStore
	} from '@/store/userStore'
	import {
		computed,
		getCurrentInstance,
		ref,
		reactive,
		onBeforeMount,
		onMounted
	} from 'vue'
	import MessageUtils from "@/utils/MessageUtils";
	import uniFab from '@/components/uni-fab/uni-fab.vue';
	import Time from '@/components/Time.vue'
	import MessageView from '@/components/MessageView.vue'
	import Voice from '@/components/Voice.vue'
	import Faces from '@/components/Faces.vue'
	import VimUpload from '@/components/VimUpload.vue'
	import type Message from '@/mode/Message'
	import MessageType from '@/utils/MessageType'
	import {
		onBackPress,
		onHide,
		onLoad,
		onShow,
		onUnload,
	} from '@dcloudio/uni-app'
	import CuCustom from '@/colorui/components/cu-custom.vue'
	import ChatType from '@/utils/ChatType'
	import type ChatSimple from '@/mode/ChatSimple'
	import type Extend from '@/mode/Extend'
	import {
		useWsStore
	} from '@/store/WsStore'
	import {
		match
	} from "pinyin-pro";
	import {
		imageLoad,
		last
	} from "@/hooks/useMessageImageLoad";
	import {
		count,
		isValidatedUser,
		isMaster,
		loadUserOrGroup,
		users
	} from "@/hooks/useChatInit";
	import {
		storeToRefs
	} from "pinia";
	import QuoteMessage from "@/components/QuoteMessage.vue";
	import HandleQuoteMessage from "@/components/HandleQuoteMessage.vue";
	import MessageEvent from "@/components/messages/MessageEvent.vue";
	import MessageApi from "@/api/MessageApi";
	import VimAvatar from "@/components/VimAvatar.vue";
	import {
		useMessageStore
	} from "@/store/messageStore";
	import MultipleForward from "@/components/MultipleForward.vue";
	import LoadMapUser from "@/components/LoadMapUser.vue";
	import QPreviewImage from "@/uni_modules/q-previewImage/components/q-previewImage/q-previewImage.vue";
	const previewImage = ref(null);
	const pattern = reactive({
		color: '#7A7E83',
		backgroundColor: '#fff',
		selectedColor: '#007AFF',
		buttonColor: '#007AFF',
		iconColor: '#fff',
		icon: 'chat-filled',
	});
	const content = reactive([]);
	const details = reactive({
		show: false,
		id: '',
		goodsName: '',
		webUrl: '',
		price: '',
	});
	const form = reactive({
		show: false,
		details: '',
		pictures: '',
		kjmessageList: {},
	});
	//是否展示快捷语
	const showKjy = ref(false);
	const listShow = ref(false);
	//@ts-ignore
	const {
		proxy
	} = getCurrentInstance()
	const chatStore = useChatStore()
	const userStore = useUserStore()
	const wsStore = useWsStore()
	//当前聊天室id
	const id = ref()
	const sendType = ref('keyboard')
	const customBar = ref(proxy.customBar)
	//是否展示多选
	const {
		showMultipleCheck
	} = storeToRefs(useMessageStore())
	//是否展示表情
	const showFace = ref(false)
	//是否展示加号
	const huawei = ref(true)

	//是否展示@
	const showAt = ref(false)
	//输入框的内容
	const messageContent = ref('')
	//过滤关键词
	const keyword = ref('')
	//当前聊天
	const chat = computed(() => {
		if (chatStore.openChatId) {
			return chatStore.getChat(chatStore.openChatId)
		} else {
			return undefined
		}
	})
	const showlist = () => {
		listShow.value = !listShow.value
	};
	// 查看照片
	const preImg = (url: string) => {
		previewImage.value?.open(url)
	}

	//聊天对象,
	const {
		userMap
	} = storeToRefs(userStore)
	//消息列表
	const messageList = computed(() => {
		return chatStore.getChatMessage(id.value) ?? []
	})

	//当前用户
	const user = userStore.getUser()

	onBackPress(() => {
		chatStore.setOpenChatId('')
	})
	onUnload(() => {
		chatStore.setOpenChatId('')
	})
	onHide(() => {
		chatStore.setOpenChatId('')
	})

	const changeSendType = () => {
		sendType.value === 'keyboard' ? sendType.value = 'voice' : sendType.value = 'keyboard'
	}
	//多选
	const checkboxChange = (e: any) => {
		useMessageStore().setCheckList(e.detail.value)
	}
	//获取聊天室id
	onLoad((opt) => {
		let userAgent = navigator.userAgent
		if (userAgent.match(/huawei/i)) {
			huawei.value=false
		}
		id.value = opt?.id
		// chat.value = chatStore.getChat(opt?.id);
		chatStore.setOpenChatId(id.value)
		if (chat.value && ChatType.FRIEND === chat.value.type && user) {
			//获取读取消息的时间,这里要颠倒下，是查询对方的读取时间，不是自己的
			//所以聊天室chatId是自己,fromId是对方
			MessageApi.getReadTime(user.id, chat.value.id).then((res) => {
				if (res.data) {
					chatStore.setCurrentChatLastReadTime(parseInt(res.data))
				}
			})
		}
		if (wsStore.wsRequest.socket?.readyState === 1) {
			wsStore.checkStatus()
		} else {
			wsStore.close(true)
			wsStore.init()
		}
	})

	const keywordFilter = (items: ChatSimple[], keyword: string): ChatSimple[] => {
		return items.filter((item) => {
			return !!(keyword.trim() === '' || match(item.name, keyword))
		})
	}
	const kjhf = (id) => {
		const userId = id;
		form.pictures = '';
		MessageApi.Shortcuthf(userId).then((res) => {
			form.details = res.data.details;
			if (res.data.pictures != null) {
				form.pictures = 'https://vim.taohaowan.com/' + res.data.pictures;
			}
			showKjy.value = true;
		});
		listShow.value = false;
		
	};
	//获取快捷语信息
	const kefuSend = () => {
		if (user?.id == '1') {
			form.show = false;
		} else {
			form.show = true;
		}
		if (user) {
			const userId = chat.value?.id
			MessageApi.Shortcut(userId).then((res) => {
				const ary = res.data.slice(0, 5)
				form.kjmessageList = ary;
				ary.forEach(res => {
					let query = {
						id: res.id,
						iconPath: '/static/icon.jpg',
						selectedIconPath: '/static/icon.jpg',
						text: res.title,
						active: false
					}
					content.push(query)
				})
			});
		}
	};

	const handleScroll = () => {
		last.value = ''
	}

	onShow(() => {
		chatStore.setOpenChatId(id.value)
		if (chat.value) {
			if (user) {
				if (chat.value.type == 0) {
					kefuSend();
				}
				loadUserOrGroup(chat.value, user)
			}
			//延迟1秒发生已读回执消息
			setTimeout(function() {
				readMessage()
			}, 1000)
			//重写 callback 方法，收到的消息后滚动到最下面
			wsStore.callBack(() => {
				if (chat.value && chatStore.openChatId === chat.value.id) {
					imageLoad(messageList.value)
				}
			})
		}
	})
	onBeforeMount(() => {
		if (Number(chat.value?.id) == 1) {
			const data = JSON.parse(userStore.getDetails())
			if (data != null) {
				details.goodsName = data.goodsName;
				details.price = data.price;
				details.webUrl = data.webUrl;
				details.id = data.id;
				details.show = true;
			}
		} else {
			details.show = false;
		}
	})


	/**
	 * 展示聊天室信息
	 */
	const chatInfo = () => {
		if (chat.value) {
			if (ChatType.GROUP === chat.value.type) {
				uni.navigateTo({
					url: '/pages/group/group?id=' + chat.value.id
				})
			} else {
				uni.navigateTo({
					url: '/pages/pub/user?id=' + chat.value.id
				})
			}
		}
	}



	const uploadCallback = (extend: Extend, messageType: string) => {
		if (user && chat.value) {
			let msg: Message = {
				messageType: messageType,
				chatId: chat.value.id,
				fromId: user.id,
				content: '',
				type: chat.value.type,
				extend: extend
			}
			wsStore.sendMessage(msg)
		}
	}

	const getAtUserIds = (str: string): Array < string > => {
		if (users.value) {
			const regex = /@\[([^\]]+)\]/g
			let match
			const usernames = new Array < string > ()
			while ((match = regex.exec(str)) !== null) {
				usernames.push(match[1])
			}
			const ids = users.value
				.filter((user) => {
					return usernames.indexOf(user.name) > -1
				})
				.map((user) => {
					return user.id
				})
			return Array.from(new Set(ids))
		} else {
			return []
		}
	}
	/**
	 * 发送消息
	 */
	const detailsSend = (): void => {
		if (user && isValidatedUser.value && chat.value) {
			const msg: Message = {
				messageType: MessageType.text,
				chatId: chat.value.id,
				fromId: user?.id,
				mine: true,
				content: `
				<div>
				<div style='display: flex;align-items: center;justify-content: space-between;background: #f7f7f7;padding:5px;border-radius:5px;font-size:13px;'>
				<img src="${details?.webUrl}" style='vertical-align: middle;width:100px;height:80px;'>
				<div style='margin-left: 20px;'>
				<p style='color:#747675'>${details?.goodsName.slice(0,20)}</p>
				<p style='margin:10px 0;color:black'><span>编号:</span>${details?.id}</p>
				<p style='color:red;'><span>价格:￥</span>${details?.price}</p></div>
				</div>
				</div>`,
				timestamp: new Date().getTime(),
				type: chat.value.type
			}
			wsStore.sendMessage(msg);
			messageContent.value = '';
			chatStore.setQuoteMessage(undefined);
			details.show = false;
		}
	}

	const mineSend = (): void => {
		if(messageContent.value==''){
			MessageUtils.message('不能发送空白信息!');
			return;
		}
		if (messageContent.value && messageContent.value.trim() !== '' && user && chat.value) {
			let msg: Message = {
				messageType: MessageType.text,
				chatId: chat.value.id,
				fromId: user.id,
				content: messageContent.value,
				type: chat.value.type
			}
			msg.extend = {
				atAll: isMaster.value && msg.content.includes('@[所有人]'),
				atUserIds: getAtUserIds(msg.content)
			}
			if (chatStore.quoteMessage) {
				msg.extend = {
					quoteMessage: chatStore.quoteMessage,
				}
			}
			wsStore.sendMessage(msg)
			messageContent.value = ''
			chatStore.setQuoteMessage(undefined);
		}
	}

	//添加表情
	const insertFace = (item: string) => {
		messageContent.value = `${messageContent.value}face${item}`
		showFace.value = false
	}

	const handleAtUser = (username: string) => {
		messageContent.value = `${messageContent.value}[${username}]`
		showAt.value = false
	}

	/**
	 * 显示@
	 */
	const handleShowAt = () => {
		if (chat.value && chat.value.type === ChatType.GROUP && messageContent.value.endsWith('@')) {
			showAt.value = true
		}
	}
	/**
	 * 隐藏@
	 * @param e TouchEvent
	 */
	const handleHideAt = (e: TouchEvent) => {
		e.stopPropagation()
		showAt.value = false
	}
	/**
	 * 用户点击消息列表某个聊天场景
	 */
	const readMessage = () => {
		if (user && chat.value) {
			let read = {
				chatId: chat.value.id,
				userId: user.id,
				timestamp: new Date().getTime(),
				type: chat.value.type
			}
			wsStore.sendRead(read)
		}
	}
</script>

<style scoped>
	.animal {
		animation: animal 1s infinite linear;
		-webkit-animation: animal 1s infinite linear;
		-webkit-transform-origin: center center;
		-ms-transform-origin: center center;
		transform-origin: center center;
	}
	
	@keyframes animal {
		0% {
			transform: scale(0.5, 0.5);
			-ms-transform: scale(0.5, 0.5);
			-webkit-transform: scale(0.5, 0.5);
		}
	
		100% {
			transform: scale(1.0, 1.0);
			-ms-transform: scale(1.0, 1.0);
			-webkit-transform: scale(1.0, 1.0);
		}
	}
	.warp {
		padding: 10px;
	}

	.button {
		margin-bottom: 10px;
	}
	.solid-bottom{
		background-color: #fff;
		border-radius: 20rpx;
		padding-left: 20rpx;
	}

	.im-chat-details {
		width: 100%;
		margin: auto;
		display: flex;
		justify-content: space-around;
		align-items: center;
		background-color: #f7f1f1;
		position: fixed;
		top:0;
		left: 0;
	}

	.im-chat-details-left {
		width: 40%;
		padding: 10rpx 20rpx;

		.imageIm {
			width: 100%;
			height: 150rpx!important;
		}
	}

	.im-chat-details-center {
		span {
			cursor: pointer;
			position: relative;
			top: -60rpx;
			right: 20rpx;
		}
	}

	.im-chat-details-right {
		width: 60%;
		padding: 20rpx 40rpx;

		.details-line {
			margin-top: 20rpx;
			display: flex;
			justify-content: space-between;
			align-items: center;
		}

		.details-id {
			margin-right: 40rpx;
		}

		.details-price {
			color: red;
			margin-right: 40rpx;
		}

		.details-send {
			padding: 10rpx;
			border-radius: 10rpx;
			background-color: #fd0202;
			color: white;
			margin-right: 40rpx;
			cursor: pointer;
		}
	}

	.cu-chat {
		display: block;
		background-color: #eee;
	}

	.faces-box {
		height: auto;
	}

	.inline {
		display: inline-block;
	}

	.at-box {
		height: 50vh;
		bottom: 0;
		overflow-y: scroll
	}

	.break-word {
		word-wrap: break-word;
		word-break: break-all;
	}

	.read-tips {
		font-size: 20upx;
		line-height: 48upx;
	}

	.read {
		color: #5fb878;
	}

	.kjy {
		position: fixed;
		bottom: calc(1.5rem + var(--window-top));
		left: 40rpx;
		z-index: 11;
		padding: 20upx;
		display: flex;
		justify-content: space-around;
		align-items: center;
		background-color: transparent;

		.kjy-main {
			width: 300rpx;
			position: relative;
			top: 20rpx;
			left: -80rpx;
			display: flex;
			
			.dwzx{
				background-color: #fff;
				padding: 10rpx;
				border-radius: 10rpx;
				text-align: center;
				position: absolute;
				top: -2.5rem;
				right: 6rem;
				font-weight: 600;
			}
			
			.doll {
			  width: 200upx;
			  height: 200upx;
			}

			.kjy-list {
				position: absolute;
				bottom: 9rem;
				left:0;
			}
		}
	}

	.kjxx {
		width: 100%;
		text-align: center;
		font-size: 25upx;
		padding: 20upx;
		text-align: center;
		background-color: white;
	}
</style>