package com.yunbao.im.utils;

import android.text.TextUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.tencent.imsdk.TIMCallBack;
import com.tencent.imsdk.TIMConnListener;
import com.tencent.imsdk.TIMConversation;
import com.tencent.imsdk.TIMConversationType;
import com.tencent.imsdk.TIMCustomElem;
import com.tencent.imsdk.TIMElem;
import com.tencent.imsdk.TIMElemType;
import com.tencent.imsdk.TIMGroupManager;
import com.tencent.imsdk.TIMGroupSystemElem;
import com.tencent.imsdk.TIMLogLevel;
import com.tencent.imsdk.TIMManager;
import com.tencent.imsdk.TIMMessage;
import com.tencent.imsdk.TIMMessageListener;
import com.tencent.imsdk.TIMSdkConfig;
import com.tencent.imsdk.TIMUserConfig;
import com.tencent.imsdk.TIMUserStatusListener;
import com.tencent.imsdk.TIMValueCallBack;
import com.tencent.imsdk.session.SessionWrapper;
import com.yunbao.common.CommonAppConfig;
import com.yunbao.common.CommonAppContext;
import com.yunbao.common.bean.ChatReceiveGiftBean;
import com.yunbao.common.bean.ConfigBean;
import com.yunbao.common.utils.L;
import com.yunbao.common.utils.RouteUtil;
import com.yunbao.common.utils.SpUtil;
import com.yunbao.common.utils.ToastUtil;
import com.yunbao.common.utils.WordUtil;
import com.yunbao.im.R;
import com.yunbao.im.bean.ImMessageBean;
import com.yunbao.im.http.ImHttpUtil;
import com.yunbao.im.interfaces.ImClient;

import org.greenrobot.eventbus.EventBus;

import java.util.List;

// +———————————————————————————————————
// | Created by Yunbao
// +———————————————————————————————————
// | Copyright (c) 2013~2022 http://www.yunbaokj.com All rights reserved.
// +———————————————————————————————————
// | Author: https://gitee.com/yunbaokeji
// +———————————————————————————————————
// | Date: 2022-03-22
// +———————————————————————————————————
public class TxImMessageUtil implements ImClient, TIMMessageListener {

    private static final String TAG = "腾讯IM";
    private TIMValueCallBack<TIMMessage> mSendCustomCallback;
    private String mGroupId;
    private boolean mLoginIM;//IM是否登录了



    /**
     * 根据IM消息 获取App用户的uid
     */
    private String getAppUid(TIMMessage msg) {
        if (msg == null) {
            return "";
        }
        String peer = msg.getConversation().getPeer();
        if (TextUtils.isEmpty(peer)) {
            return "";
        }
        return peer;
    }

    //初始化IM
    @Override
    public void init() {
        final TIMManager timManager = TIMManager.getInstance();
        if (timManager.isInited()) {
            return;
        }
        mLoginIM = false;
        //判断是否是在主线程 初始化 SDK 基本配置
        if (SessionWrapper.isMainProcess(CommonAppContext.sInstance)) {
            TIMSdkConfig config = new TIMSdkConfig(CommonAppConfig.TX_IM_APP_Id)
                    .enableLogPrint(false)
                    .setLogLevel(TIMLogLevel.OFF);

            timManager.init(CommonAppContext.sInstance, config);
        }

        //基本用户配置
        TIMUserConfig userConfig = new TIMUserConfig();
        //设置用户状态变更事件监听器
        userConfig.setUserStatusListener(new TIMUserStatusListener() {
            @Override
            public void onForceOffline() {
                L.e(TAG, "被其他终端顶掉了---->");
                RouteUtil.forwardLoginInvalid(WordUtil.getString(R.string.login_status_Invalid));
            }

            @Override
            public void onUserSigExpired() {
                L.e(TAG, "用户签名过期了，需要重新登录---->");
            }
        });
        //设置连接状态事件监听器
        userConfig.setConnectionListener(new TIMConnListener() {
            @Override
            public void onConnected() {
                L.e(TAG, "连接成功---->");
            }

            @Override
            public void onDisconnected(int code, String desc) {
                L.e(TAG, "连接断开---->");
            }

            @Override
            public void onWifiNeedAuth(String name) {
                L.e(TAG, "onWifiNeedAuth");
            }
        });
        timManager.setUserConfig(userConfig);
        timManager.addMessageListener(TxImMessageUtil.this);
    }

    //登录IM
    @Override
    public void loginImClient() {
        if (mLoginIM) {
            ImHttpUtil.setOnlineStatus(3);
            return;
        }
        String uid = CommonAppConfig.getInstance().getUid();
        if (TextUtils.isEmpty(uid) || "-1".equals(uid)) {
            return;
        }
        String sign = SpUtil.getInstance().getStringValue(SpUtil.TX_IM_USER_SIGN);
        if (TextUtils.isEmpty(sign)) {
//            ToastUtil.show("腾讯IM登录失败！ 签名错误！");
            return;
        }
        TIMManager.getInstance().login(uid, sign, new TIMCallBack() {
            @Override
            public void onError(int code, String desc) {
                L.e(TAG, "登录失败 : " + code + " errmsg: " + desc);
                mLoginIM = false;
                ToastUtil.show("IM 登录失败：" + code + " errmsg: " + desc);
            }

            @Override
            public void onSuccess() {
                L.e(TAG, "登录成功！！");
                mLoginIM = true;
                ImHttpUtil.setOnlineStatus(3);
//                refreshAllUnReadMsgCount();
                ConfigBean configBean = CommonAppConfig.getInstance().getConfig();
                if (configBean != null) {
                    String groupId = configBean.getTxImGroupId();
                    L.e(TAG, "群组ID------> " + groupId);
                    if (!TextUtils.isEmpty(groupId)) {
                        mGroupId = groupId;
                        TIMGroupManager.getInstance().applyJoinGroup(groupId, "login", new TIMCallBack() {
                            @java.lang.Override
                            public void onError(int code, String desc) {
                                L.e(TAG, "加入群组失败 : " + code + " errmsg: " + desc);
                            }

                            @java.lang.Override
                            public void onSuccess() {
                                L.e(TAG, "加入群组成功！！");
                            }
                        });
                    }
                }
            }
        });
    }


    //退出登录IM
    @Override
    public void logoutImClient() {
        TIMManager timManager = TIMManager.getInstance();
        timManager.logout(null);
        mLoginIM = false;
        L.e(TAG, "退出登录--->");
    }

    /**
     * 设置消息监听器，收到新消息时，通过此监听器回调
     *
     * @param list
     * @return
     */
    @Override
    public boolean onNewMessages(List<TIMMessage> list) {
        if (list == null || list.size() == 0) {
            return true;
        }
        for (TIMMessage msg : list) {
            onReceiveMessage(msg);
        }
        return true; //返回true将终止回调链，不再调用下一个新消息监听器
    }


    //接收消息
    private void onReceiveMessage(TIMMessage msg) {
        if (msg == null) {
            return;
        }
        if (msg.timestamp() < CommonAppConfig.getInstance().getLaunchTime()) {
            return;
        }
        //先判断是不是大群消息
        if ("@TIM#SYSTEM".equals(msg.getSender())) {
            if (msg.getElementCount() > 0) {
                TIMElem elem0 = msg.getElement(0);
                if (elem0 instanceof TIMGroupSystemElem) {
                    TIMGroupSystemElem systemElem = (TIMGroupSystemElem) elem0;
                    if (systemElem.getGroupId().equals(mGroupId)) {
                        String data = new String(systemElem.getUserData());
                        L.e(TAG, "大群消息--------> " + data);
                        try {
                            ChatLiveImUtil.onNewMessage(JSON.parseObject(data), null);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        return;
                    }
                }
            }
        }
        String uid = getAppUid(msg);
        if (TextUtils.isEmpty(uid)) {
            return;
        }
        String customMsgData = getCustomMsgData(msg);
        if (!TextUtils.isEmpty(customMsgData)) {
            L.e(TAG, "自定义消息---> " + customMsgData);
            try {
                JSONObject obj = JSON.parseObject(customMsgData);
                if (obj != null) {
                    String method = obj.getString(ChatLiveImUtil.METHOD);
                    if (ChatLiveImUtil.IM_GIFT.equals(method)) {//这是礼物消息
                        L.e(TAG, "收到礼物消息--->");
                        ImMessageBean bean = new ImMessageBean(uid, msg, ImMessageBean.TYPE_GIFT, msg.isSelf());
                        bean.setGiftBean(obj.toJavaObject(ChatReceiveGiftBean.class));
                        EventBus.getDefault().post(bean);
                    } else if (ChatLiveImUtil.IM_CHAT_CALL.equals(method)) {
                        ChatLiveImUtil.onNewMessage(obj, uid);
                    } else if (ChatLiveImUtil.IM_CHAT_HANDLE.equals(method)) {
                        ChatLiveImUtil.onNewMessage(obj, uid);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 获取自定义消息里面的数据，如果不是自定义消息，返回null
     */
    private String getCustomMsgData(TIMMessage msg) {
        if (msg == null || msg.getElementCount() <= 0) {
            return null;
        }
        TIMElem elem0 = msg.getElement(0);
        if (elem0.getType() != TIMElemType.Custom) {
            return null;
        }
        TIMCustomElem elem = (TIMCustomElem) elem0;
        return new String(elem.getData());
    }


    /**
     * 发送自定义消息
     *
     * @param toUid
     * @param data  要发送的数据
     */
    @Override
    public void sendCustomMessage(String toUid, String data, final boolean save) {
        if (!mLoginIM) {
            ToastUtil.show("IM未登录");
            return;
        }
        final TIMMessage customMsg = new TIMMessage();
        TIMCustomElem elem = new TIMCustomElem();
        elem.setData(data.getBytes());
        if (customMsg.addElement(elem) != 0) {
            return;
        }
        TIMConversation conversation = TIMManager.getInstance().getConversation(TIMConversationType.C2C, toUid);
        if (conversation != null) {
            if (mSendCustomCallback == null) {
                mSendCustomCallback = new TIMValueCallBack<TIMMessage>() {//发送消息回调
                    @Override
                    public void onError(int code, String desc) {//发送消息失败
                        L.e(TAG, "发送自定义消息失败---> code: " + code + " errmsg: " + desc);

                    }

                    @Override
                    public void onSuccess(TIMMessage msg) {//发送消息成功
                        L.e(TAG, "发送自定义消息成功！！");
                    }
                };
            }
            conversation.sendMessage(customMsg, mSendCustomCallback);
        }
    }




}
