package com.bokecc.livemodule.live.chat.adapter;


import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.text.Layout;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.StaticLayout;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.core.widget.NestedScrollView;
import androidx.recyclerview.widget.RecyclerView;

import com.bokecc.dwlivedemo.R;
import com.bokecc.livemodule.live.chat.module.ChatEntity;
import com.bokecc.livemodule.live.chat.module.ChatTopEntity;
import com.bokecc.livemodule.live.chat.util.EmojiUtil;
import com.bokecc.livemodule.utils.ChatImageUtils;
import com.bokecc.livemodule.utils.UserRoleUtils;
import com.bokecc.livemodule.view.SizeUtils;
import com.bokecc.sdk.mobile.live.DWLive;
import com.bokecc.sdk.mobile.live.pojo.Viewer;

import java.util.ArrayList;
import java.util.regex.Pattern;

/**
 * 直播公聊适配器
 */
public class VerticalLiveChatTopAdapter extends RecyclerView.Adapter<VerticalLiveChatTopAdapter.ChatViewHolder> {

    private Context mContext;
    private ArrayList<ChatTopEntity> list;
    private LayoutInflater mInflater;
    private String selfId = "";
    public static final String regular = "((http[s]{0,1}|ftp)://[a-zA-Z0-9\\.\\-]+\\.([a-zA-Z]{2,4})(:\\d+)?(/[a-zA-Z0-9\\.\\-~!@#$%^&*+?:_/=<>]*)?)|(www.[a-zA-Z0-9\\.\\-]+\\.([a-zA-Z]{2,4})(:\\d+)?(/[a-zA-Z0-9\\.\\-~!@#$%^&*+?:_/=<>]*)?)";

    private Pattern pattern;

    public VerticalLiveChatTopAdapter(Context context) {
        list = new ArrayList<>();
        mContext = context;
        mInflater = LayoutInflater.from(context);
        Viewer viewer = DWLive.getInstance().getViewer();
        if (viewer!=null){
            selfId = viewer.getId();
        }

        pattern = Pattern.compile(regular, Pattern.CASE_INSENSITIVE);


    }




    public void add(ArrayList<ChatTopEntity> data) {
        this.list.addAll(data);
        notifyDataSetChanged();
    }

    public void setList(ArrayList<ChatTopEntity> data) {
        this.list.clear();
        this.list.addAll(data);
        notifyDataSetChanged();
    }


    public void remove(String chatId) {
        int size = list.size();
        int position = -1;
        for (int i = 0; i < size; i++) {
            ChatTopEntity chatEntity = list.get(i);
            if (chatEntity.getId() != null && chatEntity.getId().equals(chatId)) {
                position = i;
                break;
            }
        }
        if (position >= 0) {
            list.remove(position);
            notifyItemRemoved(position);
        }
    }


    /**
     * 清楚聊天数据
     */
    public void clearData() {
        if (list == null) {
            return;
        }
        list.clear();
        notifyDataSetChanged();
    }

    /**
     * 添加数据
     */
    public void add(ChatTopEntity data) {
        list.add(data);

        notifyDataSetChanged();
    }


    @Override
    public ChatViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View itemView = LayoutInflater.from(mContext).inflate(R.layout.vertical_live_chat_top_item, parent, false);
        return new ChatViewHolder(itemView, viewType);
    }

    @Override
    public void onBindViewHolder(final ChatViewHolder holder, @SuppressLint("RecyclerView") final int position) {

        //显示用户名
        TextView chatContent = holder.mContent;
        final TextView chatContent2 = holder.mContent2;

        final ChatTopEntity ccChatTopBean = list.get(position);

        final String content = ccChatTopBean.getContent();
        int role = ccChatTopBean.getFromViewerRole();
        String userName = ccChatTopBean.getFromViewerName();
        String roleStr = getRoleString(role);
        String viewerId = ccChatTopBean.getFromViewerId();
        boolean isSelf = selfId.equals(viewerId);
        // 展示聊天信息
        // 1. 判断聊天内容是否是图片，如果是就提取出图片链接地址，然后展示图片
        if (ChatImageUtils.isImgChatMessage(content)) {

        } else {
            // 2. 如果聊天内容是正常的内容，就直接展示聊天内容
            String roleName = UserRoleUtils.getVerticalUserRoleName(roleStr);


            if (!TextUtils.isEmpty(roleName)){
                holder.tvChatTopRoleName.setVisibility(View.VISIBLE);
                holder.tvChatTopRoleName.setText(roleName);
                holder.tvChatTopRoleName.setBackgroundResource(UserRoleUtils.getVerticalUserRoleBg(roleStr));
            }else {
                holder.tvChatTopRoleName.setVisibility(View.GONE);
                holder.tvChatTopRoleName.setText("");
            }


            String nickname = userName;
            if (viewerId.equals(selfId)){
                nickname+="(我)：";
            }else {
                nickname+="：";
            }


            SpannableString s2 = new SpannableString(nickname);
            int index2 = 0;
            // 判断是否是自己发出的聊天
            ForegroundColorSpan foregroundColorSpan;
            if (isSelf) {
                foregroundColorSpan = new ForegroundColorSpan(Color.parseColor("#FFDD99"));
            }else {
                foregroundColorSpan = UserRoleUtils.getVerticalUserRoleColorSpan(roleStr);
            }
            s2.setSpan(foregroundColorSpan, index2,index2 + nickname.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            chatContent.setText(s2);




            SpannableString spannableString = EmojiUtil.parseFaceMsg(mContext, new SpannableString(content));
            chatContent2.setText(spannableString);

            int textViewWidth = SizeUtils.dp2px(mContext,250);
            TextPaint paint = chatContent2.getPaint();

            StaticLayout staticLayout = new StaticLayout(spannableString,paint,textViewWidth, Layout.Alignment.ALIGN_NORMAL,1f,0f,true);

            //单行文字
            float textWidthTotal = 0;
            for (int i = 0; i < staticLayout.getLineCount(); i++) {
                textWidthTotal+=staticLayout.getLineWidth(i);
            }

            if (ccChatTopBean.isExpand()){
                //展开
                chatContent2.setMaxLines(2000);
                holder.tvExpand.setText("收起");
                holder.tvExpand.setVisibility(View.VISIBLE);
                //超过3行，固定scroll高度
                if (textWidthTotal>3*textViewWidth){
                    LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) holder.scrollView.getLayoutParams();
                    layoutParams.height = SizeUtils.dp2px(mContext,80f);
                    holder.scrollView.setLayoutParams(layoutParams);
                }else {
                    LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) holder.scrollView.getLayoutParams();
                    layoutParams.height = LinearLayout.LayoutParams.WRAP_CONTENT;
                    holder.scrollView.setLayoutParams(layoutParams);
                }

                Drawable drawable = mContext.getResources().getDrawable(R.drawable.icon_chat_top_close);
                drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
                holder.tvExpand.setCompoundDrawables(null,null,drawable,null);

                holder.mChatItem.post(new Runnable() {
                    @Override
                    public void run() {
                        notifyExpand(position,true,holder.mChatItem.getMeasuredHeight());
                    }
                });
            }else {
                //收缩状态
                if (textWidthTotal>textViewWidth){
                    //超过一行，收缩textview，显示展开
                    chatContent2.setMaxLines(1);
                    holder.tvExpand.setText("展开");
                    holder.tvExpand.setVisibility(View.VISIBLE);
                    Drawable drawable = mContext.getResources().getDrawable(R.drawable.icon_vertical_chat_top_expand);
                    drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
                    holder.tvExpand.setCompoundDrawables(null,null,drawable,null);
                }else {
                    //未超过1行，隐藏按钮
                    holder.tvExpand.setVisibility(View.INVISIBLE);

                }
                LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) holder.scrollView.getLayoutParams();
                layoutParams.height = LinearLayout.LayoutParams.WRAP_CONTENT;
                holder.scrollView.setLayoutParams(layoutParams);

                holder.mChatItem.post(new Runnable() {
                    @Override
                    public void run() {
                        notifyExpand(position,false,holder.mChatItem.getMeasuredHeight());
                    }
                });
            }


            holder.tvExpand.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    ccChatTopBean.setExpand(!ccChatTopBean.isExpand());
                    notifyItemChanged(position);

                }
            });
        }
    }

    private void notifyExpand(int position,boolean expand,int height) {
        if (onExpandChangeListener!=null){
            onExpandChangeListener.onExpand(position,expand,height);
        }
    }

    private String getRoleString(int role) {
        if (role==1){
            return "publisher";
        }else if (role==2){
            return "teacher";
        }else if (role==3){
            return "host";
        }else if (role==4){
            return "student";
        }
        return "";
    }


    // 获取角色对应的名字的颜色
    private ForegroundColorSpan getRoleNameColorSpan(ChatEntity chatEntity) {
        // 判断是否是自己发出的聊天
        if (chatEntity.getUserId().equalsIgnoreCase(selfId)) {
            return new ForegroundColorSpan(Color.parseColor("#ff6633"));
        }
        return UserRoleUtils.getUserRoleColorSpan(chatEntity.getUserRole());
    }


    private OnExpandChangeListener onExpandChangeListener;

    public void setOnExpandChangeListener(OnExpandChangeListener onExpandChangeListener) {
        this.onExpandChangeListener = onExpandChangeListener;
    }

    public void collapseAll() {
        for (int i = 0; i < list.size(); i++) {
            ChatTopEntity chatTopEntity = list.get(i);
            if (chatTopEntity.isExpand()){
                chatTopEntity.setExpand(false);
                notifyItemChanged(i);
            }
        }
    }

    public interface OnExpandChangeListener{
        void onExpand(int position,boolean expand,int height);
    }


    @Override
    public int getItemViewType(int position) {

        return 0;
    }

    @Override
    public int getItemCount() {
        return list.size();
    }

    final class ChatViewHolder extends RecyclerView.ViewHolder {

        int viewType;
        ImageView ivChatTopNameLabel;
        TextView tvChatTopRoleName;
        TextView mContent;
        TextView tvExpand;
        TextView  mContent2;

        NestedScrollView scrollView;

        LinearLayout mChatItem;


        ChatViewHolder(View itemView, int viewType) {
            super(itemView);
            this.viewType = viewType;
            mContent = itemView.findViewById(R.id.chat_top_pc_chat_single_msg);
            ivChatTopNameLabel = itemView.findViewById(R.id.iv_chat_top_name_label);
            tvChatTopRoleName = itemView.findViewById(R.id.tv_chat_top_role_name);
            scrollView = itemView.findViewById(R.id.scroll_view);
            mContent2 = itemView.findViewById(R.id.tv_chat_top_content);
            mChatItem = itemView.findViewById(R.id.chat_top_chat_item_layout);
            tvExpand = itemView.findViewById(R.id.tv_vertical_chat_top_expand);

        }
    }
}