package com.common.im.ui;

import android.content.Context;
import android.graphics.Typeface;
import android.net.Uri;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;

import com.alibaba.android.arouter.launcher.ARouter;
import com.common.im.adapter.MessagePagerAdapter;
import com.common.im.contract.MessageFragmentContract;
import io.rong.imkit.utils.helper.ConversationFilterHelper;
import com.common.im.presenter.MessagePresenter;
import com.common.im.ui.contact.ContactListTabFragment;
import com.common.im_ui.R;
import com.common.im_ui.databinding.FragmentMessageLayoutBinding;
import com.common.im.bean.RongIMGroupInfo;
import com.common.im.bean.RongIMUserInfo;
import com.cooleshow.base.common.BaseApplication;
import com.cooleshow.base.router.RouterPath;
import com.cooleshow.base.utils.LogUtils;
import com.cooleshow.base.utils.Utils;
import com.cooleshow.base.ui.fragment.BaseMVPFragment;
import com.cooleshow.usercenter.helper.UserHelper;
import com.google.android.material.tabs.TabLayout;
import com.google.android.material.tabs.TabLayoutMediator;

import java.util.ArrayList;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;

import io.rong.imkit.RongIM;
import io.rong.imkit.config.ConversationListBehaviorListener;
import io.rong.imkit.conversationlist.ConversationListFragment;
import io.rong.imkit.conversationlist.model.BaseUiConversation;
import io.rong.imkit.userinfo.UserDataProvider;
import io.rong.imlib.model.Conversation;
import io.rong.imlib.model.Group;
import io.rong.imlib.model.UserInfo;

/**
 * Author by pq, Date on 2022/5/6.
 */
public class MessageFragment extends BaseMVPFragment<FragmentMessageLayoutBinding, MessagePresenter> implements MessageFragmentContract.MessageFragmentView, View.OnClickListener {
    public static final String[] titles = new String[]{"聊天", "联系人"};
    private ArrayList<Fragment> fragments = new ArrayList<>();
    String localUserid = "";

    @Override
    protected void initView(View rootView) {
        Utils.setHeadView(mViewBinding.viewStatusBar, requireContext(), 0);
        if (!BaseApplication.Companion.isTeacherClient()) {
            mViewBinding.imCreateGroup.setVisibility(View.GONE);
        }else{
            mViewBinding.imCreateGroup.setVisibility(View.VISIBLE);
            mViewBinding.imCreateGroup.setOnClickListener(this);
        }
        localUserid = UserHelper.getUserId();
        TabLayoutMediator tabLayoutMediator = new TabLayoutMediator(mViewBinding.tabLayout, mViewBinding.viewPager, new TabLayoutMediator.TabConfigurationStrategy() {
            @Override
            public void onConfigureTab(@NonNull TabLayout.Tab tab, int position) {
                createTab(tab, titles[position]);
            }
        });
        mViewBinding.tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                if (tab != null && tab.getCustomView() != null) {
                    View customView = tab.getCustomView();
                    TextView tv_text = customView.findViewById(R.id.tv_text);
                    tv_text.setTextColor(getResources().getColor(com.cooleshow.base.R.color.color_333333));
                    tv_text.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
                }
                if(tab != null && tab.getPosition() == 1){
                    ContactListTabFragment fragment = (ContactListTabFragment) fragments.get(tab.getPosition());
                    if(fragment!=null){
                        fragment.refreshContactList();
                    }
                }
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
                if (tab != null && tab.getCustomView() != null) {
                    View customView = tab.getCustomView();
                    TextView tv_text = customView.findViewById(R.id.tv_text);
                    tv_text.setTextColor(getResources().getColor(com.cooleshow.base.R.color.color_666666));
                    tv_text.setTypeface(Typeface.defaultFromStyle(Typeface.NORMAL));
                }
            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {
            }
        });
        RongIM.setUserInfoProvider(new UserDataProvider.UserInfoProvider() {
            @Override
            public UserInfo getUserInfo(String userId) {
                if (!TextUtils.isEmpty(localUserid) && localUserid.equals(userId)) {
                    RongIMUserInfo data = new RongIMUserInfo();
                    data.setFriendId(userId+"");
                    data.setFriendNickname(UserHelper.getUserName());
                    data.setFriendAvatar(UserHelper.getUserAvatar());
                    onQueryFriendDetail(data);
                } else {
                    if (presenter != null) {
                        presenter.queryFriendDetail(getContext(),userId);
                    }

                }
                return null;
            }

        }, true);

        RongIM.setGroupInfoProvider(new UserDataProvider.GroupInfoProvider() {
            @Override
            public Group getGroupInfo(String groupId) {
                if (!ConversationFilterHelper.checkConversationEnable(groupId)) {
                    return null;
                }
                if (presenter != null) {
                    presenter.queryGroupDetail(getContext(),groupId);
                }

                return null;
            }
        }, true);
        RongIM.setConversationListBehaviorListener(new ConversationListBehaviorListener() {
            public boolean onConversationPortraitClick(Context context, Conversation.ConversationType
                    conversationType, String targetId) {
                return false;
            }
            public boolean onConversationPortraitLongClick(Context context, Conversation.ConversationType conversationType, String targetId) {
                return false;
            }
            @Override
            public boolean onConversationLongClick(Context context, View view, BaseUiConversation conversation) {
                return false;
            }

            @Override
            public boolean onConversationClick(Context context, View view, BaseUiConversation conversation) {
                if (null != presenter && TextUtils.isEmpty(conversation.mCore.getConversationTitle())) {
                    if (conversation.mCore.getConversationType() == Conversation.ConversationType.GROUP) {
                        presenter.queryGroupDetail(getContext(),conversation.mCore.getTargetId());
                    } else {
                        String userId = conversation.mCore.getTargetId();
                        if (localUserid.equals(userId)) {
                            RongIMUserInfo data = new RongIMUserInfo();
                            data.setFriendId(userId);
                            data.setFriendNickname(UserHelper.getUserName());
                            data.setFriendAvatar(UserHelper.getUserAvatar());
                            onQueryFriendDetail(data);
                        } else {
                            presenter.queryFriendDetail(getContext(),userId);

                        }
                    }
                }
                return false;
            }
        });

        ConversationListFragment conversationListFragment = new ConversationListFragment();
//        ContactPersonListFragment contactPersonListFragment = new ContactPersonListFragment();
        ContactListTabFragment contactListTabFragment=new ContactListTabFragment();

        fragments.add(conversationListFragment);
        fragments.add(contactListTabFragment);
        MessagePagerAdapter messagePagerAdapter = new MessagePagerAdapter(this);
        messagePagerAdapter.setData(fragments);
        mViewBinding.viewPager.setAdapter(messagePagerAdapter);
        tabLayoutMediator.attach();
    }

    @Override
    public void onQueryFriendDetail(RongIMUserInfo data) {
        if (data != null) {
            RongIM.getInstance().refreshUserInfoCache(new UserInfo(data.getFriendId() + "", data.getFriendNickname(), Uri.parse(data.getFriendAvatar())));

        }
    }

    @Override
    public void onQueryGroupDetail(RongIMGroupInfo data) {

    }

    private TabLayout.Tab createTab(TabLayout.Tab tab, String text) {
        View view = LayoutInflater.from(getContext()).inflate(R.layout.view_message_tab_layout, null);
        TextView tv_text = view.findViewById(R.id.tv_text);
        tv_text.setText(text);
        tab.setCustomView(view);
        return tab;
    }

    @Override
    protected void initData() {

    }

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

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

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.im_create_group) {
            ARouter.getInstance().build(RouterPath.ChatCenter.CHAT_CREATE_GROUP)
                    .navigation();
        }
    }
}
