<script setup>
// 消息首页

import api from '@/api/index.js'
import {
	onMounted, onUnmounted,
	ref,
	reactive,
	getCurrentInstance,
} from 'vue';
import {
	onLoad,
	onReady,
	onHide,
	onPullDownRefresh,
	onReachBottom,
} from '@dcloudio/uni-app'
// 路由
import util from '@/common/js/util.js'
// 腾讯云聊天
import TencentCloudChat from '@tencentcloud/chat';

const chatList = reactive([])

// 用户信息
const userinfo = JSON.parse(uni.getStorageSync('userinfo'))

// 右滑菜单
const rightOption = [{
	text: '删除',
	style: {
		backgroundColor: '#F85050'
	},
	fn: (item) => delMsg(item)
}, {
	text: '设为已读',
	style: {
		backgroundColor: '#00ADEE'
	},
	fn: (item) => setRead(item)
},]

onMounted(() => {
	getList()
	addListener()
})

onUnmounted(() => {
	removeListener()
})

// 开启监听消息
function addListener() {
	let onMessageReceived = function (event) {
		getList()
	}

	uni.$chat.on(TencentCloudChat.EVENT.CONVERSATION_LIST_UPDATED, onMessageReceived);
}

// 移除监听
function removeListener() {
	uni.$chat.on(TencentCloudChat.EVENT.CONVERSATION_LIST_UPDATED);
}

// 获取消息列表
function getList() {
	api.news.getMessageList({
		query: {
			userId: userinfo.serviceId,
		}
	}).then(rs => {
		if (rs.code == 200) {
			chatList.push(...rs.data.map(item => {
				item.callbackData = JSON.parse(item.callbackJson)
				
				if (item.callbackData.callback_json.length) {
					let msgType = item.callbackData.callback_json[0].MsgType;
					if (msgType == TencentCloudChat.TYPES.MSG_TEXT) {
						item.chatText = item.callbackData.callback_json[0].MsgContent.Text
					} else if (msgType == TencentCloudChat.TYPES.MSG_IMAGE) {
						item.chatText = '[图片]'
					} else if (msgType == TencentCloudChat.TYPES.MSG_AUDIO) {
						item.chatText = '[语音]'
					} else if (msgType == TencentCloudChat.TYPES.MSG_VIDEO) {
						item.chatText = '[视频]'
					} else if (msgType == TencentCloudChat.TYPES.MSG_CUSTOM) {
						if (item.callbackData.callback_json[0].businessType == 'redPacket') {
							item.chatText = `[红包] ${item.callbackData.blessing}`
						}
					}
				}
				return item
			}))
			return
		}
		util.alert({
			content: rs.msg,
			showCancel: false,
		})
	})
}

// /**
//  * 去聊天
//  * @param {Number} item 聊天对象
//  */
// function handleChat(item) {
// 	// 
// }

// /**
//  * 跳转
//  * @param {String} url 路由地址
//  */
// function link(url) {
// 	uni.navigateTo({
// 		url,
// 	})
// }


// 退出登录
function handleLogout() {
	util.alert({
		content: '确认退出登录吗？',
	}).then(rs => {
		if (!rs.confirm) return

		util.logout(() => {
			// #ifdef APP
			plus.runtime.restart()
			// #endif
		})
	})
}




/**
 * 去聊天
 * @param {Object} item
 */
function handleChat(item) {
	let param = {};
	// 单聊
	if (item.groupId == null) {
		param.type = 'C2C'
		param.name = `${item.callbackJson.from_name}`
		param.msgId = `${item.callbackJson.from_id}`
	} else {
		// 群聊
		param.type = 'GROUP'
		param.name = `${item.groupChatDTO.name}`
		param.msgId = `${item.groupId}`
		param.num = `${item.groupChatDTO.memberCount}`
	}
	// 
	util.toChat(param)
}
/**
 * 菜单
 * @param {Object} ev 默认事件
 * @param {Object} item 单项
 */
function handleMenu(ev, item) {
	console.log('ev', ev, item)
	ev.content.fn(item)
	proxy.$refs.swipeAction.closeAll()
}

// 删除会话
function delMsg(item) {
	// 验证sdk是否准备完毕
	let isReady = uni.$chat.isReady();
	if (!isReady) {
		setTimeout(function () {
			delMsg(item);
		}, 200);
		return
	}

	let conversationId = item.groupId == null ? `C2C${item.fromId}` : `GROUP${item.groupId}`;

	uni.$chat.deleteConversation(conversationId).then(rs => {
		getList()
	})
}

// 标为已读
function setRead(item) {
	// 验证sdk是否准备完毕
	let isReady = uni.$chat.isReady();
	if (!isReady) {
		setTimeout(function () {
			setRead(item);
		}, 200);
		return
	}

	let conversationId = item.groupId == null ? `C2C${item.fromId}` : `GROUP${item.groupId}`;
	uni.$chat.setMessageRead({
		conversationID: conversationId,
	}).then(rs => {
		getList()
	})
}
</script>

<template>
	<view class="container">
		<view class="header pr ptb30 plr20">
			<image src="/static/mine-b.png" class="background pfull" mode="aspectFill" />
			<view class="content pr rows">
				<view class="avatar">
					<image class="wh120 cir" mode="aspectFill"
						src="https://p3-flow-imagex-sign.byteimg.com/user-avatar/9f4488a87a17f6f31b9716331e14fe26~tplv-a9rns2rl98-icon-tiny.jpeg?rk3s=98c978ad&x-expires=1740537084&x-signature=OrjX8tZaafN4XJE2o8QzZDs3Q20%3D" />
				</view>

				<view class="info f1 ml20">
					<view class="name c333 f34">{{ userinfo.serviceName }}</view>
					<view class="mt10 c666 f28">店铺客服</view>
				</view>
			</view>
			<view class="pr login-out">
				<view class="out-btn" @click="handleLogout">退出登录</view>
			</view>
		</view>

		<!-- 商家订单 -->
		<view class=" rows ptb30 plr20">
			<view class="">商家订单管理</view>
			<uni-icons type="right" />
		</view>

		<!-- <view class="list">
			<view class="item rows ptb20 plr20" v-for="(item, index) in chatList" :key="index"
				@click="handleChat(item)">
				<view class="avatar">
					<image :src="item.avatar" class="wh80 cir" />
				</view>

				<view class="info f1 ml20">
					<view class="rows">
						<view class="name c333 f28">{{ item.name }}</view>
						<view class="time c999 f22">2024.05.06 13:00</view>
					</view>

					<view class="rows">
						<view class="content mt10 c666 f24">{{ item.lastMessage }}</view>
						<view class="dot cfff f22">
							<view class="content" v-if="item.dot">{{ item.dot }}</view>
						</view>
					</view>
				</view>
			</view>
		</view> -->


		<view class="firendBox pr">
			<scroll-view scroll-y="true" class="scroll">
				<uni-swipe-action ref="swipeAction">
					<view class="list pb30">
						<uni-swipe-action-item :right-options="rightOption" v-for="(item, index) in chatList"
							:key="index" @click="handleMenu($event, item)">
							<view class="item rows ptb20 plr30" @click="handleChat(item)">
								<view class="image wh90 pr">
									<template v-if="item.groupId == null">
										<image class="cir wh90" :src="item.callbackJson.from_url" mode="aspectFill" />
									</template>
									<template v-else>
										<image class="cir wh90" :src="item.groupChatDTO.groupFaceUrl"
											mode="aspectFill" />
									</template>
									<view class="mark pa t0 r0 cfff f22 cir" v-if="item.unreadCount">{{ item.unreadCount
									}}
									</view>
								</view>
								<view class="col f1 ml20">
									<view class="rows">
										<template v-if="item.groupId == null">
											<view class="name f1 thd c333 f32">{{ item.callbackJson.from_name }}</view>
										</template>
										<template v-else>
											<view class="name f1 thd c333 f32">{{ item.groupChatDTO.name }}</view>
										</template>
										<view class="datetime c999 f22">
											{{ util.formatTime('MM-dd HH:mm', item.createTime) }}</view>
									</view>
									<view class="desc thd mt10 c666 f24">{{ item.chatText }}</view>
								</view>
							</view>
						</uni-swipe-action-item>
						<view class="mtb20 tac c999 f20">到底啦~</view>
					</view>
				</uni-swipe-action>
			</scroll-view>
		</view>
	</view>
</template>

<style lang="scss" scoped>
// 个人信息
.header {
	display: flex;
	justify-content: space-between;

	.background {
		width: 100%;
		height: 100%;
	}

	.login-out {
		display: table;

		.out-btn {
			display: table-cell;
			vertical-align: middle;
		}
	}
}

// 朋友列表
.firendBox {
	height: 100%;

	.scroll {
		height: 100%;
	}

	// 列表
	.list {

		// 消息提示点
		.mark,
		.dot {
			background-color: #FF6B17;
			text-align: center;
			line-height: 30rpx;
		}

		.mark {
			width: 30rpx;
			height: 30rpx;
		}

		.dot {
			width: 20rpx;
			height: 20rpx;
		}
	}
}


// // 
// .list {
// 	.item {
// 		border-top: 1rpx solid #eee;

// 		.dot {
// 			padding: 5rpx;
// 			border-radius: 100rpx;
// 			background-color: #f00;

// 			// 内容
// 			.content {
// 				display: flex;
// 				justify-content: center;
// 				align-items: center;
// 				width: 20rpx;
// 				height: 20rpx;
// 			}
// 		}
// 	}
// }</style>