package com.common.im.ui.activity;

import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

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

import com.alibaba.android.arouter.facade.annotation.Route;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.common.im.adapter.MessageSearchAdapter;
import com.common.im.contract.SearchHistoryMessageContract;

import io.rong.imkit.utils.helper.ConversationFilterHelper;

import com.common.im.presenter.SearchHistoryMessagePresenter;
import com.common.im_ui.databinding.ActivitySearchHistoryMessageBinding;
import com.cooleshow.base.router.RouterPath;
import com.cooleshow.base.ui.activity.BaseMVPActivity;
import com.cooleshow.base.utils.SoftKeyboardUtil;

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

import io.rong.imkit.RongIM;
import io.rong.imkit.userinfo.RongUserInfoManager;
import io.rong.imkit.utils.StatusBarUtil;
import io.rong.imlib.RongIMClient;
import io.rong.imlib.model.Conversation;
import io.rong.imlib.model.Group;
import io.rong.imlib.model.Message;
import io.rong.imlib.model.SearchConversationResult;
import io.rong.imlib.model.UserInfo;

/**
 * 创建日期：2022/6/11 16:02
 *
 * @author Ryan
 * 类说明：
 */
@Route(path = RouterPath.ChatCenter.CHAT_GROUP_SEARCH_HISTORY)
public class SearchHistoryMessageActivity extends BaseMVPActivity<ActivitySearchHistoryMessageBinding, SearchHistoryMessagePresenter> implements SearchHistoryMessageContract.SearchHistoryMessageView, TextWatcher {


    private EditText etSearch;
    private ImageView ivSearch;
    private TextView tvAction;
    private RecyclerView recyclerView;
    private TextView tvEmpty;

    private MessageSearchAdapter adapter;
    private List<Message> data = new ArrayList<>();
    private List<Conversation> conversations = new ArrayList<>();

    @Override
    protected void initView() {
        etSearch = viewBinding.etSearch;
        ivSearch = viewBinding.ivSearch;
        tvAction = viewBinding.tvAction;
        recyclerView = viewBinding.recyclerView;
        tvEmpty = viewBinding.tvEmptyView;

        etSearch.addTextChangedListener(this);
        ivSearch.setOnClickListener(view -> {
            searchMessage(targetId, Conversation.ConversationType.GROUP, etSearch.getText().toString().trim());
        });
        tvAction.setOnClickListener(view -> {
            SoftKeyboardUtil.hideSoftKeyboard(this);
            finish();
        });


        adapter = new MessageSearchAdapter(data);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.setAdapter(adapter);
        if (TextUtils.isEmpty(targetId)) {
            RongIM.getInstance().getConversationList(new RongIMClient.ResultCallback<List<Conversation>>() {
                @Override
                public void onSuccess(List<Conversation> conversations) {
                    if (conversations != null && conversations.size() > 0) {
                        SearchHistoryMessageActivity.this.conversations.addAll(conversations);
                    }
                }

                @Override
                public void onError(RongIMClient.ErrorCode errorCode) {
                }

            }, Conversation.ConversationType.GROUP, Conversation.ConversationType.PRIVATE);

        }
        adapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                Message message = (Message) adapter.getItem(position);
                if (message != null) {
                    String name = "";
                    if (Conversation.ConversationType.GROUP == message.getConversationType()) {
                        Group groupInfo = RongUserInfoManager.getInstance().getGroupInfo(message.getTargetId());
                        if (groupInfo != null) {
                            name = groupInfo.getName();
                        }
                    } else {
                        UserInfo userInfo = RongUserInfoManager.getInstance().getUserInfo(message.getSenderUserId());
                        if (userInfo != null) {
                            name = userInfo.getName();
                        }
                    }

                    RongIM.getInstance().startConversation(SearchHistoryMessageActivity.this,
                            message.getConversationType(),
                            message.getTargetId(), name,
                            message.getSentTime());
                }
            }
        });


    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        StatusBarUtil.setStatusBarDarkTheme(this, true);
    }

    private String targetId;

    @Override
    public void initData() {
        super.initData();
        targetId = getIntent().getStringExtra("targetId");


    }

    public void searchMessage(String targetId, Conversation.ConversationType
            conversationType, String match) {
        data.clear();
        if (TextUtils.isEmpty(targetId)) {
            if (conversations.size() != 0) {
                for (Conversation conversation : conversations) {
                    searchIMClientMessage(conversation.getTargetId(), conversation.getConversationType(), match);
                }
            } else {
                updateData(new ArrayList<Message>(), match);
            }
        } else {
            searchIMClientMessage(targetId, conversationType, match);
        }
    }

    @Override
    protected ActivitySearchHistoryMessageBinding getLayoutView() {
        return ActivitySearchHistoryMessageBinding.inflate(getLayoutInflater());
    }

    @Override
    protected SearchHistoryMessagePresenter createPresenter() {
        return new SearchHistoryMessagePresenter();
    }

    private void searchIMClientMessage(String targetId, Conversation.ConversationType
            conversationType, String match) {
        RongIMClient.getInstance().searchMessages(conversationType,
                targetId, match, 0, 0, new RongIMClient.ResultCallback<List<Message>>() {

                    @Override
                    public void onSuccess(List<Message> messages) {
                        Iterator<Message> it = messages.iterator();
                        while (it.hasNext()) {
                            Message conversation = it.next();
                            if (conversation.getConversationType() == Conversation.ConversationType.GROUP) {
                                if (!ConversationFilterHelper.checkConversationEnable(conversation.getTargetId())) {
                                    it.remove();
                                }
                            }
                        }
                        updateData(messages, match);
                    }

                    @Override
                    public void onError(RongIMClient.ErrorCode errorCode) {
                        updateData(new ArrayList<>(), match);
                    }
                });
    }

    public void updateData(List<Message> data, String search) {
        if (data != null && data.size() > 0) {
            this.data.addAll(data);
        }
        if (this.data.size() == 0) {
            tvEmpty.setVisibility(View.VISIBLE);
            String empty = String.format("没有搜到%s相关的信息", search);
            int start = empty.indexOf(search);
            tvEmpty.setText(getSpannable(empty, start, start + search.length()));
            recyclerView.setVisibility(View.GONE);
        } else {
            tvEmpty.setVisibility(View.GONE);
            recyclerView.setVisibility(View.VISIBLE);
            if (adapter != null) {
                adapter.setSearch(search);
                adapter.notifyDataSetChanged();
            }
        }
    }

    public SpannableStringBuilder getSpannable(String target, int start, int end) {
        SpannableStringBuilder spannableStringBuilder;
        if (TextUtils.isEmpty(target)) {
            spannableStringBuilder = new SpannableStringBuilder("");
        } else {
            spannableStringBuilder = new SpannableStringBuilder(target);
        }

        spannableStringBuilder.setSpan(new ForegroundColorSpan(getResources().getColor(com.cooleshow.base.R.color.color_2dc7aa)), start, end, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
        return spannableStringBuilder;
    }


    public void search(String search) {
        if (TextUtils.isEmpty(search)) {

            clear();
            recyclerView.setVisibility(View.GONE);
            tvEmpty.setVisibility(View.GONE);
        } else {
            searchMessage(targetId, Conversation.ConversationType.GROUP, search);
        }
    }

    public void clear() {
        this.data.clear();
        adapter.setSearch("");
        adapter.notifyDataSetChanged();
    }

    /**
     * 搜索会话
     *
     * @param match
     */
    public void searchConversation(String match) {
        RongIMClient.getInstance().searchConversations(match,
                new Conversation.ConversationType[]{Conversation.ConversationType.PRIVATE, Conversation.ConversationType.GROUP},
                new String[]{"RC:TxtMsg", "RC:ImgTextMsg", "RC:FileMsg"}, new RongIMClient.ResultCallback<List<SearchConversationResult>>() {

                    @Override
                    public void onSuccess(List<SearchConversationResult> searchConversationResults) {
                    }

                    @Override
                    public void onError(RongIMClient.ErrorCode errorCode) {
                    }
                });
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable editable) {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                String search = editable.toString();
                if (TextUtils.isEmpty(search)) {
                    clear();
                } else {
                    search(search);
                }
            }
        }, 300);
    }
}
