import GoEasyIM from '@/common/goeasy-im-1.3.1.js';

function Friend(uuid, name, avatar) {
	this.uuid = uuid;
	this.name = name;
	this.avatar = avatar;
}


function CurrentUser(uuid, name, avatar) {
	this.uuid = uuid;
	this.name = name;
	this.avatar = avatar;
}
//初始化
function IMService() {
	this.im = GoEasyIM.getInstance({
		host: 'hangzhou.goeasy.io', //应用所在的区域地址: [hangzhou.goeasy.io, 新加坡暂不支持IM，敬请期待]
		 appkey: "BC-eef530bc08134a22b2a58ec8f8da0b25" //测试  
		// appkey: "BC-f420edb1a2c24b97ad43a55299987a85" //测试
		//appkey: "BC-087763b7d212460484b71bffeaecb359" //
	});
	console.log(this.im)
	//当前“我”
	this.currentUser = null;
	//我的好友
	this.friends = {};
	//私聊消息记录，map格式，每个好友对应一个数组
	this.privateMessages = {};
	//收到一条私聊消息
	this.onNewPrivateMessageReceive = function(friendId, message) {};
	this.onConversationsUpdate = function(conversations) {};
}

IMService.prototype.login = function(user) {
	console.log(user)
	if (user) {
		//初始化当前用户
		this.currentUser = new CurrentUser(user.flag, user.nickname, user.avatar);
		return true;
	} else {
		return false;
	}
};
IMService.prototype.getPrivateMessages = function(friendId) {
	console.log(this.privateMessages)
	if (!this.privateMessages[friendId]) {
		this.privateMessages[friendId] = {
			sentMessages: [],
			pendingMessages: []
		};
	}
	return this.privateMessages[friendId]
};

//连接GoEasy
IMService.prototype.connectIM = function() {
	this.initialIMListeners();
	this.im.connect({
		id: this.currentUser.uuid,
		data: {
			avatar: this.currentUser.avatar,
			name: this.currentUser.name
		}
	}).then(() => {
		console.log('connect成功')
	}).catch(error => {
		console.log('connect失败,请确保网络正常，appkey和host正确，code:' + error.code + " content:" + error.content);
	});
};
IMService.prototype.initialIMListeners = function() {
	this.im.on(GoEasyIM.EVENT.CONNECTED, () => {
		console.log('连接成功.')
	});

	this.im.on(GoEasyIM.EVENT.DISCONNECTED, () => {
		console.log('连接断开.')
	});

	this.im.on(GoEasyIM.EVENT.CONNECTING, (times) => {
		console.log('连接中', times);
	});

	//监听会话列表
	this.im.on(GoEasyIM.EVENT.CONVERSATIONS_UPDATED, (conversations) => {
		this.conversations = conversations;
		this.onConversationsUpdate(this.conversations)
	});

	//监听私聊消息
	this.im.on(GoEasyIM.EVENT.PRIVATE_MESSAGE_RECEIVED, (message) => {
		//更新私聊消息记录
		let friendId;

		if (this.currentUser.uuid == message.senderId) {
			friendId = message.receiverId;
		} else {
			friendId = message.senderId;
		}
		removePrivatePendingMessage(this, friendId, message);
		let friendMessages = this.getPrivateMessages(friendId);
		friendMessages.sentMessages.push(message);
		//如果页面传入了相应的listener，执行listener
		this.onNewPrivateMessageReceive(friendId, message);
	});
};
//加载单聊历史消息
IMService.prototype.loadPrivateHistoryMessage = function(friendId, timeStamp) {
	return new Promise((resolve, reject) => {
		this.im.history({
			friendId: friendId,
			lastTimestamp: timeStamp
		}).then(result => {
			let history = result.content;
			let privateMessages = this.getPrivateMessages(friendId);
			let friendMessages = privateMessages.sentMessages;
			for (let i = history.length - 1; i >= 0; i--) {
				friendMessages.unshift(history[i])
			}
			resolve(friendMessages)
		}).catch(error => {
			if (error.code == 401) {
				console.log("您尚未开通历史消息，请登录GoEasy，查看应用详情里自助启用.");
			}
			reject(error)
		});
	})
};

function removePrivatePendingMessage(imService, friendId, message) {
	let privateMessages = imService.getPrivateMessages(friendId);
	let pendingMessages = privateMessages.pendingMessages;
	let pendingMessageIndex = pendingMessages.findIndex(item => item.messageId == message.messageId);
	if (pendingMessageIndex > -1) {
		pendingMessages.splice(pendingMessageIndex, 1);
	}
}
//发送私聊消息
IMService.prototype.sendPrivateTextMessage = function(friendId, text) {
	let textMessage = this.im.createTextMessage({
		text: text
	});
	this.sendPrivateMessage(friendId, textMessage);
};

//私聊图片消息
IMService.prototype.sendPrivateImageMessage = function(friendId, imageFile) {
	let imageMessage = this.im.createImageMessage({
		file: imageFile,
		onProgress: function(progress) {
			console.log(progress)
		}
	});
	this.sendPrivateMessage(friendId, imageMessage);
};

//私聊视频消息
IMService.prototype.sendPrivateVideoMessage = function(friendId, videoFile) {
	let videoMessage = this.im.createVideoMessage({
		file: videoFile,
		onProgress: function(progress) {
			console.log(progress)
		}
	});
	this.sendPrivateMessage(friendId, videoMessage);
};

IMService.prototype.sendPrivateAudioMessage = function(friendId, audiofile) {
	let audioMessage = this.im.createAudioMessage({
		file: audiofile,
		onProgress: function(progress) {
			console.log(progress)
		}
	});

	this.sendPrivateMessage(friendId, audioMessage);
};

//发送私聊消息
IMService.prototype.sendPrivateMessage = function(friendId, message) {
	console.log(friendId, message)
	//添加到消息中
	let privateMessages = this.getPrivateMessages(friendId);
	privateMessages.pendingMessages.push(message);

	//发送
	this.im.sendPrivateMessage(friendId, message)
		.then((res) => {
			console.log(res)
		})
		.catch(e => {
			console.log(e)
		})
};

IMService.prototype.markPrivateMessageAsRead = function(friendId) {
	this.im.markPrivateMessageAsRead(friendId)
		.then(res => {
			console.log('标记为已读成功')
		})
		.catch(e => {
			console.log(e)
		})
};

IMService.prototype.disconnect = function() {
	return this.im.disconnect()
};

IMService.prototype.latestConversations = function() {
	let promise = this.im.latestConversations();
	promise.then((conversations) => {
		this.conversations = conversations
	});
	return promise
};

IMService.prototype.topPrivateConversation = function(userId, isTop) {
	let promise = this.im.topPrivateConversation(userId, isTop);
	promise.then(res => {
		console.log(res)
	}).catch(e => {
		console.log(e)
	});
	return promise
};

IMService.prototype.removePrivateConversation = function(friendId) {
	let promise = this.im.removePrivateConversation(friendId);
	promise.then(res => {
		console.log(res)
	}).catch(e => {
		console.log(e)
	});
	return promise
};


IMService.prototype.sendCustomMessage = function(id, type, options) {
	let customMessage = this.im.createCustomMessage(options);
	let promise = null;
	if (type == 'private') {
		promise = this.im.sendPrivateMessage(id, customMessage)
	} else {
		promise = this.im.sendGroupMessage(id, customMessage)
	}
	return promise
};
export default IMService;
