package com.bokecc.livemodule.live.chat;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.Configuration;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AlphaAnimation;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bokecc.dwlivedemo.R;
import com.bokecc.livemodule.live.DWLiveChatListener;
import com.bokecc.livemodule.live.DWLiveCoreHandler;
import com.bokecc.livemodule.live.UserListener;
import com.bokecc.livemodule.live.chat.adapter.EmojiAdapter;
import com.bokecc.livemodule.live.chat.adapter.VerticalLivePublicChatAdapter;
import com.bokecc.livemodule.live.chat.barrage.BarrageLayout;
import com.bokecc.livemodule.live.chat.module.ChatEntity;
import com.bokecc.livemodule.live.chat.util.EmojiUtil;
import com.bokecc.livemodule.live.chat.window.BanChatPopup;
import com.bokecc.livemodule.utils.ChatImageUtils;
import com.bokecc.livemodule.view.BaseRelativeLayout;
import com.bokecc.livemodule.view.CustomToast;
import com.bokecc.livemodule.view.VerticalAutoScrollView;
import com.bokecc.sdk.mobile.live.DWLive;
import com.bokecc.sdk.mobile.live.common.network.model.CCChatTopBean;
import com.bokecc.sdk.mobile.live.pojo.BanChatBroadcast;
import com.bokecc.sdk.mobile.live.pojo.BroadCastMsg;
import com.bokecc.sdk.mobile.live.pojo.ChatMessage;
import com.bokecc.sdk.mobile.live.pojo.UserRedminAction;
import com.bokecc.sdk.mobile.live.pojo.Viewer;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;

/**
 * 直播间聊天展示控件（公共聊天）
 */
public class VerticalLiveChatComponent extends BaseRelativeLayout implements DWLiveChatListener, KeyboardHeightObserver, UserListener {

    private final static String TAG = "LiveChatComponent";

    private RecyclerView mChatList;
    private LinearLayout mChatLayout;
    private EditText mInput;
    private ImageView mEmoji;
    private EmojiLayout emojiLayout;

    // 软键盘是否显示
    private boolean isSoftInput = false;
    // emoji是否需要显示
    private boolean isEmojiShow = false;
    // 聊天是否显示
    private boolean isChat = false;

    // 公共聊天适配器
    private VerticalLivePublicChatAdapter mChatAdapter;

    // 软键盘监听
    private InputMethodManager mImm;

    // 定义当前支持的最大的可输入的文字数量
    private short maxInput = 300;

    private OnChatComponentClickListener mChatComponentClickListener;
    //软键盘的高度
    private int softKeyHeight;
    private boolean showEmojiAction = false;
    private BanChatPopup banChatPopup;
    private VerticalAutoScrollView autoScrollView;
    private ImageView buttonShop;
    private FrameLayout frameChatRoot;
    private ImageView buttonMore;
    private Button mChatSend;
    private RelativeLayout rlVerticalChatInputCon;
    private ChatTopLayout chatTopLayoutVertical;

    private boolean canShowTips = false;

    //聊天置顶数组
    private ArrayList<CCChatTopBean> chatTopBeanArrayList = new ArrayList<>();
    private RelativeLayout rlVerticalChatNewMsgTips;

    public void setOnChatComponentClickListener(OnChatComponentClickListener listener) {
        mChatComponentClickListener = listener;
    }


    public VerticalLiveChatComponent(Context context) {
        super(context);
        initChat();
    }

    public VerticalLiveChatComponent(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        initChat();
    }

    public void initViews() {
        LayoutInflater.from(mContext).inflate(R.layout.vertical_live_portrait_chat_layout, this, true);
        mChatList = findViewById(R.id.chat_container);
        mChatLayout = findViewById(R.id.id_push_chat_layout);
        frameChatRoot = findViewById(R.id.frame_chat_root);
        mInput = findViewById(R.id.id_push_chat_input);
        mEmoji = findViewById(R.id.id_push_chat_emoji);
        emojiLayout = findViewById(R.id.id_emoji_layout);
        mChatSend = findViewById(R.id.id_push_chat_send);
        rlVerticalChatInputCon = findViewById(R.id.rl_vertical_chat_input_con);
        rlVerticalChatNewMsgTips = findViewById(R.id.rl_vertical_chat_new_msg_tips);

        buttonShop = findViewById(R.id.button_shop);
        buttonMore = findViewById(R.id.button_more);

        chatTopLayoutVertical = findViewById(R.id.chat_top_layout_vertical);

        if (DWLiveCoreHandler.getInstance().getInteractionConfigure() != null && DWLiveCoreHandler.getInstance().getInteractionConfigure().getLiveCommerce() > 0) {
            buttonShop.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (clickListener != null){
                        clickListener.onShopClick();
                    }
                }
            });
        }else{
            buttonShop.setVisibility(GONE);
        }

        //如果是无聊天模板，不展示聊天布局
        boolean isHasChat = DWLiveCoreHandler.getInstance().hasChatView();
        if (!isHasChat){
            rlVerticalChatInputCon.setVisibility(INVISIBLE);
        }

        buttonMore.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (clickListener != null){
                    clickListener.onMoreClick();
                }
            }
        });

        rlVerticalChatNewMsgTips.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                canShowTips = false;
                rlVerticalChatNewMsgTips.setVisibility(View.GONE);
                if (mChatAdapter.getItemCount() - 1 > 0) {
                    mChatList.smoothScrollToPosition(mChatAdapter.getItemCount() - 1);
                }
            }
        });


        //用户进入动画
        autoScrollView = findViewById(R.id.auto_scroll_view);
        mEmoji.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                //如果当前软键盘处于显示状态
                if (isSoftInput) {
                    showEmojiAction = true;
                    //1显示表情键盘
                    showEmoji();
                    //2隐藏软键盘
                    mImm.hideSoftInputFromWindow(mInput.getWindowToken(), 0);
                } else if (isEmojiShow) {  //表情键盘显示，软键盘没有显示，则直接显示软键盘
                    mImm.showSoftInput(mInput, 0);
                } else { //软键盘和表情键盘都没有显示
                    //显示表情键盘
                    showEmoji();
                }
            }
        });
        mChatSend.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                String msg = mInput.getText().toString().trim();
                if (TextUtils.isEmpty(msg)) {
                    toastOnUiThread("聊天内容不能为空");
                    return;
                }
                DWLive.getInstance().sendPublicChatMsg(msg);
                clearChatInput();
                //隐藏键盘
                mImm.hideSoftInputFromWindow(mInput.getWindowToken(), 0);
                //隐藏表情
                showSendButton(false);
                frameChatRoot.setTranslationY(0);
                chatTopLayoutVertical.setTranslationY(0);
                autoScrollView.setTranslationY(0);
                hideEmoji();
            }
        });

        this.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction()==MotionEvent.ACTION_DOWN){
                    frameChatRoot.setTranslationY(0);
                    chatTopLayoutVertical.setTranslationY(0);
                    autoScrollView.setTranslationY(0);
                    hideKeyboard();
                }
                return false;
            }
        });

    }

    @SuppressLint("ClickableViewAccessibility")
    public void initChat() {
        mImm = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE);
        mChatList.setLayoutManager(new LinearLayoutManager(mContext));
        mChatAdapter = new VerticalLivePublicChatAdapter(mContext);
        mChatList.setAdapter(mChatAdapter);

        mChatAdapter.setOnChatImageClickListener(new VerticalLivePublicChatAdapter.onChatComponentClickListener() {
            @Override
            public void onChatComponentClick(View view, Bundle bundle) {
                if (mChatComponentClickListener != null) {
                    mChatComponentClickListener.onClickChatComponent(bundle);
                }
            }
        });

        mChatAdapter.setOnItemClickListener(new VerticalLivePublicChatAdapter.onItemClickListener() {
            @Override
            public void onItemClick(int position) {
                ChatEntity chatEntity = mChatAdapter.getChatEntities().get(position);
                // 判断聊天的角色，目前机制只支持和主讲、助教、主持人进行私聊
                // 主讲（publisher）、助教（teacher）、主持人（host）、学生或观众（student）、其他没有角色（unknow）
                if (chatEntity.getUserRole() == null || "student".equals(chatEntity.getUserRole()) || "unknow".equals(chatEntity.getUserRole())||!DWLive.getInstance().getRoomInfo().getPrivateChat().equals("1")) {
                    Log.w(TAG, "只支持和主讲、助教、主持人进行私聊");
                    //toastOnUiThread("只支持和主讲、助教、主持人进行私聊");
                    return;
                }

            }
        });

        mChatList.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                Log.i(TAG, "onScrollStateChanged: newState="+newState+"");
                Log.i(TAG, "onScrollStateChanged: mChatList.canScrollVertically(-1)="+(mChatList.canScrollVertically(1))+"");
                if (newState==0&&!mChatList.canScrollVertically(1)){
                    //滑动到底部
                    Log.i(TAG, "onScrollStateChanged: newState="+newState+"");
                    canShowTips = false;
                    rlVerticalChatNewMsgTips.setVisibility(View.GONE);
                }
            }

            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
            }
        });
        mChatList.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                frameChatRoot.setTranslationY(0);
                chatTopLayoutVertical.setTranslationY(0);
                autoScrollView.setTranslationY(0);
                hideKeyboard();

                if (motionEvent.getAction()==MotionEvent.ACTION_UP){
                    Log.i(TAG, "onTouch: 2");
                    if (mChatList.canScrollVertically(1)){
                        canShowTips = true;
                    }else {
                        canShowTips = false;
                        rlVerticalChatNewMsgTips.setVisibility(View.GONE);
                    }
                }

                return false;
            }
        });

        initChatView();

        DWLiveCoreHandler dwLiveCoreHandler = DWLiveCoreHandler.getInstance();
        if (dwLiveCoreHandler != null) {
            dwLiveCoreHandler.setDwLiveChatListener(this);
            dwLiveCoreHandler.setUserListener(this);
        }
    }


    @SuppressLint("ClickableViewAccessibility")
    public void initChatView() {
        mInput.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
//                hideEmoji();
                return false;
            }
        });
        mInput.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                String inputText = mInput.getText().toString();
                if (inputText.length() > maxInput) {
                    CustomToast.showToast(mContext, "字数超过300字", Toast.LENGTH_SHORT);
                    EmojiUtil.changeTextToEmoji(mContext, mInput, inputText.substring(0, maxInput));
                    mInput.setSelection(maxInput);
                }
            }
        });

        emojiLayout.setEmojiLayoutListener(new EmojiLayout.EmojiLayoutListener() {
            @Override
            public void onItemClick(boolean isDefault, String name, int position) {
                if (mInput == null) {
                    return;
                }

                if (isDefault) {
                    // 通用表情span占位8个字符
                    if (mInput.getText().length() + 8 > maxInput) {
                        toastOnUiThread("字符数超过300字");
                        return;
                    }
                    EmojiUtil.addEmoji(mContext, mInput, position);
                } else {
                    //自定义表情需要单独计算
                    if (mInput.getText().length() + name.length() > maxInput) {
                        toastOnUiThread("字符数超过300字");
                        return;
                    }
                    EmojiUtil.addEmoji(mContext, mInput, name);
                }
            }

            @Override
            public void delete() {
                EmojiUtil.deleteInputOne(mInput);
            }
        });
    }


    public void hideChatLayout() {
        if (isChat) {
            AlphaAnimation animation = new AlphaAnimation(0f, 1f);
            animation.setDuration(300L);
            mInput.setFocusableInTouchMode(false);
            mInput.clearFocus();
            mChatLayout.setVisibility(View.VISIBLE);
            isChat = false;
        }
    }

    /**
     * 显示emoji
     */
    public void showEmoji() {
        if (emojiLayout.getHeight() != softKeyHeight && softKeyHeight != 0) {
            ViewGroup.LayoutParams lp = emojiLayout.getLayoutParams();
            lp.height = softKeyHeight;
            emojiLayout.setLayoutParams(lp);
        }
        emojiLayout.reset();
        emojiLayout.setVisibility(View.VISIBLE);
        mEmoji.setImageResource(R.drawable.icon_vertical_live_keyboard);
        isEmojiShow = true;
        float transY;
        if (softKeyHeight == 0) {
            transY = -emojiLayout.getHeight();
        } else {
            transY = -softKeyHeight;
        }
        frameChatRoot.setTranslationY(transY);
        chatTopLayoutVertical.setTranslationY(transY);
        autoScrollView.setTranslationY(transY);
        showSendButton(true);
    }

    /**
     * 隐藏emoji
     */
    public void hideEmoji() {
        emojiLayout.setVisibility(View.GONE);
        if (isBanChat){
            mEmoji.setImageResource(R.drawable.icon_vertical_live_emoji_disable);
        }else {
            mEmoji.setImageResource(R.drawable.icon_vertical_live_emoji_enable);
        }
        isEmojiShow = false;
    }

    public void clearChatInput() {
        mInput.setText("");
//        hideKeyboard();
    }

    public void hideKeyboard() {
        hideEmoji();
        showSendButton(false);
        mImm.hideSoftInputFromWindow(mInput.getWindowToken(), 0);
    }

    public boolean onBackPressed() {
        if (isEmojiShow) {
            frameChatRoot.setTranslationY(0);
            chatTopLayoutVertical.setTranslationY(0);
            autoScrollView.setTranslationY(0);
            showSendButton(false);
            hideEmoji();
            hideChatLayout();
            return true;
        }
        return false;
    }

    private void clearChatEntities() {
        if (mChatAdapter != null) {
            mChatAdapter.clearData();
        }
    }

    private void showSendButton(boolean show){
        if (show){
            mChatSend.setVisibility(View.VISIBLE);
            showShopBtn(false);
            buttonMore.setVisibility(View.GONE);
        }else {
            mChatSend.setVisibility(View.GONE);
            showShopBtn(true);
            buttonMore.setVisibility(View.VISIBLE);
        }
    }

    private void showShopBtn(boolean show){
        if (show&&(DWLiveCoreHandler.getInstance().getInteractionConfigure() != null && DWLiveCoreHandler.getInstance().getInteractionConfigure().getLiveCommerce() > 0)){
            buttonShop.setVisibility(View.VISIBLE);
        }else {
            buttonShop.setVisibility(View.GONE);
        }
    }

    public void addChatEntity(ChatEntity chatEntity) {
        mChatAdapter.add(chatEntity);
        if (mChatAdapter.getItemCount() - 1 > 0) {
            Viewer viewer = DWLive.getInstance().getViewer();
            String selfId = "";
            if (viewer == null) {
                selfId = "";
            } else {
                selfId = viewer.getId();
            }
            if (("0".equals(chatEntity.getStatus()) || selfId.equals(chatEntity.getUserId()))){
                if (canShowTips){
                    rlVerticalChatNewMsgTips.setVisibility(View.VISIBLE);
                }else {
                    rlVerticalChatNewMsgTips.setVisibility(View.GONE);
                    mChatList.smoothScrollToPosition(mChatAdapter.getItemCount() - 1);
                }
            }
        }
    }

    /*** 修改聊天内容的显示状态（0：显示  1：不显示）***/
    public void changeChatStatus(String status, ArrayList<String> chatIds) {
        List<ChatEntity> chatEntities = mChatAdapter.changeStatus(status, chatIds);
        if (chatEntities.size()>0&&"0".equals(status)){
            //有新消息，定位
            if (canShowTips){
                rlVerticalChatNewMsgTips.setVisibility(View.VISIBLE);
            }else {
                rlVerticalChatNewMsgTips.setVisibility(View.GONE);
                mChatList.smoothScrollToPosition(mChatAdapter.getItemCount() - 1);
            }
        }
        String selfId = "";
        if (DWLive.getInstance()!=null
                &&DWLive.getInstance().getViewer()!=null
                &&!TextUtils.isEmpty(DWLive.getInstance().getViewer().getId())){
            selfId = DWLive.getInstance().getViewer().getId();
        }
        for (ChatEntity chatEntity:chatEntities){
            if (chatEntity!=null&&selfId.equals(chatEntity.getUserId())){
                continue;
            }
            ChatMessage chatMessage = new ChatMessage();
            chatMessage.setChatId(chatEntity.getChatId());
            chatMessage.setUserId(chatEntity.getUserId());
            chatMessage.setUserName(chatEntity.getUserName());
            chatMessage.setUserRole(chatEntity.getUserRole());
            chatMessage.setMessage(chatEntity.getMsg());
            chatMessage.setTime(chatEntity.getTime());
            chatMessage.setAvatar(chatEntity.getUserAvatar());
            chatMessage.setStatus(chatEntity.getStatus());
            publishBarrageOnly(chatMessage);
        }
    }

    public void delChatEntity(String chatId) {
        mChatAdapter.remove(chatId);
    }


    private ChatEntity getChatEntity(ChatMessage msg) {
        ChatEntity chatEntity = new ChatEntity();
        chatEntity.setChatId(msg.getChatId());
        chatEntity.setUserId(msg.getUserId());
        chatEntity.setUserName(msg.getUserName());
        chatEntity.setPrivate(!msg.isPublic());
        chatEntity.setUserRole(msg.getUserRole());

        if (DWLive.getInstance().getViewer()!=null&&msg.getUserId().equals(DWLive.getInstance().getViewer().getId())) {
            chatEntity.setPublisher(true);
        } else {
            chatEntity.setPublisher(false);
        }

        chatEntity.setMsg(msg.getMessage());
        chatEntity.setTime(msg.getTime());
        chatEntity.setUserAvatar(msg.getAvatar());
        chatEntity.setStatus(msg.getStatus());
        return chatEntity;
    }

    /**
     * 展示广播内容
     *
     */
    private void showBroadcastMsg(final BroadCastMsg msg) {
        if (msg == null) {
            return;
        }
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                // 构建一个对象
                ChatEntity chatEntity = new ChatEntity();
                chatEntity.setChatId(msg.getId());
                chatEntity.setIsBroadcast(true);
                chatEntity.setUserId("");
                chatEntity.setUserName("");
                chatEntity.setPrivate(false);
                chatEntity.setPublisher(true);
                chatEntity.setMsg(String.format("系统消息: %s", msg.getContent()));
                chatEntity.setTime("");
                chatEntity.setStatus("0");  // 显示
                chatEntity.setUserAvatar("");
                addChatEntity(chatEntity);
            }
        });
    }

    //------------------------ 处理直播聊天回调信息 ------------------------------------

    // 获取历史消息集合
    private ArrayList<ChatEntity> list = new ArrayList<>();
    private boolean hasBroadcastMsg = false; // 主要为了防止数据重复

    // 收到历史广播信息，在收到历史消息之前处理
    @Override
    public void onHistoryBroadcastMsg(ArrayList<BroadCastMsg> msgs) {
        hasBroadcastMsg = true;
        list.clear();
        final ArrayList<ChatEntity> list1 = mChatAdapter.getChatEntities();
        for (final BroadCastMsg castMsg : msgs) {
            ChatEntity chatEntity = new ChatEntity();
            chatEntity.setChatId(castMsg.getId());
            chatEntity.setIsBroadcast(true);
            chatEntity.setUserId("");
            chatEntity.setUserName("");
            chatEntity.setPrivate(false);
            chatEntity.setPublisher(true);
            chatEntity.setMsg(String.format("系统消息: %s", castMsg.getContent()));
            chatEntity.setTime(String.valueOf(castMsg.getTime()));
            chatEntity.setStatus("0");  // 显示
            chatEntity.setUserAvatar("");
            if (list1.contains(chatEntity)) {
                continue;
            }
            list.add(chatEntity);
        }

    }

    // 收到历史聊天信息
    @Override
    public void onHistoryChatMessage(final ArrayList<ChatMessage> historyChats) {
        Log.i(TAG, "onHistoryChatMessage: ");
        if (historyChats == null || historyChats.size() == 0) {
            return;
        }
        if (!hasBroadcastMsg) {
            list.clear();
        }
        hasBroadcastMsg = false;
        for (int i = 0; i < historyChats.size(); i++) {

            ChatEntity chatEntity = getChatEntity(historyChats.get(i));
            ArrayList<ChatEntity> chatEntities = mChatAdapter.getChatEntities();
            if (chatEntities.contains(chatEntity)) {
                continue;
            }
            if (barrageLayout != null) {
                // 聊天支持发送图片，需要判断聊天内容是否为图片，如果不是图片，再添加到弹幕 && 聊天状态为显示
                if (!ChatImageUtils.isImgChatMessage(historyChats.get(i).getMessage()) && "0".equals(historyChats.get(i).getStatus())) {
                    //判断横竖屏
                    if (getContext().getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
                        barrageLayout.addNewInfo(historyChats.get(i));
                    } else if (getContext().getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
                        //竖屏不需要添加
                    }
                }
            }
            list.add(chatEntity);
        }
        // 排序 -->兼容历史服务器版本处理，服务器最新版不需要加try catch
        try {
            Collections.sort(list, new Comparator<ChatEntity>() {
                @Override
                public int compare(ChatEntity o1, ChatEntity o2) {
                    int time = Integer.parseInt(o1.getTime());
                    int time2 = Integer.parseInt(o2.getTime());
                    if (time == time2) {
                        return 0;
                    }
                    if (time > time2) {
                        return 1;
                    } else {
                        return -1;
                    }
                }

            });
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 注：历史聊天信息中 ChatMessage 的 currentTime = ""
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                // 将历史聊天信息添加到UI
                mChatAdapter.add(list);
                //滚动到最后
                Log.i(TAG, "onHistoryChatMessage/run: mChatAdapter.getItemCount()="+mChatAdapter.getItemCount());
                mChatList.scrollToPosition(mChatAdapter.getItemCount()-1);

            }
        });
    }

    /**
     * 接收到聊天信息状态改变消息，重新发送弹幕
     */
    private void publishBarrageOnly(final ChatMessage msg){
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (barrageLayout != null) {
                    // 聊天支持发送图片，需要判断聊天内容是否为图片，如果不是图片，再添加到弹幕
                    boolean flag = false;
                    if (DWLive.getInstance()!=null
                            &&DWLive.getInstance().getViewer()!=null
                            &&!TextUtils.isEmpty(DWLive.getInstance().getViewer().getId())
                            &&!TextUtils.isEmpty(msg.getUserId())
                            &&DWLive.getInstance().getViewer().getId().equals(msg.getUserId())){
                        flag = true;
                    }

                    if (!ChatImageUtils.isImgChatMessage(msg.getMessage()) && getContext().getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE
                            &&(flag||"0".equals(msg.getStatus()))) {
                        barrageLayout.addNewInfo(msg);
                    }
                }
            }
        });
    }

    @Override
    public void onPublicChatMessage(final ChatMessage msg) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (barrageLayout != null) {
                    // 聊天支持发送图片，需要判断聊天内容是否为图片，如果不是图片，再添加到弹幕
                    boolean flag = false;
                    if (DWLive.getInstance()!=null
                            &&DWLive.getInstance().getViewer()!=null
                            &&!TextUtils.isEmpty(DWLive.getInstance().getViewer().getId())
                            &&!TextUtils.isEmpty(msg.getUserId())
                            &&DWLive.getInstance().getViewer().getId().equals(msg.getUserId())){
                        flag = true;
                    }

                    if (!ChatImageUtils.isImgChatMessage(msg.getMessage()) && getContext().getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE
                            &&(flag||"0".equals(msg.getStatus()))) {
                        barrageLayout.addNewInfo(msg);
                    }
                }
                addChatEntity(getChatEntity(msg));
            }
        });
    }

    @Override
    public void onBanDeleteChat(final String userId) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (mChatAdapter != null) {
                    mChatAdapter.banDeleteChat(userId);
                }
            }
        });
    }

    /**
     * 收到聊天信息状态管理事件
     *
     * @param msgStatusJson 聊天信息状态管理事件json
     */
    @Override
    public void onChatMessageStatus(final String msgStatusJson) {
        if (TextUtils.isEmpty(msgStatusJson)) {
            return;
        }
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                try {
                    JSONObject jsonObject = new JSONObject(msgStatusJson);
                    String status = jsonObject.getString("status");
                    JSONArray chatIdJson = jsonObject.getJSONArray("chatIds");
                    ArrayList<String> chatIds = new ArrayList<>();
                    for (int i = 0; i < chatIdJson.length(); i++) {
                        chatIds.add(chatIdJson.getString(i));
                    }
                    changeChatStatus(status, chatIds);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    @Override
    public void onSilenceUserChatMessage(final ChatMessage msg) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                addChatEntity(getChatEntity(msg));
            }
        });
    }


    private boolean isBanChat = false;
    /**
     * 收到禁言事件
     *
     * @param mode 禁言类型 1：个人禁言  2：全员禁言
     */
    @Override
    public void onBanChat(final int mode) {
        isBanChat = true;
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
               setChatStatus(false);
            }
        });

    }

    private View rootView;

    public void setPopView(View rootView) {
        this.rootView = rootView;
    }

    /**
     * 收到解除禁言事件
     *
     * @param mode 禁言类型 1：个人禁言  2：全员禁言
     */
    @Override
    public void onUnBanChat(final int mode) {
        isBanChat = false;

        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                setChatStatus(true);
            }
        });

    }

    private void setChatStatus(boolean enable) {
        if (enable){
            mInput.setEnabled(true);
            mInput.setHint("赶快发言吧...");
            mInput.setHintTextColor(mContext.getResources().getColor(R.color.color_vertical_live_chat_hint));
            mEmoji.setClickable(true);
            mEmoji.setImageResource(R.drawable.icon_vertical_live_emoji_enable);
        }else {
            mInput.setEnabled(false);
            mInput.setHint("文字聊天已关闭~");
            mInput.setHintTextColor(mContext.getResources().getColor(R.color.color_vertical_live_chat_hint_disable));
            mEmoji.setClickable(false);
            mEmoji.setImageResource(R.drawable.icon_vertical_live_emoji_disable);
        }
    }


    @Deprecated
    @Override
    public void onBroadcastMsg(String msg) {
        // showBroadcastMsg(msg);
    }


    /**
     * 收到广播信息
     */
    @Override
    public void onBroadcastMsg(BroadCastMsg msg) {
        showBroadcastMsg(msg);
    }


    /*删除广播消息*/
    @Override
    public void onBroadcastMsgDel(final String id) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                delChatEntity(id);
            }
        });

    }

    /***************************** 弹幕 ******************************/
    private BarrageLayout barrageLayout;

    /**
     * 设置弹幕组件
     */
    public void setBarrageLayout(BarrageLayout layout) {
        barrageLayout = layout;
    }

    @Override
    public void onKeyboardHeightChanged(int height, int orientation) {
        Log.i(TAG, "onKeyboardHeightChanged?height="+height+"&orientation="+orientation+"");
        if (height > 10) {
            showSendButton(true);
            isSoftInput = true;
            softKeyHeight = height;
            frameChatRoot.setTranslationY(-softKeyHeight);
            chatTopLayoutVertical.setTranslationY(-softKeyHeight);
            autoScrollView.setTranslationY(-softKeyHeight);
            if (isBanChat){
                mEmoji.setImageResource(R.drawable.icon_vertical_live_emoji_disable);
            }else {
                mEmoji.setImageResource(R.drawable.icon_vertical_live_emoji_enable);
            }
            isEmojiShow = false;
        } else {
            if (!showEmojiAction) {
                showSendButton(false);
                frameChatRoot.setTranslationY(0);
                chatTopLayoutVertical.setTranslationY(0);
                autoScrollView.setTranslationY(0);
                hideEmoji();
            }
            isSoftInput = false;

        }
        //结束动作指令
        showEmojiAction = false;
    }

    @Override
    public void HDUserRemindWithAction(UserRedminAction userJoinExitAction) {
        //判断观众段是否需要接受
        if (userJoinExitAction.getClientType().contains(4)) {
            autoScrollView.addDate(userJoinExitAction);
        }
    }

    @Override
    public void HDBanChatBroadcastWithData(BanChatBroadcast banChatBroadcast) {
        toastOnUiThread("用户" + banChatBroadcast.getUserName() + "被禁言了");
    }

    @Override
    public void onChatTop(ArrayList<CCChatTopBean> chatTopBeanList) {
        if (chatTopBeanList!=null){

            chatTopBeanArrayList.addAll(0,chatTopBeanList);

            if (chatTopBeanArrayList.size()>10){
                chatTopBeanArrayList.remove(chatTopBeanList.size()-1);
            }
        }


        refreshChatTop();

    }

    @Override
    public void onUnChatTop(ArrayList<String> chatIdList) {
        if (chatIdList==null||chatIdList.size()==0){
            return;
        }

        Iterator<CCChatTopBean> iterator = chatTopBeanArrayList.iterator();

        while (iterator.hasNext()){
            CCChatTopBean ccChatTopBean = iterator.next();
            if (ccChatTopBean!=null){
                String id = ccChatTopBean.getId();
                if (!TextUtils.isEmpty(id)){
                    if (chatIdList.contains(id)){
                        iterator.remove();
                    }
                }
            }
        }

        refreshChatTop();


    }

    private void refreshChatTop() {
        chatTopLayoutVertical.setData(chatTopBeanArrayList);
    }

    private ClickListener clickListener;
    public void setOnClickBottomStatusListener(ClickListener clickListener){
        this.clickListener = clickListener;
    }

    public interface ClickListener {
        void onShopClick();
        void onMoreClick();
    }
}
