package com.rv.im;

import android.app.Service;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Binder;
import android.os.IBinder;
import android.text.TextUtils;
import android.util.Log;

import com.google.gson.Gson;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.lzy.okgo.utils.HttpUtils;
import com.ruiwenliu.wrapper.MessageEventRemoteLogin;
import com.rv.component.utils.AppCookie;
import com.rv.component.utils.CacheEnum;
import com.rv.component.utils.RvCache;
import com.rv.im.bean.LastChatHistoryListBean;
import com.rv.im.broadcast.MessageReceiver;
import com.rv.im.db.table.ChatMessage;
import com.rv.im.enums.CallTypeEnum;
import com.rv.im.listener.AbstractMsgListener;
import com.rv.im.log.LogUtil;
import com.rv.im.util.NetworkUtil;
import com.rv.im.xmpp.ListenerManager;
import com.rv.im.xmpp.NotifyConnectionListener;
import com.rv.im.xmpp.ReceiptManager;
import com.rv.im.xmpp.XChatManager;
import com.rv.im.xmpp.XmppConnectionManager;
import com.rv.im.xmpp.listener.AuthStateListener;
import com.rv.im.xmpp.listener.ChatMessageListener;
import com.yuyife.okgo.OkGoUtil;

import org.greenrobot.eventbus.EventBus;
import org.jivesoftware.smack.XMPPConnection;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;


public class ImService extends Service {

    private static final String TAG = ImService.class.getSimpleName();
    private static final Intent SERVICE_INTENT = new Intent();
    private XmppConnectionManager mConnectionManager;// 唯一
    private boolean isInit = true;
    private String mLoginUserId;
    private String mLoginPassword;
    private String mLoginNickName;

    private XChatManager mXChatManager;// 唯一
    private ReceiptManager mReceiptManager;// 唯一

    public String getUserId() {
        return mLoginUserId;
    }

    public static Intent getIntent() {
        return SERVICE_INTENT;
    }

    private MessageReceiver receiver = new MessageReceiver(new AbstractMsgListener() {
        @Override
        public void send(String toUserId, String message) {
            ChatMessage chatMessage = ChatMessage.json2Message(message);
            sendChatMessage(toUserId, chatMessage);
        }
    });

    private NotifyConnectionListener mNotifyConnectionListener = new NotifyConnectionListener() {
        @Override
        public void notifyConnecting() {
            LogUtil.e(TAG, "xmpp:notifyConnecting");
            ListenerManager.getInstance().notifyAuthStateChange(AuthStateListener.AUTH_STATE_ING);
        }

        @Override
        public void notifyConnected(XMPPConnection arg0) {
            LogUtil.e(TAG, "xmpp:notifyConnected");
            ListenerManager.getInstance().notifyAuthStateChange(AuthStateListener.AUTH_STATE_ING);
        }

        @Override
        public void notifyAuthenticated(XMPPConnection arg0) {
            LogUtil.e(TAG, "xmpp:notifyAuthenticated");
            onAuthenticated();
            ListenerManager.getInstance().notifyAuthStateChange(AuthStateListener.AUTH_STATE_SUCCESS);// 通知登陆成功
            getChatHistory();
        }

        @Override
        public void notifyConnectionClosedOnError(Exception e) {
            AppCookie.save(AppCookie.OFFLINE_TIME + mLoginUserId, System.currentTimeMillis());
            ListenerManager.getInstance().notifyAuthStateChange(AuthStateListener.AUTH_STATE_NOT);
            release();
            LogUtil.e(TAG, "xmpp:notifyConnectionClosedOnError");
            Log.e(TAG, "连接异常==" + e.getMessage());
            if (e.getMessage().contains("conflict")) {
                Log.e(TAG, "连接异常==被挤下线了");
                EventBus.getDefault().post(new MessageEventRemoteLogin());
            } else {
                init();
            }
        }

        @Override
        public void notifyConnectionClosed() {
            LogUtil.e(TAG, "xmpp:notifyConnectionClosed");
            AppCookie.save(AppCookie.OFFLINE_TIME + mLoginUserId, System.currentTimeMillis());
            release();
            ListenerManager.getInstance().notifyAuthStateChange(AuthStateListener.AUTH_STATE_NOT);
        }
    };

    private ImServiceBinder mBinder = new ImServiceBinder();

    @Override
    public IBinder onBind(Intent intent) {
        LogUtil.d(TAG, "ImService onBind");
        return mBinder;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        registerReceiver();

        mLoginUserId = ImSetting.getUserId();
        mLoginPassword = ImSetting.getUserPassword();
        mLoginNickName = ImSetting.getUserName();
        init();
    }

    private void init() {
        if (mConnectionManager == null) {
            initConnection();
        }
        Log.e("zq", "isInit==true,直接登录");
        login(mLoginUserId, mLoginPassword);
        return;
    }

    private void onAuthenticated() {
        if (!isAuthenticated()) {
            return;
        }

        /* 消息回执管理 */
        if (mReceiptManager == null && mConnectionManager != null) {
            mReceiptManager = new ReceiptManager(this, mConnectionManager.getConnection());
        } else {
            mReceiptManager.reset();
        }

        // 初始化消息处理
        if (mXChatManager == null && mConnectionManager != null) {
            mXChatManager = new XChatManager(this, mConnectionManager.getConnection());
        } else {
            mXChatManager.reset();
        }

        /*  获取离线消息 */
        mConnectionManager.sendOnLineMessage();
    }

    public boolean isAuthenticated() {
        if (mConnectionManager != null && mConnectionManager.isAuthenticated()) {
            return true;
        }
        return false;
    }

    public void initConnection() {
        mConnectionManager = new XmppConnectionManager(this, mNotifyConnectionListener);
    }

    public void login(String userId, String password) {
        if (!TextUtils.isEmpty(userId) && !TextUtils.isEmpty(password) && mConnectionManager != null) {
            mConnectionManager.login(userId, password);
        }
    }

    public void getChatHistory() {
        Map<String, String> params = new HashMap();
        params.put("access_token", ImSetting.getImToken());
        params.put("receiver", mLoginUserId);

        long syncTimeLen = AppCookie.getLongValue(AppCookie.OFFLINE_TIME + mLoginUserId, 0l);
        params.put("startTime", String.valueOf(syncTimeLen));
        params.put("endTime", String.valueOf(System.currentTimeMillis()));
        params.put("pageSize", String.valueOf(100));// 尽量传一个大的值 一次性拉下来
        AppConfig appConfig = (AppConfig) RvCache.getInstance().get(CacheEnum.IM_CONFIG);
        OkGoUtil.getMap(appConfig.GET_CHAT_MSG, params, new StringCallback() {
            @Override
            public void onSuccess(Response<String> response) {
                if (response == null) return;
                int code = response.code();
                String body = response.body();
                if (code == 200 && !TextUtils.isEmpty(body)) {
                    Log.e("im_onSuccess", body);
//                    LastChatHistoryListBean bean = new Gson().fromJson(body, LastChatHistoryListBean.class);
//                    if (bean != null && bean.getResultCode() == 1) {
//                        if (bean.getCurrentTime() != 0l) {
//                            AppCookie.save(AppCookie.OFFLINE_TIME + mLoginUserId, bean.getCurrentTime());
//                        }
//                        List<LastChatHistoryListBean.ChatHistoryItem> historyItems = bean.getData();
//                        if (historyItems != null && historyItems.size() > 0) {
//                            for (LastChatHistoryListBean.ChatHistoryItem item : historyItems) {
//                                ListenerManager.getInstance().notifyNewMesssage(ChatMessage.historyToChatMessage(item));
//                            }
//                        }
//                    }
                }
            }
        });
    }


//    // 发送上线、检测消息
//    public void sendOnLineMessage() {
//        ChatMessage chatMessage = new ChatMessage();
//        chatMessage.setMessageType(XmppMessage.TYPE_SEND_ONLINE_STATUS);
//
//        chatMessage.setFromUserId(mLoginUserId);
//        chatMessage.setFromUserName(mLoginNickName);
//        chatMessage.setToUserId(mLoginUserId);
//        chatMessage.setContent("1");// 0 离线 1 在线
//
//        chatMessage.setPacketId(UUID.randomUUID().toString().replaceAll("-", ""));
//        sendChatMessage(mLoginUserId, chatMessage);
//    }


    /********
     * 发送忙线消息
     * @param messageType
     * @param toUserId
     */
    public void sendBusyMessage(int messageType, String toUserId) {

        ChatMessage chatMessage = new ChatMessage();
        chatMessage.setMessageType(messageType);
        chatMessage.setCallType(CallTypeEnum.CALL_BUSY);
        chatMessage.setFromUserId(mLoginUserId);
        chatMessage.setFromUserName(mLoginNickName);
        chatMessage.setToUserId(toUserId);
        chatMessage.setContent("对方忙线");
        chatMessage.setTimeSend(System.currentTimeMillis());
        chatMessage.setPackId(UUID.randomUUID().toString().replaceAll("-", ""));
        sendChatMessage(toUserId, chatMessage);
    }


    public class ImServiceBinder extends Binder {
        public ImService getService() {
            return ImService.this;
        }
    }

    /******
     * 注册接受消息的广播
     */
    private void registerReceiver() {
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(Constants.ACTIONS.ACTION_SEND_RECEIVER);
        registerReceiver(receiver, intentFilter);
    }

    private void release() {
        if (mConnectionManager != null) {
            mConnectionManager.release();
            mConnectionManager = null;
        }

        mReceiptManager = null;
        mXChatManager = null;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        release();

        if (receiver != null) {
            unregisterReceiver(receiver);
            receiver = null;
        }
    }

    /**
     * 发送聊天消息
     */
    public void sendChatMessage(String toUserId, ChatMessage chatMessage) {
        if (mXChatManager == null) {
            LogUtil.e(TAG, "mXChatManager==null");
        }

        if (mReceiptManager == null) {
            LogUtil.e(TAG, "mReceiptManager==null");
        }

        if (!isAuthenticated()) {
            Log.e(TAG, "isAuthenticated==false");
            ListenerManager.getInstance().notifyMessageSendStateChange(chatMessage.getPackId(), ChatMessageListener.MESSAGE_SEND_FAILED);
            return;
        }

        if (mXChatManager == null || mReceiptManager == null
                || (!isAuthenticated() && !NetworkUtil.isNetworkAvailable(getApplicationContext()))) {
            ListenerManager.getInstance().notifyMessageSendStateChange(chatMessage.getPackId(), ChatMessageListener.MESSAGE_SEND_FAILED);
        } else {
            /**
             * 先添加一个等待接收回执的消息
             * 然后再发送这条消息
             */
            mReceiptManager.addWillSendMessage(toUserId, chatMessage, ReceiptManager.SendType.NORMAL, chatMessage.getContent());
            mXChatManager.sendMessage(toUserId, chatMessage);
        }
    }
}
