package com.efounder.chat.manager;

import android.app.Activity;
import android.content.Context;
import androidx.annotation.Nullable;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;

import com.efounder.chat.adapter.ChatVoicePlayClickListener;
import com.efounder.chat.db.WeChatDBManager;
import com.efounder.chat.fragment.ChatListSwipeMenuFragment;
import com.efounder.chat.http.GetHttpUtil;
import com.efounder.chat.http.OKHttpUtils;
import com.efounder.chat.http.RequestHttpDataUtil;
import com.efounder.chat.item.VideoMessageItem;
import com.efounder.chat.item.manager.JFMessageItemManager;
import com.efounder.chat.model.ChatListItem;
import com.efounder.chat.model.Group;
import com.efounder.chat.model.MessageEvent;
import com.efounder.chat.service.SystemInfoService;
import com.efounder.chat.struct.StructFactory;
import com.efounder.chat.utils.ChatMessageMenuDialogUtil;
import com.efounder.constant.EnvironmentVariable;
import com.efounder.frame.utils.Constants;
import com.efounder.http.EFHttpRequest;
import com.efounder.message.manager.JFMessageHandler;
import com.efounder.message.manager.JFMessageManager;
import com.efounder.message.struct.IMStruct002;
import com.efounder.mobilecomps.contacts.User;

import org.greenrobot.eventbus.EventBus;

import java.util.List;

/**
 * Created by XinQing on 2016/12/22.
 */

public class ChatListManager {

    /**
     * 清除聊天角标
     *
     * @param id
     * @param chatType
     */
    public void clearunReadCount(int id, byte chatType) {
        //清除当前聊天的角标
        ChatListItem chatListItem = WeChatDBManager.getInstance().getChatListItem(id, chatType);
        JFMessageManager.getInstance().unreadZero(id, chatType);
        if (chatListItem != null) {
            chatListItem.setBadgernum(-1);
            //处理ChatListSwipeMenuFragment被销毁的情况
            dealOtherStatus(chatListItem);

            EventBus.getDefault().post(new MessageEvent(chatListItem, MessageEvent.UPDATE));
        }
    }

    //处理ChatListSwipeMenuFragment被销毁的情况,计算角标，更新界面
    private void dealOtherStatus(ChatListItem chatListItem) {
        if (!ChatListSwipeMenuFragment.ISALIVE) {
            int countNum = 0;
            for (ChatListItem item : SystemInfoService.CHATITEMLIST) {
                //遍历设置当前聊天的人角标为0
                if (item.getUserId() == chatListItem.getUserId() && item.getChatType() == chatListItem.getChatType()) {
                    item.setBadgernum(-1);
                }
            }

        }
    }


    /**
     * 清除聊天角标
     * publicchatfragment调用 与上面一样
     *
     * @param id
     * @deprecated
     */
    public void clearunReadCount(int id) {
        //清除当前聊天的角标
        ChatListItem chatListItem = WeChatDBManager.getInstance().getChatListItem(id, 0);
        JFMessageManager.getInstance().unreadZero(id, (byte) 0);

        if (chatListItem != null) {
            chatListItem.setBadgernum(-1);
            WeChatDBManager.getInstance().insertOrUpdateChatList(chatListItem);
            EventBus.getDefault().post(new MessageEvent(chatListItem, MessageEvent.UPDATE));
        }

    }

    public void release(Object activityInstance) {
        activityInstance = null;
        OKHttpUtils.callBack = null;
        GetHttpUtil.release();
        //必须回收，血的教训啊
        JFMessageItemManager.release();
        //JFMessageQQStyleItemManager.release();
        ChatVoicePlayClickListener.currentMsgId = null;
        //设置当前聊天的人id为 空，表示没有与任何人聊天
        EnvironmentVariable.setProperty("currentChatUserId", "-1");
        ChatVoiceRecordAnimManager.releaseRes();
        VideoMessageItem.BitmapPool.release();
        //回收语音播放
        if (ChatVoicePlayClickListener.currentPlayListener != null && ChatVoicePlayClickListener.isPlaying) {
            ChatVoicePlayClickListener.currentPlayListener.stopPlayVoice();
        }

        ChatVoicePlayClickListener.currentPlayListener = null;
        ChatMessageMenuDialogUtil.release();
        EFHttpRequest.cancelRequest(RequestHttpDataUtil.TAG);
    }

    public List<IMStruct002> getHistoryMessage(byte chatType, User user, JFMessageManager messageManager, Group group, String msgID, int msgNum, @Nullable JFMessageHandler
            handler) {
        List<IMStruct002> historyImStruct002s = null;
        switch (chatType) {
            case StructFactory.TO_USER_TYPE_PERSONAL:
            case StructFactory.TO_USER_TYPE_OFFICIAL_ACCOUNT:
                int fromUserId = Integer.parseInt(EnvironmentVariable
                        .getProperty(Constants.CHAT_USER_ID));
                int toUserId = user.getId();
                historyImStruct002s = messageManager.getPersonalHistoryMessage(
                        fromUserId, toUserId, msgID, msgNum, handler);

                break;
            case StructFactory.TO_USER_TYPE_GROUP:
                int groupToUserId = group.getGroupId();
                historyImStruct002s = messageManager.getGroupHistoryMessage(
                        groupToUserId, msgID, msgNum, handler);

                break;
        }
        return historyImStruct002s;
    }


    /**
     * 隐藏软键盘
     */
    public void hideKeyboard(Activity context) {
        if (context.getWindow().getAttributes().softInputMode != WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN) {
            if (context.getCurrentFocus() != null) {
                InputMethodManager manager = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
                manager.hideSoftInputFromWindow(context.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
            }
        }
    }


    /**
     * Fixme 加载历史消息的时候，判断处理消息是否是以查看，如果不是，给服务器发送以查看的回执
     *
     * @param messageList         消息记录
     * @param historyImStruct002s
     */
    public void solveUnRead(List<IMStruct002> messageList, List<IMStruct002> historyImStruct002s) {
        if (messageList == null || historyImStruct002s == null) return;
        for (int i = 0; i < historyImStruct002s.size() - 1; i++) {
            if (historyImStruct002s.get(i).getFromUserId() != Integer.valueOf(EnvironmentVariable.getProperty(Constants.CHAT_USER_ID))
                    && historyImStruct002s.get(i).getState() != IMStruct002.MESSAGE_STATE_READ
                    && historyImStruct002s.get(i).getToUserType() != StructFactory.TO_USER_TYPE_GROUP
                    && messageList.get(i).getReadState() != IMStruct002.MESSAGE_STATE_READ
                    ) {
                JFMessageManager.getInstance().sendReadMessage(historyImStruct002s.get(i));
            } else {
                if (historyImStruct002s.get(i).getToUserType() == StructFactory.TO_USER_TYPE_GROUP) {
                    JFMessageManager.getInstance().markedAsRead(historyImStruct002s.get(i));
                }
            }

        }
    }

    public void release() {

    }


}
