package io.openim.android.ouicontact.ui.fragment;

import android.content.Intent;
import android.graphics.PointF;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;

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

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;

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

import io.openim.android.ouicontact.R;
import io.openim.android.ouicontact.databinding.FragmentContactMainBinding;
import io.openim.android.ouicontact.ui.AddRelationActivity;
import io.openim.android.ouicontact.ui.GroupNoticeListActivity;
import io.openim.android.ouicontact.ui.MyGroupActivity;
import io.openim.android.ouicontact.ui.NewFriendActivity;
import io.openim.android.ouicontact.ui.adapter.ContactAdapter;
import io.openim.android.ouicontact.vm.ContactVM;
import io.openim.android.ouicore.adapter.RecyclerViewAdapter;
import io.openim.android.ouicore.base.BaseApp;
import io.openim.android.ouicore.base.BaseFragment;
import io.openim.android.ouicore.base.vm.injection.Easy;
import io.openim.android.ouicore.entity.ExUserInfo;
import io.openim.android.ouicore.utils.Common;
import io.openim.android.ouicore.utils.Routes;
import io.openim.android.ouicore.utils.SinkHelper;
import io.openim.android.ouicore.vm.NotificationVM;
import io.openim.android.ouicore.vm.SocialityVM;
import io.openim.android.ouicore.widget.HeaderAndFooterWrapper;
import io.openim.android.ouicore.widget.StickyDecoration;

/**
 * 通讯录
 */
@Route(path = Routes.Contact.HOME)
public class ContactFragment extends BaseFragment<ContactVM> {
    private FragmentContactMainBinding view;
    private NotificationVM notificationVM;
    private SocialityVM socialityVM;
    private RecyclerViewAdapter<ExUserInfo, RecyclerView.ViewHolder> adapter;
    private LinearLayoutManager mLayoutManager;
    private TextView newFriendNoticeBadge, groupNoticeBadge;
    private String mLetters = "↑ABCDEFGHIJKLMNOPQRSTUVWXYZ#";//默认字符
    private HeaderAndFooterWrapper headerAndFooterWrapper;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        bindVM(ContactVM.class);
        notificationVM = Easy.find(NotificationVM.class);
        socialityVM = Easy.installVM(SocialityVM.class);
        BaseApp.inst().putVM(socialityVM);
        super.onCreate(savedInstanceState);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        view = FragmentContactMainBinding.inflate(getLayoutInflater());
        FrameLayout.LayoutParams lp = (FrameLayout.LayoutParams) view.title.getLayoutParams();
        lp.setMargins(0, SinkHelper.getStatusBarHeight(), 0, 0);
        view.title.setLayoutParams(lp);
        listener();
        initView();
//        socialityVM.getAllFriend();
        return view.getRoot();
    }

    @Override
    public void onResume() {
        super.onResume();
        socialityVM.getAllFriend();
    }

    public ContactVM getVM() {
        return vm;
    }


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

    private void initView() {
        view.addFriend.setOnClickListener(view1 -> startActivity(new Intent(getActivity(), AddRelationActivity.class)));
        view.search.setOnClickListener(view1 -> {
            ARouter.getInstance().build(Routes.Conversation.SEARCH).navigation();
        });
        adapter = new ContactAdapter(getContext());
        headerAndFooterWrapper = new HeaderAndFooterWrapper(adapter);
        headerAndFooterWrapper.addHeaderView(topLayout());
        view.recyclerView.setLayoutManager(mLayoutManager = new LinearLayoutManager(getContext()) {
            @Override
            public void smoothScrollToPosition(RecyclerView recyclerView,
                                               RecyclerView.State state, int position) {
                LinearSmoothScroller linearSmoothScroller =
                        new LinearSmoothScroller(recyclerView.getContext()) {
                            @Override
                            protected int calculateTimeForScrolling(int dx) {
                                // 此函数计算滚动dx的距离需要多久，当要滚动的距离很大时，比如说52000，
                                // 经测试，系统会多次调用此函数，每10000距离调一次，所以总的滚动时间
                                // 是多次调用此函数返回的时间的和，所以修改每次调用该函数时返回的时间的
                                // 大小就可以影响滚动需要的总时间，可以直接修改些函数的返回值，也可以修改
                                // dx的值，这里暂定使用后者.
                                // (See LinearSmoothScroller.TARGET_SEEK_SCROLL_DISTANCE_PX)
                                if (dx > 1500) {
                                    dx = 1500;
                                }
                                return super.calculateTimeForScrolling(dx);
                            }

                            @Override
                            public PointF computeScrollVectorForPosition(int targetPosition) {
                                return mLayoutManager.computeScrollVectorForPosition(targetPosition);
                            }
                        };
                linearSmoothScroller.setTargetPosition(position);
                startSmoothScroll(linearSmoothScroller);
            }
        });
        view.recyclerView.setAdapter(headerAndFooterWrapper);
        view.recyclerView.addItemDecoration(new StickyDecoration(getContext(), position -> {
            if (position < headerAndFooterWrapper.getHeadersCount()) {
                return "";
            }
            int pos = position - headerAndFooterWrapper.getHeadersCount();
            String str = adapter.getItems().isEmpty() ? "" : adapter.getItems().get(pos).sortLetter;
            return str;
        }));
        notificationVM.groupDot.observe(getActivity(), v -> {
            groupNoticeBadge.setVisibility(v.size() == 0 ? View.GONE : View.VISIBLE);
            groupNoticeBadge.setText(v.size() + "");
        });
        notificationVM.friendDot.observe(getActivity(), v -> {
            newFriendNoticeBadge.setVisibility(v.size() == 0 ? View.GONE : View.VISIBLE);
            newFriendNoticeBadge.setText(v.size() + "");
        });
    }

    private View topLayout() {
        View top = LayoutInflater.from(getContext()).inflate(R.layout.view_contact_header, null);
        LinearLayout newFriendNotice = top.findViewById(R.id.newFriendNotice);
        newFriendNotice.setOnClickListener(view -> {
            notificationVM.clearDot(notificationVM.friendDot);
            startActivity(new Intent(getActivity(), NewFriendActivity.class));
        });
        newFriendNoticeBadge = top.findViewById(R.id.newFriendNoticeBadge);

        LinearLayout groupNotice = top.findViewById(R.id.groupNotice);
        groupNoticeBadge = top.findViewById(R.id.groupNoticeBadge);
        groupNotice.setOnClickListener(v -> {
            notificationVM.clearDot(notificationVM.groupDot);
            startActivity(new Intent(getActivity(), GroupNoticeListActivity.class));
        });
        LinearLayout myGroup = top.findViewById(R.id.myGroup);
        myGroup.setOnClickListener(v -> {
            startActivity(new Intent(getActivity(), MyGroupActivity.class));
        });
        return top;
    }

    private void listener() {
        view.sortView.setLetters(mLetters);
        socialityVM.exUserInfo.observe(getViewLifecycleOwner(), v -> {
//            if (null == v || v.isEmpty()) {
//                adapter.setItems(new ArrayList<>());
//                return;
//            }
            List<ExUserInfo> exUserInfos = new ArrayList<>(v);
            adapter.setItems(exUserInfos);
            headerAndFooterWrapper.notifyDataSetChanged();
        });

        view.sortView.setOnLetterChangedListener((letter, position) -> {
            if (letter.equals("↑")) {
                Common.smoothMoveToPosition(view.recyclerView, 0);
                return;
            }
            for (int i = 0; i < adapter.getItems().size(); i++) {
                ExUserInfo exUserInfo = adapter.getItems().get(i);
                if (exUserInfo.sortLetter.equalsIgnoreCase(letter)) {
                    Common.smoothMoveToPosition(view.recyclerView, i);
                    return;
                }
            }
        });

        view.recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (Common.mShouldScroll && RecyclerView.SCROLL_STATE_IDLE == newState) {
                    Common.mShouldScroll = false;
                    Common.smoothMoveToPosition(view.recyclerView, Common.mToPosition);
                }
            }
        });
    }

}
