import * as RongIMLib from '@rongcloud/imlib-v4';

import socketConfig from './config';

import Notice from './notice';

import store from '@/store/index';

// import $request from '$utils/request';
import User from '$config/user';
import {NoticeType} from "$utils/socket/const";

export {
    RongIMLib
}

class Socket extends Notice {

    // socket 对象
    private socket=undefined;

    // 链接成功的用户信息
    private socketUser=undefined;

    // 安装 socket
    install(user:Record<string, any>){

        return new Promise<void>( (resolve, reject)=>{

            if (this.socketUser !== undefined) resolve();

            if (this.socket === undefined) {
                this.socket = RongIMLib.init({
                    appkey: socketConfig.appKey,
                    logLevel: socketConfig.logLevel
                });

                // 添加事件监听
                this.socket.watch({
                    // 监听会话列表变更事件, 触发时机：会话状态变化（置顶、免打扰）、会话未读数变化（未读数增加、未读数清空）、会话 @ 信息、会话最后一条消息变化
                    conversation (event) {
                        return store.dispatch('mergeSessionList',event);
                    },
                    // 监听消息通知
                    message:({message})=>{

                        // 执行触发
                        this.triggerNotice(NoticeType.message, message,{
                            userId:message.senderUserId
                        });

                    },
                    // 监听 IM 连接状态变化
                    status (event) {
                        console.log(event);
                    }
                });
            }

            this.socket.connect({
                token:user.ry_token
            }).then((useUser)=>{
                this.socketUser = useUser;
                // 执行获取会话列表
                store.dispatch('getSessionListPromise');

                resolve();
            }).catch((fail)=>{
                this.socketUser = undefined;
                reject();
            });

        });
    }

    uninstall(){
        this.socketUser = undefined;
        if (this.socket) {
            this.socket.rtcInnerUnwatch && this.socket.rtcInnerUnwatch();
            this.socket.unwatch && this.socket.unwatch();
        }
        this.socket = undefined;
    }

    // 获取某人
    getConversation(uid){
        if (this.socket) {
            return this.socket.Conversation.get({
                targetId: uid.toString(),
                type: RongIMLib.CONVERSATION_TYPE.PRIVATE
            });
        } else {
            return  {};
        }
    }

    send(uid,content){
        let socketUser = this.getConversation(uid);
        if (socketUser) {
            socketUser.send(content);
        }
    }

    // 获取会话列表
    getConversationList(options){

        return  new Promise((resolve,reject)=>{
            if (this.socket) {
                return this.socket.Conversation.getList(options).then(resolve).catch(reject);
            } else {
                reject();
            }
        });

    }

    // 合并会话
    mergeConversation(data){
        if (this.socket) {
            return this.socket.Conversation.merge(data);
        }
    }

    // 添加用户
    addUser(data,user){
        if (data) {
            data.userInfo = {
                [user.uid]:{
                    uid:user.uid,
                    nick_name: user.nick_name,
                    head_pic: user.head_pic,
                    sex: user.sex,
                    birthday: user.birthday,
                    pid: user.pid
                },
                [User.uid()]:{
                    uid:User.user.uid,
                    nick_name: User.user.nick_name,
                    head_pic: User.user.head_pic,
                    sex: User.user.sex,
                    birthday: User.user.birthday,
                    pid: User.user.pid
                }
            }

            return  data;

        } else {
            return data;
        }
    }

}


export default Socket;
