package com.yidianling.uikit.business.session.fragment;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Color;
import android.media.AudioManager;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.constraintlayout.widget.Group;
import androidx.recyclerview.widget.RecyclerView;

import com.google.gson.Gson;
import com.netease.nimlib.sdk.NIMClient;
import com.netease.nimlib.sdk.Observer;
import com.netease.nimlib.sdk.RequestCallback;
import com.netease.nimlib.sdk.ResponseCode;
import com.netease.nimlib.sdk.msg.MessageBuilder;
import com.netease.nimlib.sdk.msg.MsgService;
import com.netease.nimlib.sdk.msg.MsgServiceObserve;
import com.netease.nimlib.sdk.msg.constant.MsgStatusEnum;
import com.netease.nimlib.sdk.msg.constant.SessionTypeEnum;
import com.netease.nimlib.sdk.msg.model.CustomMessageConfig;
import com.netease.nimlib.sdk.msg.model.IMMessage;
import com.netease.nimlib.sdk.msg.model.MemberPushOption;
import com.netease.nimlib.sdk.msg.model.MessageReceipt;
import com.ydl.ydlcommon.data.http.RxUtils;
import com.ydl.ydlcommon.modular.ModularServiceManager;
import com.ydl.ydlcommon.utils.LogUtil;
import com.ydl.ydlcommon.utils.SharedPreferencesEditor;
import com.ydl.ydlcommon.utils.log.AliYunLogConfig;
import com.ydl.ydlcommon.utils.log.AliYunRichLogsHelper;
import com.ydl.ydlcommon.utils.log.LogHelper;
import com.ydl.ydlcommon.view.dialog.CommonDialog;
import com.yidianling.common.tools.ToastUtil;
import com.yidianling.im.R;
import com.yidianling.im.event.MultipleAnswerBean;
import com.yidianling.im.event.MultipleSelectedEvent;
import com.yidianling.im.helper.IMChatUtil;
import com.yidianling.im.http.ImRetrofitApi;
import com.yidianling.im.router.ImIn;
import com.yidianling.im.session.viewholder.bean.AnswerBean;
import com.yidianling.im.session.viewholder.bean.AnswersItem;
import com.yidianling.im.session.viewholder.bean.LingxiAnswerBean;
import com.yidianling.nimbase.api.UIKitOptions;
import com.yidianling.nimbase.api.model.main.CustomPushContentProvider;
import com.yidianling.nimbase.api.model.session.ModuleProxy;
import com.yidianling.nimbase.api.model.session.SessionCustomization;
import com.yidianling.nimbase.business.preference.UserPreferences;
import com.yidianling.nimbase.business.session.actions.BaseAction;
import com.yidianling.nimbase.business.session.constant.Extras;
import com.yidianling.nimbase.business.session.module.Container;
import com.yidianling.nimbase.common.CommonUtil;
import com.yidianling.nimbase.common.fragment.TFragment;
import com.yidianling.uikit.api.NimUIKitImpl;
import com.yidianling.uikit.business.ait.AitManager;
import com.yidianling.uikit.business.session.activity.YDLBaseMessageActivity;
import com.yidianling.uikit.business.session.helper.ChatStatusCacheHelper;
import com.yidianling.uikit.business.session.module.input.InputPanel;
import com.yidianling.uikit.business.session.module.list.MessageListPanelEx;
import com.yidianling.uikit.custom.bridge.ActionHandlerStorage;
import com.yidianling.uikit.custom.bridge.IP2PCustomActionHandler;
import com.yidianling.uikit.custom.http.ServiceImpl;
import com.yidianling.uikit.custom.http.response.NewUserMesBean;
import com.yidianling.uikit.custom.http.response.UserQuestInfoBean;
import com.yidianling.uikit.custom.widget.TitleBarBottom;
import com.yidianling.uikit.custom.widget.UserInfoDialog;
import com.yidianling.user.api.service.IUserService;

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

import de.greenrobot.event.EventBus;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import okhttp3.MediaType;
import okhttp3.RequestBody;


/**
 * 聊天界面基类
 * <p/>
 * Created by huangjun on 2015/2/1.
 */
public class YDLMessageFragment extends TFragment implements ModuleProxy {
    //用户
    private static int USER_TYPE_USER = 1;
    //专家
    private static int USER_TYPE_EXPERT = 2;
    //助理
    private static int USER_TYPE_ASSISTANT = 3;

    private View rootView;

    private SessionCustomization customization;

    protected static final String TAG = "MessageActivity";

    // 聊天对象
    protected String sessionId; // p2p对方Account或者群id或聊天室id

    protected SessionTypeEnum sessionType;


    private LinearLayout ll_actions_yi;

    // modules
    protected InputPanel inputPanel;
    private int rvPaddingTop;
    private boolean initHeightFinish;

    public InputPanel getInputPanel() {
        return inputPanel;
    }

    protected MessageListPanelEx messageListPanel;

    private boolean isFirst = true;

    public MessageListPanelEx getMessageListPanelEx() {
        return messageListPanel;
    }

    private int timeCount = 0;

    protected AitManager aitManager;

    private ConstraintLayout top_expert_info_ll;
    //待接诊文案
    private TextView tv_receive_unstart;
    //待诊断
    private TextView tv_receive_undiagnosis;
    //待诊断 倒计时
    private TextView time_count_down;
    private CountDownTimer timer;

    //诊断结束
    private TextView tv_receive_end;
    private int expertInfoViewHeight = 0; // 专家信息栏高度
    private RecyclerView messageListView;

    private RelativeLayout constraint_ll;
    private Group receive_unstart, receive_undiagnosis, receive_end;

    private int userInfoDialogAge = 0;
    private String userInfoDialogSex = "";
    private String userInfoDialogConsultType = "";
    private String userInfoDialogQuestionDes = "";
    private String userInfoDialogSourceFrom = "";

    private UserInfoDialog userInfoDialog = null;
    private MultipleAnswerBean multipleAnswerBean;
    private ArrayList<String> answersItemsMap = new ArrayList<>();


    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        parseIntent();
        TitleBarBottom titleBar = ((YDLBaseMessageActivity) getActivity()).getTitleBarBottom();
        titleBar.setTitleLeftDraw(getResources().getDrawable(R.drawable.loading_01));
        titleBar.setTitle("正在连接中...");
        ll_actions_yi = rootView.findViewById(R.id.ll_actions_yi);
        //顶部问诊状态  客服icon
        top_expert_info_ll = rootView.findViewById(R.id.top_expert_info_ll);
        tv_receive_unstart = rootView.findViewById(R.id.tv_receive_unstart);
        tv_receive_undiagnosis = rootView.findViewById(R.id.tv_receive_undiagnosis);
        tv_receive_end = rootView.findViewById(R.id.tv_receive_end);
        // 消息列表
        messageListView = rootView.findViewById(R.id.messageListView);
        constraint_ll = rootView.findViewById(R.id.constraint_ll);
        //待接诊
        receive_unstart = rootView.findViewById(R.id.receive_unstart);
        //待诊断
        receive_undiagnosis = rootView.findViewById(R.id.receive_undiagnosis);

        //问诊中 倒计时
        time_count_down = rootView.findViewById(R.id.time_count_down);
        //诊断结束
        receive_end = rootView.findViewById(R.id.receive_end);
        messageListView.setItemAnimator(null);

        if (ActionHandlerStorage.getL(sessionId).isNotPrepare()) {
            IMChatUtil.INSTANCE.prepareChatData((AppCompatActivity) getActivity(), sessionId, (expertInfo) -> {
                String toUid = expertInfo.shareData.toUid;
                IP2PCustomActionHandler handler = ActionHandlerStorage.getL(sessionId);
                handler.setExpertInfo(toUid, expertInfo);
                handler.setUserType(expertInfo.shareData.user_type);
                initView();
            });
            if (!UserPreferences.isEarPhoneModeEnable()) {
                titleBar.setTitleLeftDraw(null);
            } else {
                titleBar.setTitleRightDraw(getResources().getDrawable(R.drawable.im_erduoxiaolv));
            }
            titleBar.setTitle(ActionHandlerStorage.getL(sessionId).getInfo().name);
        } else {
            initView();
        }
    }

    private void initView() {
        if (ActionHandlerStorage.getL(sessionId) != null && ActionHandlerStorage.getL(sessionId).getUserType() == USER_TYPE_ASSISTANT) {
            if (ChatStatusCacheHelper.getStatusCache("chatEvent")) {
                ChatStatusCacheHelper.clearDataByKey("chatEvent");
            }
        }

        TitleBarBottom titleBar = ((YDLBaseMessageActivity) getActivity()).getTitleBarBottom();
        if (!UserPreferences.isEarPhoneModeEnable()) {
            titleBar.setTitleLeftDraw(null);
        } else {
            titleBar.setTitleRightDraw(getResources().getDrawable(R.drawable.im_erduoxiaolv));
        }
        titleBar.setTitle(ActionHandlerStorage.getL(sessionId).getInfo().name);
        // 初始化顶部专家信息栏
        if (ActionHandlerStorage.getL(sessionId) != null && ActionHandlerStorage.getL(sessionId).getUserType() == USER_TYPE_EXPERT) {
            initTopViewHeight(); //设置顶部专家信息栏高度
            IMChatUtil.INSTANCE.initChatOnlineState(titleBar, getContext(), sessionId, this);
        }

        if (ActionHandlerStorage.getL(sessionId) != null) {
            int type = ActionHandlerStorage.getL(sessionId).getUserType();
            int sType = ActionHandlerStorage.getL(sessionId).getSelfUserType();
            if (type == USER_TYPE_EXPERT && sType == USER_TYPE_USER) {
                ll_actions_yi.setVisibility(View.GONE);
            } else if (type == -1 && sType == USER_TYPE_USER) {
                ll_actions_yi.setVisibility(View.VISIBLE);
                initYiMenu();
            } else {
                ll_actions_yi.setVisibility(View.GONE);
            }

        }


        // 监听消息发送状态的变化通知
        NIMClient.getService(MsgServiceObserve.class).observeMsgStatus(
                (Observer<IMMessage>) imMessage -> {
                    // 参数为有状态发生改变的消息对象，其 msgStatus 和 attachStatus 均为最新状态。
                    // 发送消息和接收消息的状态监听均可以通过此接口完成。
                    Log.e("hzs", "接收到消息状态变化-------MessageFragment");
                }, true);

        //判断是否需要发送自定义消息
        if (isFirst && ActionHandlerStorage.getL(sessionId) != null) {
            isFirst = false;
            ActionHandlerStorage.getL(sessionId).isNeedSendMsg(true);
        }

        //初始化私聊页面配置
        initDefaultConfig();
    }

    @SuppressLint("CheckResult")
    private void initDefaultConfig() {
        ServiceImpl.Companion.getInstance().getChatViewConfig()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(res -> {
                    if ("200".equals(res.code) && res.data != null && !TextUtils.isEmpty(res.data.getInputBoxReminder())) {
                        if (getInputPanel().getInputContent() == null || getInputPanel().getInputContent().equals("")) {
                            getInputPanel().setInputHintContent(res.data.getInputBoxReminder());
                        }
                    }

                }, throwable -> {
                });

        String targetUid = "";
        if (ModularServiceManager.INSTANCE.provide(IUserService.class).getUserInfo().getUser_type() == USER_TYPE_USER) {
            //自己是用戶,搜索的是自己的信息
            targetUid = ModularServiceManager.INSTANCE.provide(IUserService.class).getUserInfo().getUid();
        } else if (ModularServiceManager.INSTANCE.provide(IUserService.class).getUserInfo().getUser_type() == USER_TYPE_ASSISTANT) {
            // 自己是助理，搜索的是对方（用户）的信息
            if (ActionHandlerStorage.getL(sessionId) != null) {
                targetUid = ActionHandlerStorage.getL(sessionId).getInfo().toUid;
            }
        }
        ServiceImpl.Companion.getInstance().getNewUserMes(new NewUserMesBean(targetUid))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(hasCollectedInResp -> {

                    if (hasCollectedInResp.data != null && hasCollectedInResp.data.size() > 0) {
                        if (ActionHandlerStorage.getL(sessionId) != null && ModularServiceManager.INSTANCE.provide(IUserService.class).getUserInfo().getUser_type() == USER_TYPE_USER) {
                            if (TextUtils.isEmpty(SharedPreferencesEditor.getString("chat_age_ensure_" + ImIn.INSTANCE.getUserInfo().getUid()))) {
                                for (UserQuestInfoBean bean : hasCollectedInResp.data) {
                                    if (TextUtils.equals(bean.getUserInfoType(), "age")) {
                                        try {
                                            String year = bean.getContent();
                                            if ((Calendar.getInstance().get(Calendar.YEAR) - Integer.valueOf(year)) <= 16) {
                                                if (!getActivity().isFinishing()) {
                                                    showCheckAgeDialog();
                                                }
                                            }
                                        } catch (Exception e) {
                                            e.printStackTrace();
                                        }
                                    }
                                }
                            }
                        }

                        // 如果对方是用户，自己是助理，则展示标题文本右侧icon，并设置点击事件，展示用户信息弹窗
                        if (ActionHandlerStorage.getL(sessionId).getUserType() == USER_TYPE_USER && ModularServiceManager.INSTANCE.provide(IUserService.class).getUserInfo().getUser_type() == USER_TYPE_ASSISTANT) {
                            if (null == userInfoDialog) {

                                for (UserQuestInfoBean bean : hasCollectedInResp.data) {
                                    if (TextUtils.equals(bean.getUserInfoType(), "age")) {
                                        try {
                                            String year = bean.getContent();
                                            userInfoDialogAge = Calendar.getInstance().get(Calendar.YEAR) - Integer.valueOf(year);
                                        } catch (Exception e) {
                                        }
                                    } else if (TextUtils.equals(bean.getUserInfoType(), "gener")) {
                                        try {
                                            userInfoDialogSex = bean.getContent();
                                        } catch (Exception e) {
                                        }
                                    } else if (TextUtils.equals(bean.getUserInfoType(), "questionType")) {
                                        try {
                                            userInfoDialogConsultType = bean.getContent();
                                        } catch (Exception e) {
                                        }
                                    } else if (TextUtils.equals(bean.getUserInfoType(), "questionContent")) {
                                        try {
                                            userInfoDialogQuestionDes = bean.getContent();
                                        } catch (Exception e) {
                                        }
                                    }
                                }
                                getSourceFrom();
                            }
                        }
                    }
                }, throwable -> {
                    Log.i("user/getNewUserMes", throwable.toString());
                });
        EventBus.getDefault().register(this);
    }

    @SuppressLint("CheckResult")
    private void getSourceFrom() {
        //获取私聊对象的uid，调用接口获取来源
        String targetUid = ActionHandlerStorage.getL(sessionId).getInfo().toUid;
        ServiceImpl.Companion.getInstance().getUserSourceFrom(targetUid)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(res -> {
                    if (!TextUtils.isEmpty(res.data)) {
                        userInfoDialogSourceFrom = res.data;
                    }
                });
    }

    public void showUserInfoDialog() {
        if (userInfoDialog != null) {
            userInfoDialog.dismiss();
        }
        userInfoDialog = new UserInfoDialog(getActivity(), userInfoDialogSourceFrom, String.valueOf(userInfoDialogAge), userInfoDialogSex, userInfoDialogConsultType, userInfoDialogQuestionDes);
        userInfoDialog.show();
    }

    private void initTopViewHeight() {

        top_expert_info_ll.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                expertInfoViewHeight = top_expert_info_ll.getHeight();
                if (messageListPanel.linearLayoutManager.findLastVisibleItemPosition() == 0) {
                    initHeightFinish = true;
                    //如果页面未充满时，设置padding会出现覆盖问题，必须设置margin才可以
                    messageListView.setPadding(0, rvPaddingTop, 0, 0);
                    RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) messageListView.getLayoutParams();
                    layoutParams.topMargin = expertInfoViewHeight;
                    messageListView.setLayoutParams(layoutParams);
                } else {
                    if (initHeightFinish) {
                        rvPaddingTop += expertInfoViewHeight;
                        messageListView.setPadding(0, rvPaddingTop, 0, 0);
                    } else {
                        rvPaddingTop += expertInfoViewHeight;
                    }
                }
                initHeightFinish = true;
                top_expert_info_ll.getViewTreeObserver().removeOnGlobalLayoutListener(this);
            }
        });
    }

    private void initYiViewTopHeight() {
        ll_actions_yi.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                int rvPaddingTop = ll_actions_yi.getHeight();
                messageListView.setPadding(0, rvPaddingTop, 0, 0);
            }
        });
    }


    private void initYiMenu() {
        initYiViewTopHeight();

        rootView.findViewById(R.id.action_help).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                LogHelper.Companion.getInstance().writeLogSync("聊天界面点击常见问题");
                if (null != ActionHandlerStorage.getL(sessionId)) {
                    ActionHandlerStorage.getL(sessionId).startHelp(getActivity());
                }
            }
        });
        rootView.findViewById(R.id.action_feedback).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                LogHelper.Companion.getInstance().writeLogSync("聊天界面点击投诉与反馈");
                if (null != ActionHandlerStorage.getL(sessionId)) {
                    ActionHandlerStorage.getL(sessionId).startFeedback(getActivity());
                }
            }
        });
        ;
        rootView.findViewById(R.id.action_call).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                LogHelper.Companion.getInstance().writeLogSync("聊天界面点击免费热线");
                if (null != ActionHandlerStorage.getL(sessionId)) {
                    ActionHandlerStorage.getL(sessionId).popCallDialog(getActivity());
                }
            }
        });
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.im_ydl_nim_message_fragment, container, false);
        return rootView;
    }


    /**
     * ***************************** life cycle *******************************
     */
    @Override
    public void onPause() {
        super.onPause();
        NIMClient.getService(MsgService.class).setChattingAccount(MsgService.MSG_CHATTING_ACCOUNT_NONE, SessionTypeEnum.None);
        inputPanel.onPause();
        messageListPanel.onPause();
    }

    @SuppressLint("SetTextI18n")
    @Override
    public void onResume() {
        super.onResume();
        messageListPanel.onResume();
        NIMClient.getService(MsgService.class).setChattingAccount(sessionId, sessionType);
        getActivity().setVolumeControlStream(AudioManager.STREAM_VOICE_CALL); // 默认使用听筒播放
        messageListPanel.scrollToBottom();
        if (ActionHandlerStorage.getL(sessionId).getUserType() == USER_TYPE_EXPERT) {
            inputPanel.setVisible(false);
        }

        getInquIryIngInfo();
    }

    @SuppressLint("CheckResult")
    private void getInquIryIngInfo() {
        ImRetrofitApi.Companion.getImJavaApi()
                .getInquIryIngInfo(ActionHandlerStorage.getL(sessionId).getInfo().toUid, ImIn.INSTANCE.getUserInfo().getUid())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(response -> {
                            if ("200".equals(response.code)) {
                                upReceiceType(response.data.getStatus(), response.data.getStatusName(), response.data.getSurplusInquiryTime());

                            } else {
                                ToastUtil.toastShort(response.msg);
                                if (ActionHandlerStorage.getL(sessionId).getUserType() == USER_TYPE_EXPERT) {
                                    inputPanel.setVisible(false);
                                }
                            }

                        }, throwable -> {
                            if (ActionHandlerStorage.getL(sessionId).getUserType() == USER_TYPE_EXPERT) {
                                inputPanel.setVisible(false);
                            }
                            LogUtil.e(throwable.getMessage());
                        }
                );
    }


    public void upReceiceType(int type, String statusName, Long time) {
        if (ActionHandlerStorage.getL(sessionId).getUserType() == USER_TYPE_EXPERT) {
            if (type == 30) {
                //  30:待诊断(已接诊、问诊中)
                inputPanel.setVisible(true);
                top_expert_info_ll.setVisibility(View.VISIBLE);
                receive_undiagnosis.setVisibility(View.VISIBLE);
                receive_unstart.setVisibility(View.GONE);
                receive_end.setVisibility(View.GONE);
                if (!TextUtils.isEmpty(statusName)) {
                    tv_receive_undiagnosis.setText(statusName);
                }
                if(timer != null){
                    timer.cancel();
                }else {
                    timer = new CountDownTimer(time * 1000, 1) {
                        @Override
                        public void onTick(long millisUntilFinished) {
                            //单位时
                            long hour = millisUntilFinished / (1000 * 60 * 60);
                            //单位分
                            long minute = (millisUntilFinished - hour * (1000 * 60 * 60)) / (1000 * 60);
                            //单位秒
                            long second = (millisUntilFinished - hour * (1000 * 60 * 60) - minute * (1000 * 60)) / 1000;
                            String timeStr = "";
                            if (hour != 0) {
                                timeStr = hour + "小时" + minute + "分" + second + "秒";
                            } else if (hour == 0 && minute != 0) {
                                timeStr = minute + "分" + second + "秒";
                            }else if (hour == 0 && minute == 0 && second != 0) {
                                timeStr =  second + "秒";
                            }
                            if (!TextUtils.isEmpty(timeStr)){
                                String timeEnd = "后问诊结束";
                                SpannableStringBuilder spannable = new SpannableStringBuilder(timeStr + timeEnd);
                                spannable.setSpan(new ForegroundColorSpan(Color.parseColor("#007AFF")),
                                        0,
                                        timeStr.length(),
                                        Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
                                );

                                time_count_down.setText(spannable);
                            }else {
                                time_count_down.setText("");
                            }
                        }

                        @Override
                        public void onFinish() {

                        }
                    };
                }

                timer.start();

            } else if (type == 20) {
                //待接诊
                inputPanel.setVisible(true);
                top_expert_info_ll.setVisibility(View.VISIBLE);
                receive_undiagnosis.setVisibility(View.GONE);
                receive_unstart.setVisibility(View.VISIBLE);
                receive_end.setVisibility(View.GONE);
                if (!TextUtils.isEmpty(statusName)) {
                    tv_receive_unstart.setText(statusName);
                }
            } else if (type == 40) {
                //已完成
                inputPanel.setVisible(false);
                top_expert_info_ll.setVisibility(View.VISIBLE);
                receive_undiagnosis.setVisibility(View.GONE);
                receive_unstart.setVisibility(View.GONE);
                receive_end.setVisibility(View.VISIBLE);
                if (!TextUtils.isEmpty(statusName)) {
                    tv_receive_end.setText(statusName);
                }
                if (timer != null) {
                    timer.cancel();
                }
            } else {
                top_expert_info_ll.setVisibility(View.GONE);
                inputPanel.setVisible(false);
                if (timer != null) {
                    timer.cancel();
                }
            }
        }
    }

    @Override
    public void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
        messageListPanel.onDestroy();
        registerObservers(false);
        if (inputPanel != null) {
            inputPanel.onDestroy();
        }
        if (aitManager != null) {
            aitManager.reset();
        }
    }

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

    ArrayList<AnswersItem> answersItems = new ArrayList<>();

    public void onEvent(MultipleSelectedEvent event) {
        if (event.getOthersState() != null) {
            answersItems = event.getMultipleAnswerBean().getAnswersItems();
            multipleAnswerBean = event.getMultipleAnswerBean();
            multipleAnswerBean.setAnswersItems(answersItems);
            if (event.getRecoverInput()) {
                inputPanel.onlyShowTextEnd();
                return;
            }
            if (event.getOthersState().isOthers()) {
                //用户点击了其他事件
                if (event.getOthersState().getOthersSelect()) {
                    //其他是选中状态
                    rootView.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            inputPanel.onlyShowTextStart();
                        }
                    }, 500);
                } else {
                    //其他是未选中状态
                    inputPanel.onlyShowTextEnd();
                }

            }
        } else if (event.isFromInputPanel()) {
            for (int i = 0; i < answersItems.size(); i++) {
                if (answersItems.get(i).getName().contains("其他")) {
                    answersItems.get(i).setOther(inputPanel.getInputContent());
                    break;
                }
            }
            multipleAnswerBean.setAnswersItems(answersItems);
            for (int i = 0; i < answersItems.size(); i++) {
                answersItemsMap.add(i, answersItems.get(i).getName());
            }
            updateLocalMsg(null, answersItemsMap);
            answerMultipleQuestion(multipleAnswerBean);
        } else {

            //请求接口发送消息为56的答案
            answersItems = event.getMultipleAnswerBean().getAnswersItems();
            for (int i = 0; i < answersItems.size(); i++) {
                if (answersItems.get(i).getName().contains("其他")) {
                    answersItems.get(i).setOther(inputPanel.getInputContent());
                    break;
                }
            }
            multipleAnswerBean = event.getMultipleAnswerBean();
            multipleAnswerBean.setAnswersItems(answersItems);
            for (int i = 0; i < answersItems.size(); i++) {
                answersItemsMap.add(i, answersItems.get(i).getName());
            }
            updateLocalMsg(null, answersItemsMap);
            answerMultipleQuestion(multipleAnswerBean);
        }
    }

    private void updateLocalMsg(Integer position, ArrayList<String> selectedPosition) {
        IMMessage message = ImIn.INSTANCE.getImMessage();
        //更新本地消息
        Map<String, Object> map = message.getLocalExtension();
        if (map == null) {
            map = new HashMap();
        }
        map.put("isSure", true);
        if (position != null) {
            map.put("position", position);
        }
        if (selectedPosition != null) {
            map.put("multiple", selectedPosition);
        }
        message.setLocalExtension(map);
        NIMClient.getService(MsgService.class).updateIMMessage(message);
    }

    /*
     * 用户回答问题接口
     * */
    private void answerMultipleQuestion(MultipleAnswerBean multipleAnswerBean) {

        inputPanel.setInputContent("");
        inputPanel.onlyShowTextEnd();
        answerLingxiQuestion(multipleAnswerBean.getExamId(), multipleAnswerBean.getQuestionPaperId(),
                multipleAnswerBean.getUid(), multipleAnswerBean.getQuestionId(), multipleAnswerBean.getAnswersItems(),
                multipleAnswerBean.getFromUid());
    }

    /*
     * 用户回答问题接口
     * */
    private void answerLingxiQuestion(String examID, String questionPaperId, String uid, String questionId, ArrayList<AnswersItem> answersItems, String fromUID) {
        String str = new Gson().toJson(new LingxiAnswerBean(new AnswerBean(examID, questionPaperId, uid, questionId, answersItems), uid, "56", fromUID));
        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), str);
        Disposable subscribe = ImRetrofitApi.Companion.getImRetrofitApi().lingxiAnswerQuestion(body)
                .compose(RxUtils.INSTANCE.resultJavaData())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(it -> {
                            LogUtil.e("answerQuestion" + it.toString());
                        }, throwable ->
                                com.yidianling.common.tools.LogUtil.e(throwable.getMessage())
                );
    }

    public boolean onBackPressed() {
        return inputPanel.collapse(true) || messageListPanel.onBackPressed() || openOrCloseCommonQuestionLayout(false);
    }

    //刷新消息列表
    public void refreshMessageList() {
        messageListPanel.refreshMessageList();
    }

    //接收参数
    private void parseIntent() {
        sessionId = getArguments().getString(Extras.EXTRA_ACCOUNT);
        sessionType = (SessionTypeEnum) getArguments().getSerializable(Extras.EXTRA_TYPE);
        IMMessage anchor = (IMMessage) getArguments().getSerializable(Extras.EXTRA_ANCHOR);

        customization = (SessionCustomization) getArguments().getSerializable(Extras.EXTRA_CUSTOMIZATION);
        Container container = new Container(getActivity(), sessionId, sessionType, this);

        if (messageListPanel == null) {
            String chatStatusKey = container.account + ModularServiceManager.INSTANCE.provide(IUserService.class).getUserInfo().getUid();
            String userChatStatus = SharedPreferencesEditor.getString(chatStatusKey);

            if (TextUtils.equals(userChatStatus, "true")) {
                messageListPanel = new MessageListPanelEx(container, rootView, anchor, false, true);
                SharedPreferencesEditor.putString(chatStatusKey, "true");
            } else {
                messageListPanel = new MessageListPanelEx(container, rootView, anchor, false, false);
            }
        } else {
            messageListPanel.reload(container, anchor);
        }

        if (inputPanel == null) {
            inputPanel = new InputPanel(getActivity(), container, rootView, getActionList());
            inputPanel.setCustomization(customization);

        } else {
            inputPanel.reload(container, customization);
        }

        initAitManager();

        registerObservers(true);

        if (customization != null) {
            messageListPanel.setChattingBackground(customization.backgroundUri, customization.backgroundColor);
        }
    }

    private void initAitManager() {
        UIKitOptions options = NimUIKitImpl.getOptions();
        if (options.aitEnable) {
            aitManager = new AitManager(getContext(), options.aitTeamMember && sessionType == SessionTypeEnum.Team ? sessionId : null);
            inputPanel.addAitTextWatcher(aitManager);
            aitManager.setTextChangeListener(inputPanel);
        }
    }

    /**
     * ************************* 消息收发 **********************************
     */
    // 是否允许发送消息
    protected boolean isAllowSendMessage(final IMMessage message) {
        return customization.isAllowSendMessage(message);
    }


    private void registerObservers(boolean register) {
        MsgServiceObserve service = NIMClient.getService(MsgServiceObserve.class);
        service.observeReceiveMessage(incomingMessageObserver, register);
        // 已读回执监听
        if (NimUIKitImpl.getOptions().shouldHandleReceipt) {
            service.observeMessageReceipt(messageReceiptObserver, register);
        }
    }

    /**
     * 消息接收观察者
     */
    Observer<List<IMMessage>> incomingMessageObserver = new Observer<List<IMMessage>>() {
        @Override
        public void onEvent(List<IMMessage> messages) {
            onMessageIncoming(messages);
        }
    };

    private void onMessageIncoming(List<IMMessage> messages) {
        if (CommonUtil.isEmpty(messages)) {
            return;
        }
        messageListPanel.onIncomingMessage(messages);
        // 发送已读回执
        messageListPanel.sendReceipt();
    }

    /**
     * 已读回执观察者
     */
    private Observer<List<MessageReceipt>> messageReceiptObserver = new Observer<List<MessageReceipt>>() {
        @Override
        public void onEvent(List<MessageReceipt> messageReceipts) {
            messageListPanel.receiveReceipt();
        }
    };

    /**
     * ********************** implements ModuleProxy *********************
     */
    @Override
    public boolean sendMessage(IMMessage message) {
        if (isAllowSendMessage(message)) {
            //用户对用户第一次聊天发送安全提示消息
            if (ActionHandlerStorage.getL(sessionId) != null) {
                IP2PCustomActionHandler p2PMoreListener = ActionHandlerStorage.getL(sessionId);
                if (p2PMoreListener.getUserType() == USER_TYPE_USER && p2PMoreListener.getSelfUserType() == USER_TYPE_USER && null != p2PMoreListener.getInfo() && p2PMoreListener.getInfo().is_first == 1) {
                    p2PMoreListener.getInfo().is_first = 0;
                    ActionHandlerStorage.getL(sessionId).sendCustomMsg();
                }
            }
            appendTeamMemberPush(message);
            final IMMessage msg = message;
            appendPushConfig(message);
            // send message to server and save to db
            NIMClient.getService(MsgService.class).sendMessage(message, false).setCallback(new RequestCallback<Void>() {
                @Override
                public void onSuccess(Void param) {

                }

                @Override
                public void onFailed(int code) {
                    if (msg != null) {
                        sendFailWithBlackList(code, msg);
                    }
                }

                @Override
                public void onException(Throwable exception) {

                }
            });
            AliYunRichLogsHelper.Companion.getInstance().sendRichLog(AliYunLogConfig.YUNXIN, "sendMessage  该消息发送成功 sessionId:" + sessionId);
        } else {
            // 替换成tip
            message = MessageBuilder.createTipMessage(message.getSessionId(), message.getSessionType());
            message.setContent("该消息无法发送");
            message.setStatus(MsgStatusEnum.success);
            NIMClient.getService(MsgService.class).saveMessageToLocal(message, false);
            AliYunRichLogsHelper.Companion.getInstance().sendRichLog(AliYunLogConfig.YUNXIN, "sendMessage  该消息无法发送 sessionId:" + sessionId);
        }

        messageListPanel.onMsgSend(message);
        if (aitManager != null) {
            aitManager.reset();
        }
        return true;
    }

    // 被对方拉入黑名单后，发消息失败的交互处理
    private void sendFailWithBlackList(int code, IMMessage msg) {
        if (code == ResponseCode.RES_IN_BLACK_LIST) {
            // 如果被对方拉入黑名单，发送的消息前不显示重发红点
            msg.setStatus(MsgStatusEnum.success);
            NIMClient.getService(MsgService.class).updateIMMessageStatus(msg);
            messageListPanel.refreshMessageList();
            // 同时，本地插入被对方拒收的tip消息
            IMMessage tip = MessageBuilder.createTipMessage(msg.getSessionId(), msg.getSessionType());
            tip.setContent(getActivity().getString(R.string.im_black_list_send_tip));
            tip.setStatus(MsgStatusEnum.success);
            CustomMessageConfig config = new CustomMessageConfig();
            config.enableUnreadCount = false;
            tip.setConfig(config);
            NIMClient.getService(MsgService.class).saveMessageToLocal(tip, true);

            LogHelper.Companion.getInstance().writeLogSync("发送消息失败：已被对方拉黑");
            ToastUtil.toastLong(getActivity(), "您已被对方拉黑!");
            AliYunRichLogsHelper.Companion.getInstance().sendRichLog(AliYunLogConfig.YUNXIN, "sendFailWithBlackList  发送消息失败：已被对方拉黑 sessionId:" + sessionId);
        } else if (code == 404) {
            LogHelper.Companion.getInstance().writeLogSync("发送消息失败：对象不见了");
            ToastUtil.toastLong(getActivity(), "对象不见了!");
            AliYunRichLogsHelper.Companion.getInstance().sendRichLog(AliYunLogConfig.YUNXIN, "sendFailWithBlackList  发送消息失败：对象不见了 404 sessionId:" + sessionId);

        } else {
            //上传至后台
            if (!TextUtils.isEmpty(sessionId) && ActionHandlerStorage.getL(sessionId) != null) {
                ActionHandlerStorage.getL(sessionId).uploadSendMessageError(code);
            }
        }
    }

    private void appendTeamMemberPush(IMMessage message) {
        if (aitManager == null) {
            return;
        }
        if (sessionType == SessionTypeEnum.Team) {
            List<String> pushList = aitManager.getAitTeamMember();
            if (pushList == null || pushList.isEmpty()) {
                return;
            }
            MemberPushOption memberPushOption = new MemberPushOption();
            memberPushOption.setForcePush(true);
            memberPushOption.setForcePushContent(message.getContent());
            memberPushOption.setForcePushList(pushList);
            message.setMemberPushOption(memberPushOption);
        }
    }


    private void appendPushConfig(IMMessage message) {
        CustomPushContentProvider customConfig = NimUIKitImpl.getCustomPushContentProvider();
        if (customConfig == null) {
            return;
        }
        String content = customConfig.getPushContent(message);
        Map<String, Object> payload = customConfig.getPushPayload(message);
        Map<String, Object> vivoField = new HashMap<>();
        vivoField.put("classification", 1);
        payload.put("vivoField", vivoField);
        if (!TextUtils.isEmpty(content)) {
            message.setPushContent(content);
        }
        if (payload != null) {
            message.setPushPayload(payload);
        }

    }

    @Override
    public void onInputPanelExpand() {
        messageListPanel.scrollToBottom();

        openOrCloseCommonQuestionLayout(false);
    }

    @Override
    public void shouldCollapseInputPanel() {
        inputPanel.collapse(false);

        openOrCloseCommonQuestionLayout(false);
    }

    @Override
    public boolean isLongClickEnabled() {
        return !inputPanel.isRecording();
    }

    @Override
    public void onItemFooterClick(IMMessage message) {

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (aitManager != null) {
            aitManager.onActivityResult(requestCode, resultCode, data);
        }
        inputPanel.onActivityResult(requestCode, resultCode, data);
        messageListPanel.onActivityResult(requestCode, resultCode, data);
    }

    // 操作面板集合
    protected List<BaseAction> getActionList() {
        List<BaseAction> actions = new ArrayList<>();

        if (customization != null && customization.actions != null) {
            actions.addAll(customization.actions);
        }
        return actions;
    }

    private boolean openOrCloseCommonQuestionLayout(boolean open) {
        boolean result = false;
        if (ActionHandlerStorage.getL(sessionId) != null && ActionHandlerStorage.getL(sessionId).getUserType() == USER_TYPE_ASSISTANT) {
            if (open) {
                inputPanel.collapse(true);
                messageListPanel.scrollToBottom();
            }
        }
        return result;
    }

    private void showCheckAgeDialog() {
        CommonDialog.create(getActivity())
                .setLeftOnclick("返回", v -> {
                    getActivity().finish();
                })
                .setRightClick("继续", v -> {
                    SharedPreferencesEditor.putString("chat_age_ensure_" + ImIn.INSTANCE.getUserInfo().getUid(), "ensure");
                })
                .setMessage("由于您未满16周岁，如需咨询需要在家长陪同下进行")
                .setCancelAble(false)
                .show();

    }
}
