package io.rong.imkit.conversation;

import android.annotation.SuppressLint;
import android.app.Application;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.GestureDetector;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.cooleshow.base.utils.LogUtils;
import com.cooleshow.base.utils.SizeUtils;
import com.cooleshow.usercenter.helper.UserHelper;

import org.jetbrains.annotations.NotNull;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.lifecycle.Observer;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;


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

import io.rong.imkit.R;
import io.rong.imkit.RongIM;
import io.rong.imkit.model.UiMessage;
import io.rong.imkit.widget.NoticyMsaPop;
import io.rong.imkit.widget.adapter.BaseAdapter;
import io.rong.imkit.widget.adapter.ViewHolder;
import io.rong.imkit.widget.refresh.wrapper.RongRefreshHeader;
import io.rong.imlib.RongIMClient;
import io.rong.imlib.model.Message;

/**
 * @author lvz
 * 真正的聊天显示界面
 */
public class ConversationFragmentSEC extends ConversationFragment {


    private static final int UPDATE_TIME_ID = 1009;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(@NonNull android.os.Message msg) {
            if (msg.what == UPDATE_TIME_ID) {
                String update_anncontext = msg.getData().getString("UPDATE_ANNCONTEXT");
                String messid = msg.getData().getString("UPDATE_ANNCONTEXT_MESSID");
                Log.i("ConversationFragmentSEC", "messid == " + messid);
                try {
                    NoticyMsaPop noticyMsaPop = new NoticyMsaPop(getActivity(), messid, update_anncontext);
                    noticyMsaPop.showAtLocation(mRootView, Gravity.TOP, 0, SizeUtils.dp2px(70));
                } catch (Exception e) {

                }


            }
        }
    };
    private String currentMessageUid;
    private ConstraintLayout mRootView;

    /**
     * findId，绑定监听
     */
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
//        super.onCreateView(inflater, container, savedInstanceState);
        View rootView = inflater.inflate(R.layout.rc_conversation_fragment_sec, container, false);
        mList = rootView.findViewById(R.id.rc_message_list);
        mRongExtension = rootView.findViewById(R.id.rc_extension);
        mRootView = rootView.findViewById(R.id.cl_root_view);
        mRefreshLayout = rootView.findViewById(R.id.rc_refresh);
        mNewMessageNum = rootView.findViewById(R.id.rc_new_message_number);

        mUnreadHistoryMessageNum = rootView.findViewById(R.id.rc_unread_message_count);
        mUnreadMentionMessageNum = rootView.findViewById(R.id.rc_mention_message_count);
        mNotificationContainer = rootView.findViewById(R.id.rc_notification_container);
        mNewMessageNum.setOnClickListener(this);
        mUnreadHistoryMessageNum.setOnClickListener(this);
        mUnreadMentionMessageNum.setOnClickListener(this);
        mLinearLayoutManager = new LinearLayoutManager(getContext());
        mLinearLayoutManager.setStackFromEnd(true);
        if (mList != null) {
            mList.setLayoutManager(mLinearLayoutManager);
        }
        mRefreshLayout.setOnTouchListener(new View.OnTouchListener() {
            @SuppressLint("ClickableViewAccessibility")
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                closeExpand();
                return false;
            }
        });
        mAdapter.setItemClickListener(new BaseAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, ViewHolder holder, int position) {
                closeExpand();
            }

            @Override
            public boolean onItemLongClick(View view, ViewHolder holder, int position) {
                return false;
            }
        });


        //关闭动画
        if (mList != null) {
            mList.setAdapter(mAdapter);
            mList.addOnScrollListener(mScrollListener);
            mList.setItemAnimator(null);
            final GestureDetector gd = new GestureDetector(getContext(), new GestureDetector.SimpleOnGestureListener() {
                @Override
                public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
                    closeExpand();
                    return super.onScroll(e1, e2, distanceX, distanceY);

                }
            });
            mList.addOnItemTouchListener(new RecyclerView.OnItemTouchListener() {
                @Override
                public boolean onInterceptTouchEvent(@NonNull RecyclerView rv, @NonNull MotionEvent e) {
                    return gd.onTouchEvent(e);
                }

                @Override
                public void onTouchEvent(@NonNull RecyclerView rv, @NonNull MotionEvent e) {
                    // Do nothing
                }

                @Override
                public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
                    // Do nothing
                }
            });
        }

        mRefreshLayout.setNestedScrollingEnabled(false);
        mRefreshLayout.setRefreshHeader(new RongRefreshHeader(getContext()));
        mRefreshLayout.setRefreshFooter(new RongRefreshHeader(getContext()));
        mRefreshLayout.setEnableRefresh(true);
        mRefreshLayout.setOnRefreshListener(this);
        mRefreshLayout.setOnLoadMoreListener(this);
        return rootView;
    }

    private List<Message> historyMessage = new ArrayList<>();

    @Override
    public void onViewCreated(@NonNull @NotNull View view, @Nullable @org.jetbrains.annotations.Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);


//        RongIMClient.setOnReceiveMessageListener(new RongIMClient.OnReceiveMessageListener() {
//            @Override
//            public boolean onReceived(Message message, int i) {
//                if ("DY:NoticeMsg".equals(message.getObjectName())) {
//                    String context = message.getContent().getExtra();
//                    android.os.Message updateTimeMessage = android.os.Message.obtain();
//                    Bundle bundle = new Bundle();
//                    bundle.putString("UPDATE_ANNCONTEXT", context);
//                    updateTimeMessage.what = UPDATE_TIME_ID;
//                    updateTimeMessage.setData(bundle);
//                    handler.sendMessageDelayed(updateTimeMessage, 1000);
//                }
//                return false;
//            }
//        });

        mMessageViewModel.getUiMessageLiveData().observeForever(mListObserver);


    }

    private void getHistoryPop(final String msgUid) {
        LogUtils.i("ConversationFragmentSEC", "msgUid == " + msgUid);
        RongIMClient.getInstance().getHistoryMessages(mConversationType, mTargetId, -1, 10,
                new RongIMClient.ResultCallback<List<Message>>() {
                    /**
                     * 成功时回调
                     * @param messages 获取的消息列表
                     */
                    @Override
                    public void onSuccess(List<Message> messages) {
                        final String uid = msgUid;
                        if (messages != null) {
                            if (historyMessage == null) {
                                historyMessage = new ArrayList<>();
                            }
                            historyMessage.clear();
                            for (int i = 0; i < messages.size(); i++) {
                                if ("DY:NoticeMsg".equals(messages.get(i).getObjectName())) {
                                    historyMessage.add(messages.get(i));
                                }
                            }
                            if (historyMessage.size() > 0) {
                                new Thread(new Runnable() {
                                    @Override
                                    public void run() {
                                        for (int p = 0; p < historyMessage.size(); p++) {
                                            if (uid.equals(historyMessage.get(p).getUId())) {
                                                if (historyMessage.get(p).getExpansion() != null) {
                                                    String localUserid= UserHelper.getUserId();
                                                    if (!historyMessage.get(p).getExpansion().containsKey(localUserid)) {
                                                        String extra = historyMessage.get(p).getContent().getExtra();
                                                        String msgUid = historyMessage.get(p).getUId();
                                                        android.os.Message historyMessage = android.os.Message.obtain();
                                                        Bundle bundle = new Bundle();
                                                        bundle.putString("UPDATE_ANNCONTEXT", extra);
                                                        bundle.putString("UPDATE_ANNCONTEXT_MESSID", msgUid);
                                                        historyMessage.what = UPDATE_TIME_ID;
                                                        historyMessage.setData(bundle);
                                                        handler.sendMessageDelayed(historyMessage, 100);
                                                    }
                                                } else {
                                                    String extra = historyMessage.get(p).getContent().getExtra();
                                                    String msgUID = historyMessage.get(p).getUId();
                                                    android.os.Message historyMessage = android.os.Message.obtain();
                                                    Bundle bundle = new Bundle();
                                                    bundle.putString("UPDATE_ANNCONTEXT", extra);
                                                    bundle.putString("UPDATE_ANNCONTEXT_MESSID", msgUID);
                                                    historyMessage.what = UPDATE_TIME_ID;
                                                    historyMessage.setData(bundle);
                                                    handler.sendMessageDelayed(historyMessage, 100);
                                                }
                                            }
                                        }
                                    }
                                }).start();
                            }

                        }
                    }

                    /**
                     * 错误时回调。
                     * @param e 错误码
                     */
                    @Override
                    public void onError(RongIMClient.ErrorCode e) {

                    }
                });
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (handler != null) {
            handler.removeMessages(UPDATE_TIME_ID);
        }
        if (mMessageViewModel != null) {
            mMessageViewModel.getUiMessageLiveData().removeObserver(mListObserver);
        }
    }

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

    }

    Observer<List<UiMessage>> mListObserver = new Observer<List<UiMessage>>() {
        @Override
        public void onChanged(List<UiMessage> uiMessages) {
            LogUtils.i("ConversationFragmentSEC", "uiMessages == " + uiMessages.toString());
            for (int i = 0; i < uiMessages.size(); i++) {
                if ("DY:NoticeMsg".equals(uiMessages.get(i).getObjectName())) {
                    if (uiMessages.get(i).getExpansion() != null) {
                        String localUserid= UserHelper.getUserId();
                        if (!uiMessages.get(i).getExpansion().containsKey(localUserid)) {

                            String context = uiMessages.get(i).getMessage().getContent().getExtra();
                            String msgUID = uiMessages.get(i).getMessage().getUId();
                            android.os.Message updateTimeMessage = android.os.Message.obtain();
                            Bundle bundle = new Bundle();
                            bundle.putString("UPDATE_ANNCONTEXT", context);
                            bundle.putString("UPDATE_ANNCONTEXT_MESSID", msgUID);
                            updateTimeMessage.what = UPDATE_TIME_ID;
                            updateTimeMessage.setData(bundle);
                            handler.sendMessageDelayed(updateTimeMessage, 100);
                        }
                    } else {
                        String context = uiMessages.get(i).getMessage().getContent().getExtra();
                        String msgUID = uiMessages.get(i).getMessage().getUId();
                        getHistoryPop(msgUID);
//                        android.os.Message updateTimeMessage = android.os.Message.obtain();
//                        Bundle bundle = new Bundle();
//                        bundle.putString("UPDATE_ANNCONTEXT", context);
//                        bundle.putString("UPDATE_ANNCONTEXT_MESSID", msgUID);
//                        updateTimeMessage.what = UPDATE_TIME_ID;
//                        updateTimeMessage.setData(bundle);
//                        handler.sendMessageDelayed(updateTimeMessage, 100);
                    }

                } else {

                }
            }

        }
    };
}