package com.yidianling.im.helper;


import com.netease.nimlib.sdk.NIMClient;
import com.netease.nimlib.sdk.NIMSDK;
import com.netease.nimlib.sdk.RequestCallbackWrapper;
import com.netease.nimlib.sdk.msg.MsgService;
import com.netease.nimlib.sdk.msg.constant.NotificationType;
import com.netease.nimlib.sdk.msg.constant.SessionTypeEnum;
import com.netease.nimlib.sdk.msg.model.RecentContact;
import com.netease.nimlib.sdk.team.model.MemberChangeAttachment;
import com.yidianling.common.tools.LogUtil;
import com.yidianling.im.event.UpdateTabUnreadNumEvent;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import de.greenrobot.event.EventBus;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;

/**
 * 接收到消息后的更新机制
 * Created by zqk on 2017/11/08;
 */
public class MsgReceiveHelper {

    private static Map<String, Integer> unreadNumMap = new HashMap<>();


    public static void updateNum(String accId, int unreadUnm) {
        unreadNumMap.put(accId, unreadUnm);
    }

    public static int getUnNum(String accId) {
        if (unreadNumMap.get(accId) != null) {
            return unreadNumMap.get(accId);
        } else {
            return 0;
        }
    }

    /**
     * 获取所有未读数
     * @return
     */
    public static int getAllUnNum() {

        Object[] list = unreadNumMap.values().toArray();

        int sum = 0;
        for (int i=0;i<list.length;i++) {
            try {
                sum += Integer.parseInt(list[i].toString());
            }catch (Exception e) {
                sum += 0;
            }
        }

        return sum;
    }

    public static void onMessageReceived() {

        reQueryUnreadNum();
    }

    public static void reQueryUnreadNum() {
        NIMClient.getService(MsgService.class).queryRecentContacts()
                .setCallback(new RequestCallbackWrapper<List<RecentContact>>() {
                    @Override
                    public void onResult(int code, List<RecentContact> recentList, Throwable e) {
                        // recentList参数即为最近联系人列表（最近会话列表）
                        if (recentList != null && recentList.size() != 0) {
                            for (RecentContact r : recentList) {
                                if (r.getSessionType() == SessionTypeEnum.Team && r.getAttachment() instanceof MemberChangeAttachment) {
                                    if (((MemberChangeAttachment) r.getAttachment()).getType() == NotificationType.KickMember) {
                                        //如果是群聊，且有被踢的消息，删除该群聊
                                        NIMClient.getService(MsgService.class).deleteRecentContact(r);
                                        continue;
                                    }
                                }
                                LogUtil.d(MsgReceiveHelper.class.getSimpleName(), "account:" + r.getContactId() + "--" + "num:" + r.getUnreadCount());
                                MsgReceiveHelper.updateNum(r.getContactId(), r.getUnreadCount());
                            }
                        }
                        Observable.timer(500, TimeUnit.MILLISECONDS)
                                .observeOn(AndroidSchedulers.mainThread())
                                .subscribe(aLong -> {
                                    EventBus.getDefault().post(new UpdateTabUnreadNumEvent());
                                });
                    }
                });
    }

    public interface MessageRefreshCallback {
        void onSuccess();
    }

    //更新未读数量及最近联系人列表
    public static void reQueryUnreadNumber(MessageRefreshCallback callback) {
        try {
            NIMClient.getService(MsgService.class).queryRecentContacts()
                    .setCallback(new RequestCallbackWrapper<List<RecentContact>>() {
                        @Override
                        public void onResult(int code, List<RecentContact> recentList, Throwable e) {
                            // recentList参数即为最近联系人列表（最近会话列表）
                            if (recentList != null && recentList.size() != 0) {
                                for (RecentContact r : recentList) {
                                    if (r.getSessionType() == SessionTypeEnum.Team && r.getAttachment() instanceof MemberChangeAttachment) {
                                        if (((MemberChangeAttachment) r.getAttachment()).getType() == NotificationType.KickMember) {
                                            //如果是群聊，且有被踢的消息，删除该群聊
                                            NIMClient.getService(MsgService.class).deleteRecentContact(r);
                                            continue;
                                        }
                                    }
                                    MsgReceiveHelper.updateNum(r.getContactId(), r.getUnreadCount());
                                }
                            }
                            if (callback != null) {
                                callback.onSuccess();
                            }
                        }
                    });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void markAllRead() {
        NIMSDK.getMsgService().clearAllUnreadCount();
        NIMClient.getService(MsgService.class).queryRecentContacts()
                .setCallback(new RequestCallbackWrapper<List<RecentContact>>() {
                    @Override
                    public void onResult(int code, List<RecentContact> recentList, Throwable e) {
                        // recentList参数即为最近联系人列表（最近会话列表）
                        if (recentList != null && recentList.size() != 0) {
                            for (RecentContact r : recentList) {
                                MsgReceiveHelper.updateNum(r.getContactId(), 0);
                            }
                        }
                    }
                });
        Observable.timer(1500, TimeUnit.MILLISECONDS)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(aLong -> EventBus.getDefault().post(new UpdateTabUnreadNumEvent()));
    }

    public static void markTeamChatRead(String contactId) {
        NIMClient.getService(MsgService.class).clearUnreadCount(contactId, SessionTypeEnum.Team);
        MsgReceiveHelper.updateNum(contactId, 0);
        //跟新首页底部未读消息树
        EventBus.getDefault().post(new UpdateTabUnreadNumEvent());
    }


    public static boolean isHasUnread = false;

}
