package com.common.im.adapter;

import android.content.Context;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.style.ForegroundColorSpan;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.common.im_ui.R;
import com.cooleshow.base.utils.GlideImageLoaderUtils;
import com.cooleshow.base.utils.GlideUtils;

import java.util.List;

import io.rong.imkit.userinfo.RongUserInfoManager;
import io.rong.imkit.utils.RongDateUtils;
import io.rong.imlib.model.Conversation;
import io.rong.imlib.model.Group;
import io.rong.imlib.model.Message;
import io.rong.imlib.model.MessageContent;
import io.rong.imlib.model.UserInfo;
import io.rong.message.FileMessage;
import io.rong.message.RichContentMessage;
import io.rong.message.TextMessage;

/**
 * 创建日期：2022/6/11 16:15
 *
 * @author Ryan
 * 类说明：
 */
public class MessageSearchAdapter extends BaseQuickAdapter<Message, BaseViewHolder> {

    public MessageSearchAdapter(List<Message> data) {
        super(R.layout.search_fragment_recycler_chatting_records_list, data);
    }

    private String search = "";

    public void setSearch(String search) {
        this.search = search;
    }

    @Override
    protected void convert(BaseViewHolder helper, Message message) {
        ImageView ivPortrait = helper.getView(R.id.item_iv_record_image);
        TextView tvChatName = helper.getView(R.id.item_tv_chat_name);
        TextView tvContent = helper.getView(R.id.item_tv_chatting_records_detail);
        TextView tvDate = helper.getView(R.id.item_tv_chatting_records_date);
        UserInfo userInfo = RongUserInfoManager.getInstance().getUserInfo(message.getSenderUserId());
        if (userInfo != null) {

            if (Conversation.ConversationType.GROUP == message.getConversationType()) {
                Group groupInfo = RongUserInfoManager.getInstance().getGroupInfo(message.getTargetId());
                if (groupInfo != null) {
                    tvChatName.setText(groupInfo.getName());
                }
                GlideImageLoaderUtils.getInstance().loadCircleImage(getContext(), R.drawable.ic_stu_student_head, ivPortrait);

            } else {
                tvChatName.setText(userInfo.getName());
                GlideImageLoaderUtils.getInstance().loadCircleImage(getContext(), userInfo.getPortraitUri(), ivPortrait);
            }
        }
        tvContent.setText(getColoredChattingRecord(search, message.getContent(), tvContent.getContext()));
        String sendTime = RongDateUtils.getConversationFormatDate(message.getSentTime(), getContext());
        tvDate.setText(sendTime);
    }

    public static SpannableStringBuilder getColoredChattingRecord(String filterStr, MessageContent messageContent, Context context) {
        SpannableStringBuilder messageText = new SpannableStringBuilder();
        if (messageContent instanceof TextMessage) {
            TextMessage textMessage = (TextMessage) messageContent;
            String textMessageContent = textMessage.getContent();
            messageText = getOmitColored(filterStr, textMessageContent, 0, context);
        }
        if (messageContent instanceof RichContentMessage) {
            RichContentMessage richContentMessage = (RichContentMessage) messageContent;
            String messageTitle = richContentMessage.getTitle();
            messageText = getOmitColored(filterStr, messageTitle, 1, context);
            if (messageText.length() == 0) {
                SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder("[链接]");
                spannableStringBuilder.append(messageTitle);
                messageText = spannableStringBuilder;
            }
        }
        if (messageContent instanceof FileMessage) {
            FileMessage fileMessage = (FileMessage) messageContent;
            String fileName = fileMessage.getName();
            messageText = getOmitColored(filterStr, fileName, 2, context);
        }
        return messageText;
    }

    public static SpannableStringBuilder getOmitColored(String filterStr, String content, int type, Context context) {
        SpannableStringBuilder messageText = new SpannableStringBuilder();
        String lowerCaseFilterStr = filterStr.toLowerCase();
        String lowerCaseText = content.toLowerCase();
        if (lowerCaseText.contains(lowerCaseFilterStr)) {
            SpannableStringBuilder finalBuilder = new SpannableStringBuilder();
            if (type == 0) {
            } else if (type == 1) {
                finalBuilder.append("[链接]");
            } else if (type == 2) {
                finalBuilder.append("[文件]");
            }
            int length = content.length();
            int firstIndex = lowerCaseText.indexOf(lowerCaseFilterStr);
            String subString = content.substring(firstIndex);
            int restLength;
            if (subString != null) {
                restLength = subString.length();
            } else {
                restLength = 0;
            }
            if (length <= 12) {
                SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder(content);
                spannableStringBuilder.setSpan(new ForegroundColorSpan(context.getResources().getColor(com.cooleshow.base.R.color.color_2dc7aa)), firstIndex, firstIndex + filterStr.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
                return finalBuilder.append(spannableStringBuilder);

            } else {
                //首次出现搜索字符的index加上filter的length；
                int totalLength = firstIndex + filterStr.length();
                if (totalLength < 12) {
                    String smallerString = content.substring(0, 12);
                    SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder(smallerString);
                    spannableStringBuilder.setSpan(new ForegroundColorSpan(context.getResources().getColor(com.cooleshow.base.R.color.color_2dc7aa)), firstIndex, firstIndex + filterStr.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
                    spannableStringBuilder.append("...");
                    return finalBuilder.append(spannableStringBuilder);
                } else if (restLength < 12) {
                    String smallerString = content.substring(length - 12, length);
                    String smallerStringLowerCase = lowerCaseText.substring(length - 12, length);
                    int index = smallerStringLowerCase.indexOf(lowerCaseFilterStr);
                    SpannableStringBuilder builder = new SpannableStringBuilder("...");
                    SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder(smallerString);
                    spannableStringBuilder.setSpan(new ForegroundColorSpan(context.getResources().getColor(com.cooleshow.base.R.color.color_2dc7aa)), index, index + filterStr.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
                    builder.append(spannableStringBuilder);
                    return finalBuilder.append(builder);
                } else {
                    String smallerString;
                    String smallerStringLowerCase;
                    int index = 0;
                    if (firstIndex >= 5) {
                        smallerString = content.substring(firstIndex - 5, firstIndex + 7);
                        smallerStringLowerCase = lowerCaseText.substring(firstIndex - 5, firstIndex + 7);
                        String smallerFilter = lowerCaseFilterStr;
                        if (smallerFilter.length() > 7) {
                            smallerFilter = lowerCaseFilterStr.substring(0, 7);
                        }
                        index = smallerStringLowerCase.indexOf(smallerFilter);
                    } else {
                        smallerString = content.substring(firstIndex, firstIndex + 12);
                        smallerStringLowerCase = lowerCaseText.substring(firstIndex, firstIndex + 12);
                        if (smallerStringLowerCase.length() < lowerCaseFilterStr.length()) {
                            index = 0;
                        }
                    }
                    SpannableStringBuilder builder = new SpannableStringBuilder("...");
                    SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder(smallerString);
                    spannableStringBuilder.setSpan(new ForegroundColorSpan(context.getResources().getColor(com.cooleshow.base.R.color.color_2dc7aa)), index, getSmallerLength(smallerString.length(), index + filterStr.length()), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
                    builder.append(spannableStringBuilder);
                    builder.append("...");
                    return finalBuilder.append(builder);
                }
            }
        }
        return messageText;
    }

    private static int getSmallerLength(int stringLength, int endIndex) {
        return stringLength > endIndex + 1 ? endIndex : stringLength;
    }
}
