import {
	getUserimInfo
} from '@/api/members';

import {
	TUILogin
} from '@tencentcloud/tui-core';

import {
	TUIConversationService,
} from '@tencentcloud/chat-uikit-engine';


import {
	TUIGlobal
} from '@tencentcloud/universal-api';


import * as Push from '@/uni_modules/TencentCloud-Push';

import storage from "@/utils/storage.js";

// sdkStateNotReady IM断了
// onMessageReceived 收到推送的单聊、群聊、群提示、群系统通知的新消息

// im断开链接时
const onSdkNotReady = function(event) {
	console.log('IM断了')
	var islogin = storage.getVlogUserInfo();
	if (islogin != null) {
		// 重新执行IM登录
		loginIm()
	}
}

const onMessageReceived = function(event) {
	// event.data - 存储 Message 对象的数组 - [Message]
	// 这里处理消息通知相关业务，4.0版本后续进行开发
	console.log('收到了消息通知内容')
	console.log(event.data)
}

const pushClick = (res) => {
	console.log('notification clicked', res);
	// 解析扩展信息，跳转到相应的会话（代码仅供参考，发布前需要完善）
	try {
		const data = JSON.parse(res.data);
		const conv_type = data?.entity?.chatType === 1 ? 'C2C' : 'GROUP';
		// 根据推送信息拼的 conversationID
		const conversationID = `${conv_type}${data.entity.sender}`;
		// 切换会话
		TUIConversationService.switchConversation(conversationID);
		const chatPath = '/TUIKit/components/TUIChat/index';
		uni.navigateTo({
			url: chatPath
		});
	} catch (error) {
		console.log('error', error);
	}
}

const pushOnLine = (res) => {
	// res 为消息内容
	console.log('在线推送', res);
}

const pushMsgBack = (res) => {
	// res 为被撤回的消息 ID
	console.log('撤回消息推送', res);
}



export const loginIm = () => {
	console.log('执行im登录')
	getUserimInfo()
		.then(({
			data
		}) => {
			console.log(data)
			if (data.code == 200) {
				const par = data.result;
				TUILogin.login({
					SDKAppID: par.sdkAppId,
					userID: par.userID,
					userSig: par.userSig,
					useUploadPlugin: true, // If you need to send rich media messages, please set to true.
					framework: `vue2` // framework used vue2 / vue3
				}).then((res) => {

					var {
						SDKAppID,
						userID,
						userSig,
						chat
					} = TUILogin.getContext();
					getApp().globalData.chat = chat;
					console.log('我是个老板', res)
					// 每次登录先移除，避免多次监听
					chat.off('sdkStateNotReady', onSdkNotReady);
					chat.off('onMessageReceived', onMessageReceived);
					// 监听im断开链接后重新链接
					chat.on('sdkStateNotReady', onSdkNotReady);
					// 监听消息通知
					chat.on('onMessageReceived', onMessageReceived);


					Push.setRegistrationID(par.userID, () => {
						console.log('设置id设置id设置id设置id设置id设置id设置id设置id设置id设置id', par.userID);

						Push.registerPush(
							par.sdkAppId,
							'vkFpe55aYqfV7Sk5uGaoxhEstJ3tcI9dquk7JwG1GloDSLD2HeMWeQweWWXgNlhC',
							(data) => {
								console.log('registerPush ok', data);
								Push.getRegistrationID((registrationID) => {
									console.log('getRegistrationID ok',
										registrationID);
								});
							},
							(errCode, errMsg) => {
								console.error('registerPush failed', errCode, errMsg);
							}
						);
					});
					// 监听通知栏点击事件，获取推送扩展信息
					Push.addPushListener(Push.EVENT.NOTIFICATION_CLICKED, pushClick);
					// 监听在线推送
					Push.addPushListener(Push.EVENT.MESSAGE_RECEIVED, pushOnLine);
					// 监听在线推送被撤回
					Push.addPushListener(Push.EVENT.MESSAGE_REVOKED, pushMsgBack);
				});
			} else {
				// 接口返回非 200 状态码，跳转登录页面
				uni.navigateTo({
					url: '/pages/passport/login'
				});
			}
		})
		.catch((e) => {
			console.log(e)
		});
}

export const clearIm = async () => {
	var chat = getApp().globalData.chat;
	var res_out = await chat.logout()
	console.log(res_out)
	console.log('IM退出登录')
	getApp().globalData.chat = null;
	// chat.logout中做了关闭推送服务
	// Push.unRegisterPush().then(res => {
	// 	//反注册关闭推送服务
	// 	console.log(res)
	// 	console.log('反注册关闭推送服务')
	// })
	Push.removePushListener(Push.EVENT.NOTIFICATION_CLICKED, pushClick)
	Push.removePushListener(Push.EVENT.MESSAGE_RECEIVED, pushOnLine)
	Push.removePushListener(Push.EVENT.MESSAGE_REVOKED, pushMsgBack)
}

export const conversationData = async () => {
	// 会话列表
	try {
		const chatInstance = getApp().globalData.chat
		console.log(chatInstance)
		var res = await chatInstance.getConversationList()
		return res
	} catch (err) {
		console.log(err)
	}
}

export const sendVlogCustomMsg = async (i, vlogItem) => {
	// i=IM相关用户信息 
	console.log(i);
	console.log(vlogItem);
	try {
		var chat = getApp().globalData.chat;
		var conversationType = i.type;
		if (conversationType == 'C2C') {
			var to = i.userProfile.userID;
		} else {
			var to = i.groupProfile.groupID;
		}
		var message = chat.createCustomMessage({
			to,
			conversationType,
			payload: {
				data: JSON.stringify({
					businessID: 'video',
					title: vlogItem.vlogerName,
					description: vlogItem.content,
					price: '分享好视频',
					link: '/pages/me/vlog?vlogId=' + vlogItem.vlogId,
					imageUrl: vlogItem.cover || vlogItem.firstFrameImg
				}),
				description: '[分享视频]',
				extension: '',

			},
			cloudCustomData: JSON.stringify({
				pushTitle: vlogItem.vlogerName,
				pushDesc: vlogItem.content,
				businessID: 'video', // 保持一致
			})
		})
		var result = await chat.sendMessage(message)
		console.log('发送成功：', result);
		return result; // 成功就把发送结果返回出去
	} catch (err) {
		console.log(err);
		throw err;
	}

}