package com.efounder.chat.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.text.Editable;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.TextWatcher;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.widget.AutoCompleteTextView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.efounder.chat.R;
import com.efounder.chat.db.WeChatDBManager;
import com.efounder.chat.model.ChatLocalSerachBean;
import com.efounder.chat.model.Group;
import com.efounder.chat.struct.StructFactory;
import com.efounder.chat.utils.ChatActivitySkipUtil;
import com.efounder.chat.utils.LXGlideImageLoader;
import com.efounder.mobilecomps.contacts.User;
import com.efounder.recycleviewhelper.MultiItemTypeAdapter;
import com.efounder.recycleviewhelper.base.ItemViewDelegate;
import com.efounder.recycleviewhelper.base.ViewHolder;
import com.efounder.utils.ResStringUtil;
import com.utilcode.util.KeyboardUtils;

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

/**
 * 聊天本地查询，快捷搜索本地联系人以及群组
 *
 * @author yqs
 * @date 2018/10/24
 */

public class ChatLocalSearchActivity extends BaseActivity {

    private LinearLayout activityChatGroupAddress;
    private AutoCompleteTextView etSearch;
    private TextView tvSearchCancel;
    private RecyclerView recyclerView;
    private List<ChatLocalSerachBean> searchBeanList;
    private ChatSearchAdapter chatSearchAdapter;
    private TextView tvNoDataTip;
    //搜索输入的关键字
    private String keyWord = "";

    public static void start(Context context) {
        Intent starter = new Intent(context, ChatLocalSearchActivity.class);
        context.startActivity(starter);
        ((Activity) context).overridePendingTransition(R.anim.push_bottom_in, R.anim.push_bottom_out);
        ;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.wechatview_activity_local_search);
        initView();
        initListener();
        initData();
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    private void initView() {
        activityChatGroupAddress = (LinearLayout) findViewById(R.id.activity_chat_group_address);
        etSearch = (AutoCompleteTextView) findViewById(R.id.et_search);
        tvSearchCancel = (TextView) findViewById(R.id.tv_search_cancel);
        recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        tvNoDataTip = (TextView) findViewById(R.id.tv_no_data_tip);
        etSearch.post(new Runnable() {
            @Override
            public void run() {
                etSearch.setFocusableInTouchMode(true);
                etSearch.requestFocus();
                KeyboardUtils.showSoftInput(etSearch);
            }
        });
    }

    private void initData() {
        searchBeanList = new ArrayList<>();
        chatSearchAdapter = new ChatSearchAdapter(this, searchBeanList);
        chatSearchAdapter.addItemViewDelegate(titleDelegate);
        chatSearchAdapter.addItemViewDelegate(contentItemDelegate);
        recyclerView.setAdapter(chatSearchAdapter);
    }

    @Override
    public void onBackPressed() {
        finish();
    }

    @Override
    public void finish() {
        super.finish();
        overridePendingTransition(R.anim.push_bottom_in, R.anim.push_bottom_out);
    }

    private void initListener() {
        tvSearchCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        etSearch.addTextChangedListener(new TextWatcher() {
            @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 s) {
                keyWord = s.toString();
                tvNoDataTip.setVisibility(View.GONE);
                recyclerView.setVisibility(View.VISIBLE);
                if (s.length() == 0) {
                    searchBeanList.clear();
                    chatSearchAdapter.notifyDataSetChanged();
                } else {
                    queryDataAndRefresh(s.toString());
                }
            }
        });
    }

    /**
     * 查新数据并且刷新界面
     *
     * @param keyword
     */
    private void queryDataAndRefresh(String keyword) {
        searchBeanList.clear();
        chatSearchAdapter.notifyDataSetChanged();
        //查询好友
        List<User> userList = WeChatDBManager.getInstance().searchFriendsByKeyword(keyword);
        if (userList.size() > 0) {
            searchBeanList.add(new ChatLocalSerachBean.Builder()
                    .type(ChatLocalSerachBean.TYPE_TITLE)
                    .name(ResStringUtil.getString(R.string.wrchatview_linman)).build());
        }

        for (int i = 0; i < userList.size(); i++) {
            ChatLocalSerachBean chatLocalSerachBean = new ChatLocalSerachBean.Builder()
                    .bean(userList.get(i))
                    .type(ChatLocalSerachBean.TYPE_FRIEND)
                    .id(userList.get(i).getId())
                    .build();
            searchBeanList.add(chatLocalSerachBean);
        }

        //查询群组
        List<Group> groupList = WeChatDBManager.getInstance().searchGroupByKeyword(keyword);
        if (groupList.size() > 0) {
            searchBeanList.add(new ChatLocalSerachBean.Builder()
                    .type(ChatLocalSerachBean.TYPE_TITLE)
                    .name(ResStringUtil.getString(R.string.chat_room_name)).build());
        }

        for (int i = 0; i < groupList.size(); i++) {
            ChatLocalSerachBean chatLocalSerachBean = new ChatLocalSerachBean.Builder()
                    .bean(groupList.get(i))
                    .type(ChatLocalSerachBean.TYPE_GROUP)
                    .id(groupList.get(i).getGroupId())
                    .build();
            searchBeanList.add(chatLocalSerachBean);
        }
        chatSearchAdapter.notifyDataSetChanged();
        if (userList.size() == 0 && groupList.size() == 0) {
            tvNoDataTip.setVisibility(View.VISIBLE);
            recyclerView.setVisibility(View.GONE);
        }

    }


    /**
     * recycleview的adaper
     */
    public static class ChatSearchAdapter extends MultiItemTypeAdapter<ChatLocalSerachBean> {

        private Context mContext;

        public ChatSearchAdapter(Context context, List<ChatLocalSerachBean> datas) {
            super(context, datas);
            this.mContext = context;
        }
    }

    //内容布局
    public ItemViewDelegate<ChatLocalSerachBean> contentItemDelegate = new ItemViewDelegate<ChatLocalSerachBean>() {
        @Override
        public int getItemViewLayoutId() {
            return R.layout.wechatview_item_local_search;
        }

        @Override
        public boolean isForViewType(ChatLocalSerachBean item, int position) {
            return item.getType() == ChatLocalSerachBean.TYPE_FRIEND || item.getType() == ChatLocalSerachBean.TYPE_GROUP;
        }

        @Override
        public void convert(ViewHolder holder, final ChatLocalSerachBean bean, int position) {
            final int type = bean.getType();
            CharSequence name;
            String avatar;
            CharSequence nickName;
            if (type == ChatLocalSerachBean.TYPE_FRIEND) {
                User user = (User) bean.getBean();
//                name = user.getReMark();
//                avatar = user.getAvatar();
//                nickName = ResStringUtil.getString(R.string.wechatview_nickname) + user.getNickName();
                //name 放入备注+昵称
                name = getUserSpanText(user.getReMark(), user.getNickName());
                avatar = user.getAvatar();
                //nickname 现在放入的是星际id
//                nickName = getSpanText(ResStringUtil.getString(R.string.wechatview_nickname), user.getNickName());
                nickName = getSpanText(ResStringUtil.getString(R.string.im_chat_number) + ":",
                        user.getId() + "");

            } else {
                Group group = (Group) bean.getBean();
                // name = ;
                name = getSpanText("", group.getGroupName());

                avatar = group.getAvatar();
//                nickName = group.getRecommond().equals("") ? ResStringUtil
//                        .getString(R.string.wechatview_no_group_recommend) : group.getRecommond();
                nickName = getSpanText(ResStringUtil.getString(R.string.chatgroupsettingactivity_qh),
                        group.getGroupId() + "");

            }
            holder.setText(R.id.tv_name, name);
            holder.setText(R.id.tv_nick_name, nickName);
            ImageView imageView = holder.getView(R.id.iv_avatar);
            if (type == ChatLocalSerachBean.TYPE_FRIEND) {
                LXGlideImageLoader.getInstance().showRoundUserAvatar(ChatLocalSearchActivity.this, imageView, avatar
                        , LXGlideImageLoader.DEFATLT_AVATAR_RADIUS_12);
            } else {
                LXGlideImageLoader.getInstance().showRoundGrouAvatar(ChatLocalSearchActivity.this, imageView, avatar
                        , LXGlideImageLoader.DEFATLT_AVATAR_RADIUS_12);
            }
            holder.getConvertView().setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (type == ChatLocalSerachBean.TYPE_FRIEND) {
                        Intent intent = new Intent();
                        intent.putExtra("id", bean.getId());
                        intent.putExtra("chattype", StructFactory.TO_USER_TYPE_PERSONAL);
                        ChatActivitySkipUtil.startChatActivity(ChatLocalSearchActivity.this, intent);
                        ChatLocalSearchActivity.this.finish();
                    } else {
                        Intent intent = new Intent();
                        intent.putExtra("id", bean.getId());
                        intent.putExtra("chattype", StructFactory.TO_USER_TYPE_GROUP);
                        ChatActivitySkipUtil.startChatActivity(ChatLocalSearchActivity.this, intent);
                        ChatLocalSearchActivity.this.finish();
                    }
                }
            });
        }
    };
    //标题布局
    public ItemViewDelegate<ChatLocalSerachBean> titleDelegate = new ItemViewDelegate<ChatLocalSerachBean>() {
        @Override
        public int getItemViewLayoutId() {
            return R.layout.wechatview_item_local_search_title;
        }

        @Override
        public boolean isForViewType(ChatLocalSerachBean item, int position) {
            return item.getType() == ChatLocalSerachBean.TYPE_TITLE;
        }

        @Override
        public void convert(ViewHolder holder, ChatLocalSerachBean bean, int position) {
            holder.setText(R.id.tv_name, bean.getName());

        }
    };


    /**
     * 对关键字着色
     *
     * @param prefix
     * @param content
     * @return
     */
    private CharSequence getSpanText(String prefix, String content) {
        SpannableStringBuilder stringBuilder = new SpannableStringBuilder(prefix);
        ForegroundColorSpan blueSpan = new ForegroundColorSpan(getResources().getColor(R.color.deepskyblue));
        int index = content.toLowerCase().indexOf(keyWord.toLowerCase());
        if (index != -1) {
            SpannableStringBuilder contentBuilder = new SpannableStringBuilder(content);
            contentBuilder.setSpan(blueSpan, index, index + keyWord.length(),
                    Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            stringBuilder.append(contentBuilder);
        } else {
            stringBuilder.append(content);
        }

        return stringBuilder;
    }

    /**
     * 对user关键字着色
     *
     * @param remark   备注
     * @param nickName 昵称
     * @return
     */
    private CharSequence getUserSpanText(String remark, String nickName) {
        SpannableStringBuilder stringBuilder = new SpannableStringBuilder("");
        ForegroundColorSpan blueSpan = new ForegroundColorSpan(getResources().getColor(R.color.deepskyblue));


        int index = remark.toLowerCase().indexOf(keyWord.toLowerCase());
        if (index != -1) {
            SpannableStringBuilder remarkBuilder = new SpannableStringBuilder(remark);
            remarkBuilder.setSpan(blueSpan, index, index + keyWord.length(),
                    Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            stringBuilder.append(remarkBuilder);
        } else {
            stringBuilder.append(remark);
        }
        stringBuilder.append("(").append(ResStringUtil.getString(R.string.wechatview_nickname));

        int nickNameIndex = nickName.toLowerCase().indexOf(keyWord.toLowerCase());
        if (nickNameIndex != -1) {
            SpannableStringBuilder nickNameBuilder = new SpannableStringBuilder(nickName);
            nickNameBuilder.setSpan(blueSpan, nickNameIndex, nickNameIndex + keyWord.length(),
                    Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            stringBuilder.append(nickNameBuilder);
        } else {
            stringBuilder.append(nickName);
        }
        stringBuilder.append(")");
        return stringBuilder;
    }
}
