package com.daya.live_teaching.im;

import android.content.Context;

import com.cooleshow.base.common.BaseApplication;
import com.cooleshow.base.utils.LogUtils;
import com.daya.live_teaching.R;
import com.daya.live_teaching.common.ErrorCode;
import com.daya.live_teaching.common.ResultCallback;
import com.daya.live_teaching.im.message.ApplyForSpeechMessage;
import com.daya.live_teaching.im.message.AssistantTransferMessage;
import com.daya.live_teaching.im.message.ControlDeviceNotifyMessage;
import com.daya.live_teaching.im.message.DeviceStateChangedMessage;
import com.daya.live_teaching.im.message.DisplayMessage;
import com.daya.live_teaching.im.message.ExamSongDownloadMessage;
import com.daya.live_teaching.im.message.ExamSongDownloadStatusMessage;
import com.daya.live_teaching.im.message.MemberChangedMessage;
import com.daya.live_teaching.im.message.MusicScoreDownloadMessage;
import com.daya.live_teaching.im.message.PlayMidiMessage;
import com.daya.live_teaching.im.message.RoleChangedMessage;
import com.daya.live_teaching.im.message.RoleSingleChangedMessage;
import com.daya.live_teaching.im.message.SpeechResultMessage;
import com.daya.live_teaching.im.message.TicketExpiredMessage;
import com.daya.live_teaching.im.message.TurnPageMessage;
import com.daya.live_teaching.im.message.UpgradeRoleMessage;
import com.daya.live_teaching.im.message.WhiteBoardMessage;
import com.daya.live_teaching.im.provider.ClassMemberChangedNotificationProvider;
import com.daya.live_teaching.im.provider.ClassTextMessageItemProvider;
import com.daya.live_teaching.im.provider.RoleChangedMessageItemProvider;
import com.daya.live_teaching.model.RoleChangedUser;

import io.rong.imkit.conversation.messgelist.provider.RCChatShareLiveProvider;
import io.rong.imkit.conversation.messgelist.provider.RCChatShareMusicProvider;
import io.rong.imkit.utils.helper.ConversationFilterHelper;
import io.rong.imkit.widget.RCChatShareLiveMessage;
import io.rong.imkit.widget.RCChatShareMusicMessage;

import java.util.ArrayList;
import java.util.List;

import io.rong.imkit.RongIM;
import io.rong.imkit.config.DataProcessor;
import io.rong.imkit.config.RongConfigCenter;
import io.rong.imkit.conversation.extension.RongExtensionManager;
import io.rong.imkit.conversation.messgelist.provider.AnnouncementProvider;
import io.rong.imkit.manager.UnReadMessageManager;
import io.rong.imkit.widget.CustomMessage;
import io.rong.imlib.IRongCallback;
import io.rong.imlib.RongIMClient;
import io.rong.imlib.model.Conversation;
import io.rong.imlib.model.MentionedInfo;
import io.rong.imlib.model.Message;
import io.rong.imlib.model.UserInfo;
import io.rong.message.TextMessage;
import io.rong.sight.SightExtensionModule;


/**
 * Rong IM 业务相关封装
 */
public class IMManager {
    private static final String TAG = IMManager.class.getSimpleName();
    private static IMManager sInstance;
    private final int DEFAULT_MESSAGE_COUNT = -1;//-1代表不拉取历史消息
    private List<RongIMClient.OnReceiveMessageListener> listenerList = new ArrayList<>();

    public static IMManager getInstance() {
        if (sInstance == null) {
            synchronized (IMManager.class) {
                if (sInstance == null) {
                    sInstance = new IMManager();
                }
            }
        }
        return sInstance;
    }

    private IMManager() {
    }

    /**
     * 初始化，需要在使用前初始化一次
     *
     * @param appkey
     * @param context
     */
    public static void init(Context context, String appkey) {
        final IMManager imManager = getInstance();
        RongIMClient.getInstance().setReconnectKickEnable(true);//是否踢出重连设备，在init之前调用 打开后会有连接被判定为重连

        /*
         * 初始化 SDK，在整个应用程序全局，只需要调用一次。建议在 Application 继承类中调用。
         */
        // 可在初始 SDK 时直接带入融云 IM 申请的APP KEY
        RongIM.init(BaseApplication.context, appkey, true);
        // 注册自定义消息
        RongIMClient.registerMessageType(ApplyForSpeechMessage.class);
        RongIMClient.registerMessageType(AssistantTransferMessage.class);
        RongIMClient.registerMessageType(ControlDeviceNotifyMessage.class);
        RongIMClient.registerMessageType(DeviceStateChangedMessage.class);
        RongIMClient.registerMessageType(DisplayMessage.class);
        RongIMClient.registerMessageType(MemberChangedMessage.class);
        RongIMClient.registerMessageType(RoleChangedMessage.class);
        RongIMClient.registerMessageType(SpeechResultMessage.class);
        RongIMClient.registerMessageType(TicketExpiredMessage.class);
        RongIMClient.registerMessageType(TurnPageMessage.class);
        RongIMClient.registerMessageType(UpgradeRoleMessage.class);
        RongIMClient.registerMessageType(WhiteBoardMessage.class);
        RongIMClient.registerMessageType(RoleSingleChangedMessage.class);
        RongIMClient.registerMessageType(ExamSongDownloadMessage.class);//伴奏下载
        RongIMClient.registerMessageType(PlayMidiMessage.class);//播放节拍器消息
        RongIMClient.registerMessageType(ExamSongDownloadStatusMessage.class);//学生伴奏下载状态
        RongIMClient.registerMessageType(MusicScoreDownloadMessage.class);//学生伴奏下载
        RongIMClient.registerMessageType(CustomMessage.class);//学生伴奏下载
        RongIMClient.registerMessageType(RCChatShareMusicMessage.class);//乐谱分享
        RongIMClient.registerMessageType(RCChatShareLiveMessage.class);//直播分享

        // 设置自定义文本显示
        RongIM.registerMessageTemplate(new ClassTextMessageItemProvider());
        RongIM.registerMessageTemplate(new ClassMemberChangedNotificationProvider());
        RongIM.registerMessageTemplate(new RoleChangedMessageItemProvider());
        RongIM.registerMessageTemplate(new AnnouncementProvider());
        RongIM.registerMessageTemplate(new RCChatShareMusicProvider());
        RongIM.registerMessageTemplate(new RCChatShareLiveProvider());

        RongExtensionManager.getInstance().registerExtensionModule(new SightExtensionModule());


        Conversation.ConversationType[] types = new Conversation.ConversationType[]{
                Conversation.ConversationType.PRIVATE,
                Conversation.ConversationType.GROUP,
        };
        RongIM.getInstance().setReadReceiptConversationTypeList(types);

        RongConfigCenter.conversationListConfig().setDataProcessor(new DataProcessor<Conversation>() {
            @Override
            public Conversation.ConversationType[] supportedTypes() {
                Conversation.ConversationType[] supportedTypes = {Conversation.ConversationType.PRIVATE,
                        Conversation.ConversationType.GROUP, Conversation.ConversationType.SYSTEM,
                        Conversation.ConversationType.APP_PUBLIC_SERVICE, Conversation.ConversationType.PUBLIC_SERVICE,
                };
                return supportedTypes;
            }

            @Override
            public List<Conversation> filtered(List<Conversation> data) {
                for (Conversation conversation : data) {
                    if (conversation.getConversationType() == Conversation.ConversationType.GROUP) {
                        //群聊排除课程和fans群之外的,比如网络教室
                        if (!ConversationFilterHelper.checkConversationEnable(conversation.getTargetId())) {
                            data.remove(conversation); //此处以过滤 "XXX" 这个群组会话为例。
                        }
                    }
                }
                return data;
            }

            @Override
            public boolean isGathered(Conversation.ConversationType type) {
                if (type.equals(Conversation.ConversationType.SYSTEM)) {
                    return true; //以配置系统会话聚合显示为例
                } else {
                    return false;
                }
            }
        });
        /*
         * 管理消息监听，由于同一时间只能有一个消息监听加入 融云 的消息监听，所以做一个消息管理来做消息路由
         */

        RongIM.addOnReceiveMessageListener(new RongIMClient.OnReceiveMessageWrapperListener() {
            @Override
            public boolean onReceived(Message message, int left, boolean b, boolean b1) {

                String targetId = message.getTargetId();
//                if (!ActivityManager.getInstance().isOpenActivity(LiveActivity.class) && !TextUtils.isEmpty(targetId) && (targetId.contains("S") || targetId.contains("DAYA") || targetId.contains("I"))) {
//                    //    清除视频课消息未读状态
//                    RongIM.getInstance().clearMessagesUnreadStatus(Conversation.ConversationType.GROUP, targetId, null);
//                }
                LogUtils.e(message.toString());
                boolean result = false;
                synchronized (imManager.listenerList) {
                    if (imManager.listenerList.size() > 0) {
                        for (RongIMClient.OnReceiveMessageListener listener : imManager.listenerList) {
                            result = listener.onReceived(message, left);
                            if (result) {
                                break;
                            }
                        }
                    }
                }
                return result;
            }
        });
    }


    /**
     * 设置用户信息
     *
     * @param userInfo
     */
    public void setCurrentUserInfo(UserInfo userInfo) {
        RongIM.getInstance().setCurrentUserInfo(userInfo);
    }

    /**
     * 登录 IM 服务器
     *
     * @param token
     */
    public void login(final String token, final ResultCallback<String> callBack) {
        RongIM.connect(token, new RongIMClient.ConnectCallback() {
            @Override
            public void onSuccess(String s) {
                if (null != callBack) {
                    callBack.onSuccess(s);
                }
            }

            @Override
            public void onError(RongIMClient.ConnectionErrorCode connectionErrorCode) {
                if (null != callBack) {
                    if (connectionErrorCode == RongIMClient.ConnectionErrorCode.RC_CONNECTION_EXIST) {
                        callBack.onSuccess(null);
                    } else {
                        callBack.onFail(ErrorCode.IM_ERROR.getCode(), null);
                    }

                }
            }

            @Override
            public void onDatabaseOpened(RongIMClient.DatabaseOpenStatus databaseOpenStatus) {

            }
        });
    }


    /**
     * 退出登录
     */
    public void logout() {
        RongIM.getInstance().logout();
    }


    /**
     * 加入消息监听
     *
     * @param listener
     */
    public void addMessageReceiveListener(RongIMClient.OnReceiveMessageListener listener) {
        synchronized (listenerList) {
            listenerList.add(listener);
        }
    }

    /**
     * 移除消息监听
     *
     * @param listener
     */
    public void removeMessageReceiveListener(RongIMClient.OnReceiveMessageListener listener) {
        synchronized (listenerList) {
            listenerList.remove(listener);
        }
    }

    /**
     * 设置未读消息数监听
     *
     * @param listener
     */
    public void addOnUnReadMessageListener(UnReadMessageManager.IUnReadMessageObserver listener) {
        RongIM.getInstance().addUnReadMessageCountChangedObserver(listener, Conversation.ConversationType.GROUP, Conversation.ConversationType.PRIVATE);
    }

    /**
     * 移除未读消息数监听
     *
     * @param listener
     */
    public void removeOnUnReadMessageListener(UnReadMessageManager.IUnReadMessageObserver listener) {
        RongIM.getInstance().removeUnReadMessageCountChangedObserver(listener);
    }

    /**
     * 将私聊消息存为房间消息
     *
     * @param message
     * @param roomId
     */
    public void savePrivateMessageToRoom(Message message, String roomId) {
        RongIM.getInstance().insertIncomingMessage(Conversation.ConversationType.GROUP, roomId, message.getSenderUserId(), message.getReceivedStatus(), message.getContent(), null);
    }

    /**
     * 将多用户角色改变消息拆分保存成单一角色改变
     */
    public void saveRoleChangedMessageToSingle(List<RoleChangedUser> roleChangedUserList, String optUserId, String roomId) {
        if (roleChangedUserList != null && roleChangedUserList.size() > 0) {
            for (RoleChangedUser user : roleChangedUserList) {
                RoleSingleChangedMessage roleSingleChangedMessage = new RoleSingleChangedMessage();
                roleSingleChangedMessage.setUser(user);
                roleSingleChangedMessage.setOpUserId(optUserId);
                Message.ReceivedStatus receivedStatus = new Message.ReceivedStatus(0);
                RongIM.getInstance().insertIncomingMessage(Conversation.ConversationType.GROUP, roomId, optUserId, receivedStatus, roleSingleChangedMessage, null);
            }
        }
    }

    /**
     * 群发消息
     *
     * @param targetId
     * @param conversationType
     * @param message
     * @return
     */
    public void sendToAll(String targetId, Conversation.ConversationType conversationType, String message) {

        TextMessage textMessage = TextMessage.obtain(BaseApplication.context.getString(R.string.profile_group_notice_prefix) + message);
        MentionedInfo mentionedInfo = new MentionedInfo(MentionedInfo.MentionedType.ALL, null, null);
        textMessage.setMentionedInfo(mentionedInfo);

        RongIM.getInstance().sendMessage(Message.obtain(targetId, conversationType, textMessage), null, null, new IRongCallback.ISendMessageCallback() {
            @Override
            public void onAttached(Message message) {

            }

            @Override
            public void onSuccess(Message message) {

            }

            @Override
            public void onError(Message message, RongIMClient.ErrorCode errorCode) {
            }
        });
    }

}
