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

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Color;
import android.text.Layout;
import android.text.SpannableString;
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.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

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.DensityUtil;
import com.bokecc.livemodule.utils.UserRoleUtils;
import com.bokecc.livemodule.view.HeadView;
import com.bokecc.livemodule.view.SizeUtils;
import com.bokecc.sdk.mobile.live.DWLive;
import com.bokecc.sdk.mobile.live.pojo.Viewer;
import com.bumptech.glide.Glide;

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

/**
 * 直播公聊适配器
 */
public class LandLiveChatTopAdapter extends RecyclerView.Adapter<LandLiveChatTopAdapter.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 LandLiveChatTopAdapter(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.land_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 chatContent2 chatContent2 = holder.mContent2;
        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);
            String headStr = userName;
            boolean isMe = false;
            if (viewerId.equals(selfId)){
                headStr+="（我）";
                isMe = true;
            }

            chatContent.setText(headStr);
            chatContent.setVisibility(View.VISIBLE);

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


            //  如果头像字段有数据就展示头像，否则按照角色展示角色头像
            if (TextUtils.isEmpty(ccChatTopBean.getFromViewerAvatar())) {
                holder.ivHeadImg.setImageResource(UserRoleUtils.getUserRoleAvatar(roleStr));
            } else {
                Glide.with(mContext).load(ccChatTopBean.getFromViewerAvatar()).placeholder(R.drawable.user_head_icon).into(holder.ivHeadImg);
            }
            //设置头像位置的 讲师 助教 主持人的标
            if (holder.mHeadLogo!=null){
                int userRoleAvatarLogo = UserRoleUtils.getUserRoleAvatarLogo(roleStr);
                if (userRoleAvatarLogo!=-1){
                    holder.mHeadLogo.setVisibility(View.VISIBLE);
                    holder.mHeadLogo.setImageResource(userRoleAvatarLogo);
                }else{
                    holder.mHeadLogo.setVisibility(View.GONE);
                }
            }

            int textViewWidth = DensityUtil.getWidth(mContext)-SizeUtils.dp2px(mContext,100);


            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()){
                //展开状态
                holder.mContent2.setMaxLines(2000);
                //展开收起按钮
                holder.tvExpand.setVisibility(View.GONE);
                holder.tvExpand2.setVisibility(View.VISIBLE);
                if (textWidthTotal>4*textViewWidth){
                    //超过4行，固定滚动布局高度为80
                    LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) holder.scrollChatTopContent.getLayoutParams();
                    layoutParams.height = SizeUtils.dp2px(mContext,80f);
                    holder.scrollChatTopContent.setLayoutParams(layoutParams);
                }else {
                    LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) holder.scrollChatTopContent.getLayoutParams();
                    layoutParams.height = LinearLayout.LayoutParams.WRAP_CONTENT;
                    holder.scrollChatTopContent.setLayoutParams(layoutParams);
                }
                notifyExpand(position,true,0);

            }else {
                LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) holder.scrollChatTopContent.getLayoutParams();
                layoutParams.height = LinearLayout.LayoutParams.WRAP_CONTENT;
                holder.scrollChatTopContent.setLayoutParams(layoutParams);
                //折叠状态
                holder.mContent2.setMaxLines(1);
                if (textWidthTotal> textViewWidth){
                    holder.mContent2.setMaxLines(1);
                    holder.tvExpand.setVisibility(View.VISIBLE);
                    holder.tvExpand2.setVisibility(View.GONE);
                }else {
                    holder.tvExpand.setVisibility(View.GONE);
                    holder.tvExpand2.setVisibility(View.GONE);

                }
                notifyExpand(position,false,0);

            }





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

                }
            });
            holder.tvExpand2.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);
        }
    }


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

    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 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 {

        ScrollView scrollChatTopContent;
        int viewType;

        TextView mContent;
        TextView tvExpand;
        TextView tvExpand2;
        TextView  mContent2;

        LinearLayout llScrollViewCon;

        RelativeLayout mChatItem;

        HeadView ivHeadImg;
        ImageView mHeadLogo;


        ChatViewHolder(View itemView, int viewType) {
            super(itemView);
            this.viewType = viewType;
            mContent = itemView.findViewById(R.id.chat_top_pc_chat_single_msg);
            scrollChatTopContent = itemView.findViewById(R.id.scroll_chat_top_content);
            llScrollViewCon = itemView.findViewById(R.id.ll_chat_top_scroll_con);
            tvExpand2 = itemView.findViewById(R.id.tv_vertical_chat_top_expand_2);
            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);
            ivHeadImg = itemView.findViewById(R.id.iv_chat_top_head_img);
            mHeadLogo = itemView.findViewById(R.id.iv_headview_logo);

        }
    }
}