package com.common.im.ui.contact;


import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;


import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.common.im.adapter.ContactListAdapter;
import com.common.im.bean.ContactListBean;
import com.common.im.bean.ContactRoomListBean;
import com.common.im.contract.ContactListFragmentContract;
import com.common.im.helper.ConversationHelper;
import com.common.im.presenter.ContactListPresenter;
import com.common.im_ui.R;
import com.common.im_ui.databinding.FragmentContactListLayoutBinding;
import com.cooleshow.base.common.BaseApplication;
import com.cooleshow.base.utils.SizeUtils;
import com.cooleshow.base.utils.ToastUtil;
import com.cooleshow.base.widgets.EmptyViewLayout;
import com.cooleshow.base.ui.fragment.BaseMVPFragment;
import com.mcxtzhang.indexlib.suspension.SuspensionDecoration;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;

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

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

import io.rong.common.RLog;
import io.rong.imkit.config.ConversationListBehaviorListener;
import io.rong.imkit.config.RongConfigCenter;
import io.rong.imkit.conversationlist.model.GatheredConversation;
import io.rong.imkit.utils.RouteUtils;
import io.rong.imlib.RongIMClient;
import io.rong.imlib.model.Conversation;

/**
 * 联系人列表
 */
public class ContactPersonListFragment extends BaseMVPFragment<FragmentContactListLayoutBinding, ContactListPresenter> implements ContactListFragmentContract.ContactListFragmentView, View.OnClickListener {

    private SuspensionDecoration mDecoration;
    private List<ContactListBean> mDatas = new ArrayList<>();
    private ContactListAdapter mListAdapter;
    private String searchCondition;
    private EmptyViewLayout mEmptyViewLayout;
    private boolean isSelectContact = false;//是否是选择联系人

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

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

    @Override
    protected void initView(View rootView) {
        if (getArguments() != null) {
            isSelectContact = getArguments().getBoolean(ContactListTabFragment.IS_SELECT_CONTACT, false);
        }
        if (BaseApplication.Companion.isTeacherClient()) {
            mViewBinding.etTargetName.setText("请输入学员名称");
        } else {
            mViewBinding.etTargetName.setText("请输入老师名称");
        }
        mViewBinding.tvSearch.setOnClickListener(this);
        mListAdapter = new ContactListAdapter(R.layout.item_contact_list_layout);
        LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
        mViewBinding.recyclerView.setLayoutManager(layoutManager);
        mDecoration = new SuspensionDecoration(getContext(), mDatas);
        mDecoration.setColorTitleBg(Color.TRANSPARENT);
        mDecoration.setmTitleHeight(SizeUtils.dp2px(30));
        mViewBinding.recyclerView.addItemDecoration(mDecoration);
        mViewBinding.livLetters.setmPressedShowTextView(mViewBinding.tvHint)//设置HintTextView
                .setNeedRealIndex(false)//设置需要真实的索引
                .setmLayoutManager(layoutManager);//设置RecyclerView的LayoutManager
        mViewBinding.recyclerView.setAdapter(mListAdapter);
        mListAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                if (isSelectContact) {
                    ContactListBean item = (ContactListBean) mListAdapter.getItem(position);
                    //选择联系人模式
                    if (getActivity() != null) {
                        Intent intent = new Intent();
                        intent.putExtra(ConversationHelper.TARGET_ID_KEY, item.friendId);
                        intent.putExtra(ConversationHelper.CONVERSATION_TYPE_KEY, Conversation.ConversationType.PRIVATE.getValue());
                        getActivity().setResult(Activity.RESULT_OK, intent);
                        getActivity().finish();
                    }
                    return;
                }
                ContactListBean item = (ContactListBean) adapter.getItem(position);
                goChat(view, item.friendId + "", item.friendNickname);
            }
        });

        mViewBinding.refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                presenter.queryFriendList(getContext(), searchCondition);
            }
        });

    }

    private void goChat(View view, String targetId, String nickName) {
        Bundle bundle = new Bundle();
        bundle.putString(RouteUtils.TITLE, nickName);
        RouteUtils.routeToConversationActivity(view.getContext(), Conversation.ConversationType.PRIVATE, targetId, bundle);
    }

    @Override
    protected void initData() {

    }

    @Override
    public void onResume() {
        super.onResume();
        presenter.queryFriendList(getContext(), searchCondition);
    }

    @Override
    public void getFriendListSuccess(List<ContactListBean> contactListBeans) {
        if (isDetached()) {
            return;
        }
        mViewBinding.refreshLayout.finishRefresh();
        if (mListAdapter != null) {
            if (contactListBeans != null && contactListBeans.size() > 0) {
                mDatas = contactListBeans;
                mDecoration.setmDatas(mDatas);
                mViewBinding.livLetters.setmSourceDatas(mDatas)//设置数据
                        .invalidate();
                mListAdapter.setNewInstance(contactListBeans);
            } else {
                mListAdapter.getData().clear();
                mListAdapter.notifyDataSetChanged();
                showEmptyView();
            }
        }
    }

    @Override
    public void getFriendListError() {
        if (isDetached()) {
            return;
        }
        if (mListAdapter != null) {
            mListAdapter.getData().clear();
            mListAdapter.notifyDataSetChanged();
        }
        mViewBinding.refreshLayout.finishRefresh();
    }

    private void showEmptyView() {
        if (mEmptyViewLayout == null) {
            mEmptyViewLayout = new EmptyViewLayout(getContext());
        }
        mEmptyViewLayout.setContent(com.cooleshow.base.R.drawable.icon_empty_content, "暂无联系人");
        mListAdapter.setEmptyView(mEmptyViewLayout);
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.tv_search) {
            String targetSearchStr = mViewBinding.etTargetName.getText().toString().trim();
//            if (TextUtils.isEmpty(targetSearchStr)) {
//                ToastUtil.getInstance().showShort("请输入学员名称");
//                return;
//            }
            searchCondition = targetSearchStr;
            if (presenter != null) {
                presenter.queryFriendList(getContext(), searchCondition);
            }
        }
    }
}
