package com.cooleshow.student.adapter;

import android.content.Context;
import android.text.SpannableString;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.cooleshow.base.utils.SizeUtils;
import com.cooleshow.base.utils.UiUtils;
import com.cooleshow.student.R;
import com.cooleshow.usercenter.helper.UserHelper;
import com.rong.io.live.LiveRoomMsgConstants;
import com.rong.io.live.message.RCChatJoinRoomMessage;
import com.rong.io.live.message.RCChatModeMessage;
import com.rong.io.live.message.RCChatroomLocationMessage;
import com.rong.io.live.message.RCOnSnappingUpMessage;
import com.rong.io.live.message.RCUserAddLikeMessage;
import com.rong.io.live.message.RCUserSeatApplyMessage;
import com.rong.io.live.message.RCUserSeatResponseMessage;
import com.rong.io.live.message.RCUserSeatsCtrlMessage;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import io.rong.imlib.model.Message;
import io.rong.imlib.model.MessageContent;
import io.rong.imlib.model.UserInfo;
import io.rong.message.TextMessage;

/**
 * Author by pq, Date on 2022/3/31.
 */
public class MessageAdapter extends RecyclerView.Adapter {
    private Context context;
    private String roomAuthorId = "";
    private ArrayList<Message> mMessageList;
    public static final int MESSAGE_TYPE_TEXT = -1;//文本消息
    public static final int MESSAGE_TYPE_JOIN_ROOM = -2;//加入直播间
    public static final int MESSAGE_TYPE_LOCAL_MSG = -3;//本地消息
    public static final int MESSAGE_TYPE_ADD_LIKE_MSG = -4;//点赞消息
    public static final int MESSAGE_TYPE_SEAT_CTRL_MSG = -5;//连麦控制消息
    public static final int MESSAGE_TYPE_CHAT_CTRL_MSG = -6;//聊天控制消息
    public static final int MESSAGE_TYPE_SEAT_APPLY_MSG = -7;//观众连麦申请
    public static final int MESSAGE_TYPE_SEAT_RESPONSE_MSG = -8;//连麦响应消息
    public static final int MESSAGE_TYPE_ON_SNAP_UP_MSG = -9;//xxx正在抢购
    public static final String[] MSG_TAGS = new String[]{LiveRoomMsgConstants.TAG_TXT, LiveRoomMsgConstants.TAG_CHAT_ROOM_ENTER
            , LiveRoomMsgConstants.TAG_CHAT_ROOM_LOCAL_MSG, LiveRoomMsgConstants.TAG_CHAT_ROOM_ADD_LIKE, LiveRoomMsgConstants.TAG_CHAT_ROOM_SEAT_CTRL
            , LiveRoomMsgConstants.TAG_CHAT_ROOM_CHAT_MODE_CTRL, LiveRoomMsgConstants.TAG_CHAT_ROOM_SEAT_APPLY,
            LiveRoomMsgConstants.TAG_CHAT_ROOM_SEAT_RESPONSE, LiveRoomMsgConstants.TAG_LIVE_ON_SNAP_UP};
    public List<String> msgTags;

    public MessageAdapter(Context context) {
        this.context = context;
        mMessageList = new ArrayList();
        msgTags = Arrays.asList(MSG_TAGS);

    }

    public void addMessage(Message message) {
        if (message == null) {
            return;
        }
        if (TextUtils.isEmpty(message.getObjectName())) {
            return;
        }
        if (!msgTags.contains(message.getObjectName())) {
            return;
        }
        if (message.getContent() instanceof RCUserSeatResponseMessage) {
            RCUserSeatResponseMessage responseMessage = (RCUserSeatResponseMessage) message.getContent();
            if (!TextUtils.equals(responseMessage.getAudienceId(), UserHelper.getUserId())) {
                return;
            }
        }
        if (message.getContent() instanceof RCUserSeatApplyMessage) {
            RCUserSeatApplyMessage applyMessage = (RCUserSeatApplyMessage) message.getContent();
            if (!TextUtils.equals(applyMessage.getAudienceId(), UserHelper.getUserId())) {
                return;
            }
        }
        mMessageList.add(message);
        notifyDataSetChanged();
    }

    public void setRoomAuthorId(String roomAuthorId) {
        this.roomAuthorId = roomAuthorId;
    }

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        switch (viewType) {
            case MESSAGE_TYPE_TEXT:
            case MESSAGE_TYPE_LOCAL_MSG:
                View view = LayoutInflater.from(context).inflate(R.layout.item_live_room_message_text, parent, false);
                return new TextMessageHolder(view);
            case MESSAGE_TYPE_ON_SNAP_UP_MSG:
            case MESSAGE_TYPE_ADD_LIKE_MSG:
            case MESSAGE_TYPE_JOIN_ROOM:
                View joinView = LayoutInflater.from(context).inflate(R.layout.item_live_room_join_message_text, parent, false);
                return new JoinRoomMessageHolder(joinView);
            case MESSAGE_TYPE_SEAT_APPLY_MSG:
            case MESSAGE_TYPE_SEAT_RESPONSE_MSG:
            case MESSAGE_TYPE_CHAT_CTRL_MSG:
            case MESSAGE_TYPE_SEAT_CTRL_MSG:
                View modechangeView = LayoutInflater.from(context).inflate(R.layout.item_live_room_message_mode_change, parent, false);
                return new ModeChangeMessageHolder(modechangeView);
        }
        return null;
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
        Message message = mMessageList.get(position);
        String nickNameShow = "用户" + message != null ? message.getSenderUserId() : "";
        switch (getItemViewType(position)) {
            case MESSAGE_TYPE_LOCAL_MSG:
                TextMessageHolder localMsgHolder = (TextMessageHolder) holder;
                RCChatroomLocationMessage localMsgContent = (RCChatroomLocationMessage) message.getContent();
                localMsgHolder.mTvText.setText(localMsgContent.getContent());
                localMsgHolder.mTvText.setTextColor(context.getResources().getColor(com.cooleshow.base.R.color.color_00d6c9));
                break;
            case MESSAGE_TYPE_TEXT:
                TextMessageHolder textMessageHolder = (TextMessageHolder) holder;
                TextMessage content = (TextMessage) message.getContent();
                Log.i("pq", "textMessage:" + content.toString());
                //昵称
                String authorName = "用户" + message.getUId();
                SpannableString spannableString;
                if (content.getUserInfo() != null) {
                    UserInfo userInfo = content.getUserInfo();
                    if (!TextUtils.isEmpty(userInfo.getName())) {
                        authorName = content.getUserInfo().getName();
                    }
                    if (TextUtils.equals(message.getSenderUserId(), roomAuthorId)) {
                        //房间主讲人
                        spannableString = getRoomAuthorTextStyleSpan(context.getString(R.string.live_msg_text_nickname, authorName), content.getContent());
                    } else {
                        //其他
                        spannableString = getNormalTextStyleSpan(context.getString(R.string.live_msg_text_nickname, authorName), content.getContent());
                    }
                } else {
                    spannableString = getNormalTextStyleSpan(context.getString(R.string.live_msg_text_nickname, authorName), content.getContent());
                }
                textMessageHolder.mTvText.setText(spannableString);
                break;

            case MESSAGE_TYPE_JOIN_ROOM:
                JoinRoomMessageHolder joinRoomMessageHolder = (JoinRoomMessageHolder) holder;
                Message joinMessage = mMessageList.get(position);
                RCChatJoinRoomMessage content1 = (RCChatJoinRoomMessage) joinMessage.getContent();
                String name = "用户" + joinMessage.getSenderUserId();
                if (content1.getUserInfo() != null && !TextUtils.isEmpty(content1.getUserInfo().getName())) {
                    name = content1.getUserInfo().getName();
                }
                joinRoomMessageHolder.mTvText.setText(getNormalTextStyleSpan(name, "进入直播间"));
                break;
            case MESSAGE_TYPE_ADD_LIKE_MSG:
                JoinRoomMessageHolder addLikeMessageHolder = (JoinRoomMessageHolder) holder;
                Message addLikeMessage = mMessageList.get(position);
                RCUserAddLikeMessage addLikeContent = (RCUserAddLikeMessage) addLikeMessage.getContent();
                String nick = "用户" + addLikeMessage.getSenderUserId();
                if (addLikeContent.getUserInfo() != null && !TextUtils.isEmpty(addLikeContent.getUserInfo().getName())) {
                    nick = addLikeContent.getUserInfo().getName();
                }
                int counts = addLikeContent.getCounts();
                addLikeMessageHolder.mTvText.setText(getNormalTextStyleSpan(nick, context.getString(R.string.live_room_add_like_count_text_str, counts)));
                break;
            case MESSAGE_TYPE_SEAT_CTRL_MSG:
                //连麦控制
                ModeChangeMessageHolder seatModeChangeHolder = (ModeChangeMessageHolder) holder;
                Message modeChangeMsg = mMessageList.get(position);
                RCUserSeatsCtrlMessage ctrlContent = (RCUserSeatsCtrlMessage) modeChangeMsg.getContent();
                String nickName = "用户" + modeChangeMsg != null ? modeChangeMsg.getSenderUserId() : "";
                if (!TextUtils.isEmpty(ctrlContent.getUserName())) {
                    nickName = ctrlContent.getUserName();
                }
                boolean isEnableSeat = ctrlContent.isSeatBan();
                String afterContent = isEnableSeat ? "关闭连麦" : "开启连麦";
                seatModeChangeHolder.mIvIcon.setVisibility(View.VISIBLE);
                seatModeChangeHolder.mTvText.setText(getNormalTextStyleSpan(nickName, afterContent));
                break;
            case MESSAGE_TYPE_CHAT_CTRL_MSG:
                //聊天控制
                ModeChangeMessageHolder chatModeChangeHolder = (ModeChangeMessageHolder) holder;
                Message chatModeChangeMsg = mMessageList.get(position);
                RCChatModeMessage chatModeContent = (RCChatModeMessage) chatModeChangeMsg.getContent();
                String nickName2 = "用户" + chatModeChangeMsg != null ? chatModeChangeMsg.getSenderUserId() : "";
                if (!TextUtils.isEmpty(chatModeContent.getUserName())) {
                    nickName2 = chatModeContent.getUserName();
                }
                boolean isEnableChat = chatModeContent.isChatBan();
                String afterContent2 = isEnableChat ? "关闭聊天" : "开启聊天";
                chatModeChangeHolder.mIvIcon.setVisibility(View.VISIBLE);
                chatModeChangeHolder.mTvText.setText(getNormalTextStyleSpan(nickName2, afterContent2));
                break;
            case MESSAGE_TYPE_SEAT_APPLY_MSG:
                ModeChangeMessageHolder seatApplyMsgHolder = (ModeChangeMessageHolder) holder;
                RCUserSeatApplyMessage content2 = (RCUserSeatApplyMessage) message.getContent();
                int type = content2.getType();
                if (type == LiveRoomMsgConstants.MIC_ACTION_SEAT_BY_USER
                        || type == LiveRoomMsgConstants.MIC_ACTION_CANCEL_SEAT_BY_USER) {
                    seatApplyMsgHolder.mIvIcon.setVisibility(View.GONE);
                    seatApplyMsgHolder.mTvText.setPadding(SizeUtils.dp2px(10), 0, SizeUtils.dp2px(10), 0);
                    if (!TextUtils.isEmpty(content2.getAudienceName())) {
                        nickNameShow = content2.getAudienceName();
                    }
                } else {
                    seatApplyMsgHolder.mIvIcon.setVisibility(View.VISIBLE);
                    seatApplyMsgHolder.mTvText.setPadding(SizeUtils.dp2px(5), 0, SizeUtils.dp2px(10), 0);
                    if (!TextUtils.isEmpty(content2.getTeacherName())) {
                        nickNameShow = content2.getTeacherName();
                    }
                }
                String contentText = "";
                if (type == LiveRoomMsgConstants.MIC_ACTION_SEAT_BY_USER) {
                    //观众发起连麦申请
                    contentText = "发起了连麦申请";
                }
                if (type == LiveRoomMsgConstants.MIC_ACTION_CANCEL_SEAT_BY_USER) {
                    //观众取消连麦申请
                    contentText = "取消了连麦申请";
                }

                if (type == LiveRoomMsgConstants.MIC_ACTION_CANCEL_SEAT_BY_CREATE) {
                    //主讲人将观众抱下麦
                    contentText = "将你抱下麦";
                }

                if (type == LiveRoomMsgConstants.MIC_ACTION_INVITE_SEAT_BY_CREATE) {
                    //主讲人发起了连麦邀请
                    contentText = "发起了连麦邀请";
                }
                if (type == LiveRoomMsgConstants.MIC_ACTION_CANCEL_INVITE_SEAT_BY_CREATE) {
                    //主讲人取消了连麦邀请
                    contentText = "取消了连麦邀请";
                }
                seatApplyMsgHolder.mTvText.setText(getNormalTextStyleSpan(nickNameShow, contentText));
                break;
            case MESSAGE_TYPE_SEAT_RESPONSE_MSG:
                ModeChangeMessageHolder seatResponseMsgHolder = (ModeChangeMessageHolder) holder;
                RCUserSeatResponseMessage responseContent = (RCUserSeatResponseMessage) message.getContent();
                int responseType = responseContent.getType();
                if (responseType == LiveRoomMsgConstants.MIC_RESPONSE_AGREE_BY_USER
                        || responseType == LiveRoomMsgConstants.MIC_RESPONSE_DISAGREE_BY_USER) {
                    seatResponseMsgHolder.mIvIcon.setVisibility(View.GONE);
                    seatResponseMsgHolder.mTvText.setPadding(SizeUtils.dp2px(10), 0, SizeUtils.dp2px(10), 0);
                    if (!TextUtils.isEmpty(responseContent.getAudienceName())) {
                        nickNameShow = responseContent.getAudienceName();
                    }
                } else {
                    seatResponseMsgHolder.mIvIcon.setVisibility(View.VISIBLE);
                    seatResponseMsgHolder.mTvText.setPadding(SizeUtils.dp2px(5), 0, SizeUtils.dp2px(10), 0);
                    if (!TextUtils.isEmpty(responseContent.getTeacherName())) {
                        nickNameShow = responseContent.getTeacherName();
                    }
                }
                String responseContentText = "";
                if (responseType == LiveRoomMsgConstants.MIC_RESPONSE_AGREE) {
                    //主讲人同意观众上麦申请
                    responseContentText = "同意了连麦申请";
                }
                if (responseType == LiveRoomMsgConstants.MIC_RESPONSE_DISAGREE) {
                    //主讲人不同意观众上麦申请
                    responseContentText = "取消了连麦申请";
                }
                if (responseType == LiveRoomMsgConstants.MIC_RESPONSE_AGREE_BY_USER) {
                    //观众同意了连麦邀请
                    responseContentText = "同意了连麦邀请";
                }
                if (responseType == LiveRoomMsgConstants.MIC_RESPONSE_DISAGREE_BY_USER) {
                    //观众取消了连麦邀请
                    responseContentText = "取消了连麦邀请";
                }
                seatResponseMsgHolder.mTvText.setText(getNormalTextStyleSpan(nickNameShow, responseContentText));
                break;
            case MESSAGE_TYPE_ON_SNAP_UP_MSG:
                JoinRoomMessageHolder onSnapUpHolder = (JoinRoomMessageHolder) holder;
                Message onSnapUpMessage = mMessageList.get(position);
                RCOnSnappingUpMessage onSnapUpContent = (RCOnSnappingUpMessage) onSnapUpMessage.getContent();
                String lastName = getNickName(onSnapUpMessage, onSnapUpContent != null ? onSnapUpContent.getUserName() : "");
                onSnapUpHolder.mTvText.setText(getNormalTextStyleSpan(lastName, " 正在抢购"));
                break;

        }
    }

    private void setDefaultInfo(Message message) {

    }

    private String getNickName(Message message, String defaultName) {
        if (!TextUtils.isEmpty(defaultName)) {
            return defaultName;
        }
        return getNickName(message);
    }

    private String getNickName(Message message) {
        //昵称
        String name = "用户" + message.getSenderUserId();
        MessageContent content = message.getContent();
        if (content.getUserInfo() != null && !TextUtils.isEmpty(content.getUserInfo().getName())) {
            name = content.getUserInfo().getName();
        }
        return name;
    }

    @Override
    public int getItemCount() {
        return mMessageList != null ? mMessageList.size() : 0;
    }

    @Override
    public int getItemViewType(int position) {
        Message message = mMessageList.get(position);
        String objectName = message.getObjectName();
        if (TextUtils.equals(objectName, LiveRoomMsgConstants.TAG_TXT)) {
            //文本消息
            return MESSAGE_TYPE_TEXT;
        }
        if (TextUtils.equals(objectName, LiveRoomMsgConstants.TAG_CHAT_ROOM_ENTER)) {
            //进入房间消息
            return MESSAGE_TYPE_JOIN_ROOM;
        }

        if (TextUtils.equals(objectName, LiveRoomMsgConstants.TAG_CHAT_ROOM_LOCAL_MSG)) {
            //本地消息
            return MESSAGE_TYPE_LOCAL_MSG;
        }

        if (TextUtils.equals(objectName, LiveRoomMsgConstants.TAG_CHAT_ROOM_ADD_LIKE)) {
            //点赞消息
            return MESSAGE_TYPE_ADD_LIKE_MSG;
        }

        if (TextUtils.equals(objectName, LiveRoomMsgConstants.TAG_CHAT_ROOM_SEAT_CTRL)) {
            //连麦控制
            return MESSAGE_TYPE_SEAT_CTRL_MSG;
        }

        if (TextUtils.equals(objectName, LiveRoomMsgConstants.TAG_CHAT_ROOM_CHAT_MODE_CTRL)) {
            //聊天控制
            return MESSAGE_TYPE_CHAT_CTRL_MSG;
        }

        if (TextUtils.equals(objectName, LiveRoomMsgConstants.TAG_CHAT_ROOM_SEAT_APPLY)) {
            //连麦相关
            return MESSAGE_TYPE_SEAT_APPLY_MSG;
        }
        if (TextUtils.equals(objectName, LiveRoomMsgConstants.TAG_CHAT_ROOM_SEAT_RESPONSE)) {
            //连麦响应相关
            return MESSAGE_TYPE_SEAT_RESPONSE_MSG;
        }

        if (TextUtils.equals(objectName, LiveRoomMsgConstants.TAG_LIVE_ON_SNAP_UP)) {
            //正在抢购
            return MESSAGE_TYPE_ON_SNAP_UP_MSG;
        }
        return super.getItemViewType(position);
    }


    private static class TextMessageHolder extends RecyclerView.ViewHolder {

        private final TextView mTvText;

        public TextMessageHolder(@NonNull View itemView) {
            super(itemView);
            mTvText = itemView.findViewById(R.id.tv_text);
        }
    }

    private static class ModeChangeMessageHolder extends RecyclerView.ViewHolder {

        private final TextView mTvText;
        private final ImageView mIvIcon;

        public ModeChangeMessageHolder(@NonNull View itemView) {
            super(itemView);
            mTvText = itemView.findViewById(R.id.tv_text);
            mIvIcon = itemView.findViewById(R.id.iv_icon);
        }
    }

    private static class JoinRoomMessageHolder extends RecyclerView.ViewHolder {

        private final TextView mTvText;

        public JoinRoomMessageHolder(@NonNull View itemView) {
            super(itemView);
            mTvText = itemView.findViewById(R.id.tv_text);
        }
    }

    private SpannableString getNormalTextStyleSpan(String startStr, String contentText) {
        return UiUtils.diffColorString(startStr
                , contentText
                , context.getResources().getColor(com.cooleshow.base.R.color.color_00d6c9)
                , context.getResources().getColor(R.color.white));
    }

    private SpannableString getRoomAuthorTextStyleSpan(String nickName, String contentText) {
        return UiUtils.diffColorString(nickName
                , contentText
                , context.getResources().getColor(com.cooleshow.base.R.color.color_00d6c9)
                , context.getResources().getColor(R.color.white)
                , context.getResources().getDrawable(R.drawable.icon_live_msg_room_author));
    }
}
