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

import android.animation.Animator;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.media.AudioManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

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

import com.blankj.utilcode.util.SPUtils;
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.netease.nimlib.sdk.uinfo.model.NimUserInfo;
import com.ydl.webview.H5Params;
import com.ydl.webview.NewH5Activity;
import com.ydl.ydl_image.module.GlideApp;
import com.ydl.ydlcommon.base.config.HttpConfig;
import com.ydl.ydlcommon.data.PlatformDataManager;
import com.ydl.ydlcommon.data.http.RxUtils;
import com.ydl.ydlcommon.modular.ModularServiceManager;
import com.ydl.ydlcommon.ui.LoadingDialogFragment;
import com.ydl.ydlcommon.utils.AnimUtils;
import com.ydl.ydlcommon.utils.LogUtil;
import com.ydl.ydlcommon.utils.NetworkParamsUtils;
import com.ydl.ydlcommon.utils.SharedPreferencesEditor;
import com.ydl.ydlcommon.utils.YdlBuryPointUtil;
import com.ydl.ydlcommon.utils.actionutil.ActionCountUtils;
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.utils.remind.HttpErrorUtils;
import com.ydl.ydlcommon.view.CircleImageView;
import com.ydl.ydlcommon.view.dialog.CommonDialog;
import com.ydl.ydlcommon.view.dialog.ListDialog;
import com.yidianling.common.tools.ToastUtil;
import com.yidianling.im.R;
import com.yidianling.im.bean.RemoveHistory;
import com.yidianling.im.config.constants.ImConstants;
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.im.session.viewholder.bean.UserIsIn;
import com.yidianling.im.session.viewholder.bean.UserIsInPageData;
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.nimbase.impl.cache.NimUserInfoCache;
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.helper.MessageListPanelHelper;
import com.yidianling.uikit.business.session.module.input.InputPanel;
import com.yidianling.uikit.business.session.module.list.MessageListPanelEx;
import com.yidianling.uikit.business.session.view.ChatPrivateTips;
import com.yidianling.uikit.business.session.view.CommonQuestionView;
import com.yidianling.uikit.business.session.view.ImCommentBannerView;
import com.yidianling.uikit.business.session.view.ImRedStarGradeView;
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.CommonQuestionBean;
import com.yidianling.uikit.custom.http.response.NewUserMesBean;
import com.yidianling.uikit.custom.http.response.UserQuestInfoBean;
import com.yidianling.uikit.custom.widget.ConfideOrderInfoView;
import com.yidianling.uikit.custom.widget.ExpertInfoDialog;
import com.yidianling.uikit.custom.widget.TitleBarBottom;
import com.yidianling.uikit.custom.widget.UserInfoDialog;
import com.yidianling.uikit.custom.widget.expertConsultService.view.ExpertConsultServiceListDialog;
import com.yidianling.user.api.service.IUserService;

import org.jetbrains.annotations.NotNull;

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 View rootView;

    private SessionCustomization customization;

    protected static final String TAG = "MessageActivity";

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

    protected SessionTypeEnum sessionType;

    //快捷菜单
    protected RelativeLayout lin_actions;
    protected RelativeLayout rl_doctor_name;

    private LinearLayout ll_actions_yi;

    private FrameLayout fl_container;
    private ChatPrivateTips v_chattips;
    // modules
    protected InputPanel inputPanel;
    private int rvPaddingTop;
    private RelativeLayout rl_contain;
    private boolean initHeightFinish;
    public TitleBarBottom titleBar;
    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 CircleImageView small_head_img; //小头像
    private TextView help_num_tv; //帮助人数
    private TextView server_num_tv; //服务时长
    private TextView good_num_tv; //好评率

    private LinearLayout top_expert_info_ll;
    private int expertInfoViewHeight = 0; // 专家信息栏高度
    private RecyclerView messageListView;
    private ConstraintLayout top_expert_info_cl;
//    private RelativeLayout rl_common_question_enter;
    private FrameLayout fl_question_content;
    private List<CommonQuestionBean> commonQuestionBeanList;
    private TextView question_multiple;
    private LinearLayout comment_banner_view_ll;
    private TextView tv_all_comment_desc;
    private ImageView tv_all_comment_go;
    private ImCommentBannerView comment_banner_view;

    private ImRedStarGradeView good_num_icons;

    private TextView im_focus_btn;
    private TextView tv_from;
    private TextView tv_doctor_name;

    private LinearLayout top_view_container;
    private RelativeLayout constraint_ll;
    private LinearLayout ll_info_detail;

    protected RelativeLayout rela_zixun;
    private ValueAnimator anim_out;
    private ObjectAnimator sourceLayoutAnim;
    private ValueAnimator anim_in;
    private Boolean expertInfoViewIsIn = true;
    private Boolean expertInfoViewIsAnimating = false;

    private ExpertInfoDialog expertInfoDialog;
    private ExpertConsultServiceListDialog expertConsultServiceListDialog;

    private int IN_OUT_DURATION = 400;

    private Boolean hasUpScroll = false;

    private String help_num;// 帮助人数
    private String server_num;// 服务时长
    private String good_num;// 好评率

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

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

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (timeCount == 5) {
                v_chattips.setVisibility(View.GONE);
            } else {
                timeCount++;
                sendEmptyMessageDelayed(1, 1000);
            }
        }
    };

    @SuppressLint("CheckResult")
    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        parseIntent();
         titleBar = ((YDLBaseMessageActivity) getActivity()).getTitleBarBottom();
        titleBar.setTitleLeftDraw(getResources().getDrawable(R.drawable.loading_01));
        titleBar.setTitle("正在连接中...");

        fl_container = rootView.findViewById(R.id.message_activity_list_view_container);
        v_chattips = rootView.findViewById(R.id.v_chattips);
        lin_actions = rootView.findViewById(R.id.lin_actions);
        ll_actions_yi = rootView.findViewById(R.id.ll_actions_yi);
        small_head_img = rootView.findViewById(R.id.small_head_img);
        help_num_tv = rootView.findViewById(R.id.help_num_tv);
        server_num_tv = rootView.findViewById(R.id.server_num_tv);
        good_num_tv = rootView.findViewById(R.id.good_num_tv);
        top_expert_info_ll = rootView.findViewById(R.id.top_expert_info_ll);
        top_expert_info_cl = rootView.findViewById(R.id.top_expert_info_cl);
        comment_banner_view_ll = rootView.findViewById(R.id.comment_banner_view_ll);
        tv_all_comment_desc = rootView.findViewById(R.id.tv_all_comment_desc);
        tv_all_comment_go = rootView.findViewById(R.id.tv_all_comment_go);
        comment_banner_view = rootView.findViewById(R.id.comment_banner_view);
        messageListView = rootView.findViewById(R.id.messageListView); // 消息列表
        top_view_container = rootView.findViewById(R.id.top_view_container); // 消息列表
        constraint_ll = rootView.findViewById(R.id.constraint_ll);
        im_focus_btn = rootView.findViewById(R.id.im_focus_btn);
        good_num_icons = rootView.findViewById(R.id.good_num_icons);
        rela_zixun = rootView.findViewById(R.id.rela_zixun);
        rl_doctor_name = rootView.findViewById(R.id.rl_doctor_name);
        tv_from = rootView.findViewById(R.id.tv_from);
        ll_info_detail = rootView.findViewById(R.id.ll_info_detail);
        tv_doctor_name = rootView.findViewById(R.id.tv_doctor_name);
        rl_contain = rootView.findViewById(R.id.rl_contain);
        messageListView.setItemAnimator(null);
                //和助理私聊时的常用语逻辑
//        rl_common_question_enter = rootView.findViewById(R.id.rl_common_question);
        fl_question_content = rootView.findViewById(R.id.fl_question_content);
        question_multiple = rootView.findViewById(R.id.question_multiple);
            //做灵犀2.0 去掉常用语逻辑
            //rl_common_question_enter.setVisibility(ActionHandlerStorage.getL(sessionId) != null && ActionHandlerStorage.getL(sessionId).getUserType() == 3 ? View.VISIBLE : View.GONE);

        if (null!=ActionHandlerStorage.getL(sessionId)&&ActionHandlerStorage.getL(sessionId).getUserType() != 2) {
            if (null != getActivity() && null != rela_zixun) {
                rela_zixun.setVisibility(View.GONE);
            }
        }
        if (null!=ActionHandlerStorage.getL(sessionId)&&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();
        }
        //如果是群聊
        if (SessionTypeEnum.Team==sessionType){
            titleBar.setRightIcon(getContext().getDrawable(R.drawable.platform_common_more));
            rela_zixun.setVisibility(View.GONE);
            titleBar.setTitleRightDraw(null);
        }
    }

    @SuppressLint("CheckResult")
    private void initView() {
        if (ChatStatusCacheHelper.getStatusCache("chatEvent")&&SessionTypeEnum.Team!=sessionType) {
            // 获取首问语数据
            ServiceImpl.Companion.getInstance().getFirstQuestion()
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(res -> {
                        if (res.code.equals("200")){
                            if (!res.data.getObjects().isEmpty()){
                                inputPanel.setFirstQuestion(res.data.getObjects());
                            }
                        }
                    }, throwable -> {
                        ToastUtil.toastShort(throwable.getMessage());
                    });
        }

        //有未完成订单或者有未评价订单时，显示订单布局
        if (ActionHandlerStorage.getL(sessionId) != null && ActionHandlerStorage.getL(sessionId).getInfo() != null) {
            if (ActionHandlerStorage.getL(sessionId).getInfo().hasAvailableListenOrder == 2 || ActionHandlerStorage.getL(sessionId).getInfo().listenOrderCommentStatus == 1) {
                //2专家   1用户
                ConfideOrderInfoView confideOrderInfoView = new ConfideOrderInfoView(getContext(), sessionId);
                confideOrderInfoView.setData(ActionHandlerStorage.getL(sessionId).getInfo());
                rl_contain.addView(confideOrderInfoView);
                AnimUtils.Companion.slideToDown(rl_contain);
            }
        }
        TitleBarBottom titleBar = ((YDLBaseMessageActivity) getActivity()).getTitleBarBottom();
        if (!UserPreferences.isEarPhoneModeEnable()) {
            titleBar.setTitleLeftDraw(null);
        } else {
            titleBar.setTitleRightDraw(getResources().getDrawable(R.drawable.im_erduoxiaolv));
        }
        if (ActionHandlerStorage.getL(sessionId)!=null){
            titleBar.setTitle(ActionHandlerStorage.getL(sessionId).getInfo().name);
        }
        // 初始化顶部专家信息栏
        if (ActionHandlerStorage.getL(sessionId) != null && ActionHandlerStorage.getL(sessionId).getUserType() == 2) {
            top_expert_info_cl.setVisibility(View.VISIBLE);
            AnimUtils.Companion.slideToDown(top_expert_info_cl);
            initTopCustomBar();
            comment_banner_view_ll.setVisibility(View.VISIBLE);
            AnimUtils.Companion.slideToDown(comment_banner_view_ll);
            initCommentBanner();
            initAnimation(); // 初始化顶部布局的动画
            initTopViewHeight(); //设置顶部专家信息栏高度
            addScrollListener();
            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 == 2 && sType == 1) {
                lin_actions.setVisibility(View.VISIBLE);
                ll_actions_yi.setVisibility(View.GONE);
                AnimUtils.Companion.slideToDown(lin_actions);
                initMenu();
            } else if (type == -1 && sType == 1) {
                ll_actions_yi.setVisibility(View.VISIBLE);
                lin_actions.setVisibility(View.GONE);
                initYiMenu();
            } else {
                ll_actions_yi.setVisibility(View.GONE);
                lin_actions.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();
        if (null!=ActionHandlerStorage.getL(sessionId)&&ActionHandlerStorage.getL(sessionId).getInfo().doctorId != null){
             // 获取专家是否在繁忙状态
            ServiceImpl.Companion.getInstance().queryDoctorIsBusy(ActionHandlerStorage.getL(sessionId).getInfo().doctorId)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(res -> {
                    isBusy = res.data.getSuccess();
                }, throwable -> {
                });
        }
    }

    /**
     * 是否隐藏输入框相关控件
     */
    public void setGoneInput(boolean isGone){
        if (isGone){
            inputPanel.messageInputBar.setVisibility(View.GONE);
            inputPanel.hideInputMethod();
        }else {
            inputPanel.messageInputBar.setVisibility(View.VISIBLE);
        }
    }
    @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());
                        }
                    }
                    if ("200".equals(res.code) && res.data != null) {
                        if (res.data.getStatus() == 0) {
                            if (null != getActivity() && null != rela_zixun) {
                                rela_zixun.setVisibility(View.GONE);
                            }
                        }
                    }
                }, throwable -> {
                });
        if (ActionHandlerStorage.getL(sessionId) != null && ActionHandlerStorage.getL(sessionId).getUserType() == 1 && ModularServiceManager.INSTANCE.provide(IUserService.class).getUserInfo().getUser_type() == 3) {
            //获取来源的专家
            ServiceImpl.Companion.getInstance().getSourceDoctor(ActionHandlerStorage.getL(sessionId).getInfo().toUid, ModularServiceManager.INSTANCE.provide(IUserService.class).getUserInfo().getUid())
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(res -> {
                        if (TextUtils.equals(res.code, "200") && res.data != null && !TextUtils.isEmpty(res.data.name)) {
                            addSourceLayoutScrollListener();
                            rl_doctor_name.setVisibility(View.VISIBLE);

                            tv_doctor_name.setText(res.data.name);
                        } else {
                            rl_doctor_name.setVisibility(View.GONE);
                        }
                    }, throwable -> {
                        rl_doctor_name.setVisibility(View.GONE);
                    });
        }

        String targetUid = "";
        if (ModularServiceManager.INSTANCE.provide(IUserService.class).getUserInfo().getUser_type() == 1) {
            //自己是用戶,搜索的是自己的信息
            targetUid = ModularServiceManager.INSTANCE.provide(IUserService.class).getUserInfo().getUid();
        } else if (ModularServiceManager.INSTANCE.provide(IUserService.class).getUserInfo().getUser_type() == 3) {
            // 自己是助理，搜索的是对方（用户）的信息
            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() == 1) {
                            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() == 1 && ModularServiceManager.INSTANCE.provide(IUserService.class).getUserInfo().getUser_type() == 3) {
                            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) {
                                            e.printStackTrace();
                                        }
                                    } else if (TextUtils.equals(bean.getUserInfoType(), "gener")) {
                                        try {
                                            userInfoDialogSex = bean.getContent();
                                        } catch (Exception e) {
                                            e.printStackTrace();
                                        }
                                    } else if (TextUtils.equals(bean.getUserInfoType(), "questionType")) {
                                        try {
                                            userInfoDialogConsultType = bean.getContent();
                                        } catch (Exception e) {
                                            e.printStackTrace();
                                        }
                                    } else if (TextUtils.equals(bean.getUserInfoType(), "questionContent")) {
                                        try {
                                            userInfoDialogQuestionDes = bean.getContent();
                                        } catch (Exception e) {
                                            e.printStackTrace();
                                        }
                                    }
                                }
                                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 addScrollListener() {
        messageListView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);

                if (dy < 0 && Math.abs(dy) > 15) {
                    hasUpScroll = true;
                    // 下滑
                    if (!expertInfoViewIsIn && !expertInfoViewIsAnimating) {

                        expertInfoViewIsAnimating = true;
                        anim_in.start();
                    }
                } else if (dy > 0 && Math.abs(dy) > 15) {
                    if (expertInfoViewIsIn && !expertInfoViewIsAnimating && hasUpScroll) {


                        expertInfoViewIsAnimating = true;
                        anim_out.start();
                    }
                }
            }
        });
    }

    private void addSourceLayoutScrollListener() {
        messageListView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                    sourceDoctorLayoutIn();
                } else {
                    sourceDoctorLayoutOut();
                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);

            }
        });
    }

    private void initTopViewHeight() {
        rl_contain.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                if (initHeightFinish) {
                    rvPaddingTop += rl_contain.getHeight();
                    messageListView.setPadding(0, rvPaddingTop, 0, 0);
                } else {
                    rvPaddingTop += rl_contain.getHeight();
                }
                initHeightFinish = true;
                rl_contain.getViewTreeObserver().removeOnGlobalLayoutListener(this);
            }
        });
        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);
                rl_contain.getViewTreeObserver().removeOnGlobalLayoutListener(this);
            }
        });
    }

    private void initAnimation() {
        anim_out = newAnimation(0f, 1f);
        anim_out.setDuration(IN_OUT_DURATION);
        anim_in = newAnimation(1f, 0f);
        anim_in.setDuration(IN_OUT_DURATION);
        anim_in.addUpdateListener(animation -> {
            if (expertInfoViewHeight != 0 && constraint_ll != null) {

                ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams) constraint_ll.getLayoutParams();

                params.topMargin = (int) (-expertInfoViewHeight * Float.valueOf(animation.getAnimatedValue().toString()));
                constraint_ll.setLayoutParams(params);
            }
        });
        anim_in.addListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animation) {

            }

            @Override
            public void onAnimationEnd(Animator animation) {
                expertInfoViewIsIn = true;
                expertInfoViewIsAnimating = false;
            }

            @Override
            public void onAnimationCancel(Animator animation) {

            }

            @Override
            public void onAnimationRepeat(Animator animation) {

            }
        });
        anim_out.addUpdateListener(animation -> {
            if (expertInfoViewHeight != 0 && constraint_ll != null) {
                ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams) constraint_ll.getLayoutParams();

                params.topMargin = (int) (-expertInfoViewHeight * Float.valueOf(animation.getAnimatedValue().toString()));
                constraint_ll.setLayoutParams(params);
            }
        });
        anim_out.addListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animation) {

            }

            @Override
            public void onAnimationEnd(Animator animation) {
                expertInfoViewIsIn = false;
                expertInfoViewIsAnimating = false;

            }

            @Override
            public void onAnimationCancel(Animator animation) {

            }

            @Override
            public void onAnimationRepeat(Animator animation) {

            }
        });

    }

    private ValueAnimator newAnimation(float fromYValue, float toYValue) {
        ValueAnimator anim = ValueAnimator.ofFloat(fromYValue, toYValue);
        return anim;
    }

    private void sourceDoctorLayoutIn() {
        if (rl_doctor_name.getVisibility() == View.VISIBLE) {
            if (sourceLayoutAnim == null) {
                sourceLayoutAnim = ObjectAnimator.ofFloat(ll_info_detail, "translationX", 0.0f, -tv_from.getMeasuredWidth());
                sourceLayoutAnim.setDuration(250);
            }
            sourceLayoutAnim.reverse();
        }
    }

    private void sourceDoctorLayoutOut() {
        if (rl_doctor_name.getVisibility() == View.VISIBLE) {
            if (sourceLayoutAnim == null) {
                sourceLayoutAnim = ObjectAnimator.ofFloat(ll_info_detail, "translationX", 0.0f, -tv_from.getMeasuredWidth());
                sourceLayoutAnim.setDuration(250);
            }
            sourceLayoutAnim.start();
        }
    }


    /**
     * 初始化顶部专家信息栏
     */
    private void initTopCustomBar() {
        // 头像
        String headUrl = ActionHandlerStorage.getL(sessionId).getInfo().doctorBriefInfoSmallImage;
        if (!TextUtils.isEmpty(headUrl)) {
            GlideApp.with(getActivity()).load(headUrl).into(small_head_img);
            small_head_img.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (ActionHandlerStorage.getL(sessionId) != null) {//
                        int userType = ActionHandlerStorage.getL(sessionId).getUserType();//1普通用户2专家3助理
                        if (userType == 1 || userType == 3) {
                            //跳转用户主页
                            ActionHandlerStorage.getL(sessionId).showUserHome();
                        } else if (userType == 2) {
                            //跳转专家主页
                            ActionHandlerStorage.getL(sessionId).showZhuanjPage();
                        }
                    }
                }
            });
        }
        // 帮助人数
        help_num = String.valueOf(ActionHandlerStorage.getL(sessionId).getInfo().doctorBriefInfoOrderNum);
        if (TextUtils.isEmpty(help_num)) {
            help_num = "0";
        }
        help_num_tv.setText(help_num);
        // 服务时长
        server_num = String.valueOf((int) Math.ceil((double) ActionHandlerStorage.getL(sessionId).getInfo().doctorBriefInfoHelpLong / 60.0));
        if (TextUtils.isEmpty(server_num)) {
            server_num = "0";
        }
        server_num_tv.setText(server_num);
        // 好评率
        good_num = ActionHandlerStorage.getL(sessionId).getInfo().doctorBriefInfoFeedbackRateForShow;
        if (TextUtils.isEmpty(good_num)) {
            good_num = "0.0";
        }
        good_num_tv.setText(good_num);

        try {
            good_num_icons.setGrade(Float.parseFloat(good_num));
        } catch (Exception e) {
            LogUtil.i(e.toString());
        }
        if (!TextUtils.isEmpty(headUrl)) {
            IP2PCustomActionHandler.DocInfo info = ActionHandlerStorage.getL(sessionId).getInfo();
            if (null != info) {
                NimUserInfo user = NimUserInfoCache.getInstance().getUserInfo(info.toUid);
                if (null != user && null != user.getAvatar() && headUrl.equals(user.getAvatar())) {
                    NimUserInfoCache.getInstance().getUserInfoFromRemote(info.toUid, null);
                }
            }
        }

        top_expert_info_cl.setOnClickListener(v -> {
            if (null != getActivity()) {
                if (expertInfoDialog == null) {
                    expertInfoDialog = new ExpertInfoDialog(getActivity(), help_num, server_num, good_num);
                }
                expertInfoDialog.show();
            }
        });
    }

    /**
     * 初始化顶部专家信息栏下面的评论view
     */
    private void initCommentBanner() {
        if (ActionHandlerStorage.getL(sessionId).getInfo().commentList.size() == 0) {
            comment_banner_view_ll.setVisibility(View.GONE);
            return;
        }

        int commentCounter = ActionHandlerStorage.getL(sessionId).getInfo().commentCounter;
        tv_all_comment_desc.setText(String.valueOf(commentCounter));

        H5Params params = new H5Params(ActionHandlerStorage.getL(sessionId).getInfo().commentCounterUrl, "");

        View.OnClickListener onClickListener = v -> NewH5Activity.start(getActivity(), params);
        tv_all_comment_desc.setOnClickListener(onClickListener);
        tv_all_comment_go.setOnClickListener(onClickListener);

        comment_banner_view.initData(ActionHandlerStorage.getL(sessionId).getInfo().commentList);

        if (ActionHandlerStorage.getL(sessionId).getInfo().isFollowed) {
            im_focus_btn.setText("已关注");
            im_focus_btn.setTextColor(Color.parseColor("#999999"));
            im_focus_btn.setBackgroundResource(R.drawable.im_unfocus_btn_bg);
        } else {
            im_focus_btn.setText("关注");
            im_focus_btn.setTextColor(getResources().getColor(R.color.platform_main_theme));
            im_focus_btn.setBackgroundResource(R.drawable.im_focus_btn_bg);
            im_focus_btn.setOnClickListener(v -> {
                focus();
            });
        }
    }

    //关注
    @SuppressLint("CheckResult")
    private void focus() {
        if (ActionHandlerStorage.getL(sessionId) != null && ActionHandlerStorage.getL(sessionId).getInfo() != null) {
            // 未关注才能进行关注
            if (ActionHandlerStorage.getL(sessionId).getInfo().isFollowed == false) {
                ActionHandlerStorage.getL(sessionId).getInfo().isFollowed = true;
                ServiceImpl.Companion.getInstance().focus(ActionHandlerStorage.getL(sessionId).getInfo().doctorId, "1")
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(res -> {
                            if ("200".equals(res.code) && null != getActivity()) {
                                ToastUtil.toastShort("关注成功");
                                im_focus_btn.setText("已关注");
                                im_focus_btn.setTextColor(Color.parseColor("#999999"));
                                im_focus_btn.setBackgroundResource(R.drawable.im_unfocus_btn_bg);
                                if (ActionHandlerStorage.getL(sessionId) != null && ActionHandlerStorage.getL(sessionId).getInfo() != null) {
                                    ActionHandlerStorage.getL(sessionId).getInfo().isFollowed = true;
                                }
                            }
                        }, throwable -> {
                            if (null != getActivity()) {
                                ActionHandlerStorage.getL(sessionId).getInfo().isFollowed = false;
//                                ToastUtil.toastShort(throwable.toString());
                            }
                        });
            }
        }
    }

    private void showTips() {
        mHandler.sendEmptyMessageDelayed(1, 1000);
    }

    boolean isBusy = false; // 是否繁忙
    //初始化聊天顶部快捷菜单
    @SuppressLint("CheckResult")
    private void initMenu() {
        rela_zixun.setOnClickListener(view -> {
            if (sessionId != null && ActionHandlerStorage.getL(sessionId) != null && ActionHandlerStorage.getL(sessionId).getInfo() != null) {
                if (expertConsultServiceListDialog == null) {
                    ServiceImpl.Companion.getInstance().serviceList(ActionHandlerStorage.getL(sessionId).getInfo().doctorId)
                            .subscribeOn(Schedulers.io())
                            .observeOn(AndroidSchedulers.mainThread())
                            .subscribe(res -> {
                                if (res.data != null && res.data.size() > 0) {
                                    if (getActivity() != null && expertConsultServiceListDialog == null) {
                                        expertConsultServiceListDialog = new ExpertConsultServiceListDialog(getActivity(), res.data,isBusy,sessionId);
                                        expertConsultServiceListDialog.show();
                                    }
                                } else {
                                    ToastUtil.toastShort("咨询师暂未发布服务");
                                }
                            }, throwable -> {
                            });
                } else {
                    expertConsultServiceListDialog.show();
                }
            } else {
                ToastUtil.toastShort("请退出聊天重试");
            }
        });

        //倾诉,不确定是否还要使用，暂留
//        RelativeLayout rela_qingsu = rootView.findViewById(R.id.rela_qingsu);
//        StateListDrawable confideDrawable = new StateListDrawable();
//        confideDrawable.addState(new int[]{android.R.attr.state_pressed}, new HalfCircleDrawable(getContext(), true, ContextCompat.getColor(getContext(), R.color.platform_color_F7F7F7)));
//        confideDrawable.addState(new int[]{}, new HalfCircleDrawable(getContext(), true, Color.WHITE));
//        rela_qingsu.setBackground(confideDrawable);
//
//        if (ActionHandlerStorage.getL(sessionId) != null && ActionHandlerStorage.getL(sessionId).getInfo().listenerIsOpen == 1) {//开通倾诉
//            int status = ActionHandlerStorage.getL(sessionId).getInfo().isChatOnline;
//            if (status == 5) {
//                qingshu.setText("倾诉通话中...");
//                qingshu.setTextColor(Color.parseColor("#BFBFBF"));
//                qingshuImg.setImageResource(R.mipmap.im_chat_ico_calling);
//                canConsultBtnClick = false;
//            } else if (status == 3 || status == 4 || status == 6) {
//                qingshu.setText("即时倾诉");
//                qingshu.setTextColor(Color.parseColor("#BFBFBF"));
//                qingshuImg.setImageResource(R.mipmap.im_chat_ico_calling);
//                canConsultBtnClick = false;
//            } else {
//                qingshu.setText("即时倾诉");
//                qingshu.setTextColor(Color.parseColor("#242424"));
//                qingshuImg.setImageResource(R.mipmap.im_chat_ico_can_call);
//                canConsultBtnClick = true;
//            }
//            if (ActionHandlerStorage.getL(sessionId).getInfo().hasAvailableListenOrder == 2) {//有未完成订单
//                qingshu.setText("继续倾诉");
//                qingshu.setTextColor(Color.parseColor("#242424"));
//                qingshuImg.setImageResource(R.mipmap.im_chat_ico_calling);
//                canConsultBtnClick = true;
//            }
//        } else {
//            qingshu.setText("即时倾诉");
//            qingshu.setTextColor(Color.parseColor("#242424"));
//            qingshuImg.setImageResource(R.mipmap.im_chat_ico_can_call);
//            canConsultBtnClick = true;
//        }
//
//
//        rela_qingsu.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                if (canConsultBtnClick) {
//                    LogHelper.Companion.getInstance().writeLogSync("聊天界面点击电话倾诉");
//                    if (ActionHandlerStorage.getL(sessionId) != null) {
//                        try {
//                            JSONObject jsb = new JSONObject();
//                            jsb.put("button_name", "电话倾诉");
//                            ActionHandlerStorage.getL(sessionId).buryPoint("messageClick", jsb);
//
//                            JSONObject jsonObject = new JSONObject();
//                            jsonObject.put("expert_id", ActionHandlerStorage.getL(sessionId).getInfo().doctorId);
//                            jsonObject.put("expert_name", ActionHandlerStorage.getL(sessionId).getInfo().name);
//                            jsonObject.put("listen_entrance", "私聊窗口");
//                            ActionHandlerStorage.getL(sessionId).buryPoint("Listen_expert", jsonObject);
//                        } catch (JSONException e) {
//                            e.printStackTrace();
//                        }
//                        ActionHandlerStorage.getL(sessionId).confide();
//                    } else {
//                        ToastUtil.toastShort("请退出聊天重试");
//                    }
//                }
//            }
//        });
    }

    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();
        userIsInPage("67","用户离开当前页面",sessionId,ImIn.INSTANCE.getUserInfo().getUid());
        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); // 默认使用听筒播放
        userIsInPage("66","用户在当前页面",sessionId,ImIn.INSTANCE.getUserInfo().getUid());
        messageListPanel.scrollToBottom();

    }


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


    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()){
                question_multiple.setVisibility(View.GONE);
                inputPanel.onlyShowTextEnd();
                return;
            }
            if (event.getOthersState().isOthers()){
                //用户点击了其他事件
                if (event.getOthersState().getOthersSelect()){
                    //其他是选中状态
                    isOthers=event.getOthersState().getOthersSelect();
                    rootView.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            inputPanel.onlyShowTextStart();
                        }
                    }, 500);
                }else{
                    //其他是未选中状态
                    question_multiple.setVisibility(View.GONE);
                    isOthers=event.getOthersState().getOthersSelect();
                    inputPanel.onlyShowTextEnd();
                }
                if (event.getStrSelected().contains("其他")){
                    question_multiple.setVisibility(View.VISIBLE);
                    question_multiple.setText(event.getStrSelected().replace("、","#"));
                }
            }else{
                if (event.getStrSelected().contains("其他")){
                    question_multiple.setVisibility(View.VISIBLE);
                    question_multiple.setText(event.getStrSelected().replace("、","#"));
                }
            }
        }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("");
        question_multiple.setText("");
        question_multiple.setVisibility(View.GONE);
        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() == 1 && p2PMoreListener.getSelfUserType() == 1 && 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() == 3) {
            if (open) {
                inputPanel.collapse(true);
                messageListPanel.scrollToBottom();
            }

            /*if (rl_common_question_enter != null) {
                rl_common_question_enter.setVisibility(open ? View.GONE : View.VISIBLE);
            }*/
            if (fl_question_content != null) {
                if (fl_question_content.getVisibility() == View.VISIBLE) {
                    result = true;
                }
                fl_question_content.setVisibility(open ? View.VISIBLE : View.GONE);
            }
        }
        return result;
    }


//    @SuppressLint("CheckResult")
//    private void getCommonQuestionListData() {
//        ServiceImpl.Companion.getInstance().getCommonQuestionList()
//                .subscribeOn(Schedulers.io())
//                .observeOn(AndroidSchedulers.mainThread())
//                .subscribe(res -> {
//                    if (res.data != null && res.data.size() > 0) {
//                        if (commonQuestionBeanList == null) {
//                            commonQuestionBeanList = new ArrayList<>();
//                        } else {
//                            commonQuestionBeanList.clear();
//                        }
//                        commonQuestionBeanList.addAll(res.data);
//                        initCommonQuestionLayout();
//                    }
//
//                }, throwable -> {
//                    ToastUtil.toastShort(throwable.toString());
//                });
//    }
    /*
     * 用户是否在当前页面
     *
     * */
    private  void userIsInPage(String noticeType,String content,String fromUid,String toUid) {
        String str =  new Gson().toJson(new UserIsIn(new UserIsInPageData(content),toUid,noticeType,fromUid));
        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), str);
        Disposable subscribe = ImRetrofitApi.Companion.getImRetrofitApi().lingxiSendNotice(body)
                .compose(RxUtils.INSTANCE.resultJavaData())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(it -> {
                            LogUtil.e(it.toString()+content);
                        }, throwable ->
                                com.yidianling.common.tools.LogUtil.e(throwable.getMessage())
                );
    }
    private void initCommonQuestionLayout() {
        CommonQuestionView commonQuestionView = new CommonQuestionView(getActivity());
        commonQuestionView.setData(commonQuestionBeanList);
        commonQuestionView.setListener(new CommonQuestionView.OnSelectItemListener() {
            @Override
            public void close() {
                openOrCloseCommonQuestionLayout(false);
            }

            @Override
            public void onSelect(@NotNull String title, String id) {
                IMMessage textMessage = MessageBuilder.createTextMessage(sessionId, sessionType, title);
                if (sendMessage(textMessage)) {
                    openOrCloseCommonQuestionLayout(false);
                }
                commonQuestionClickCount(id);
            }
        });
        fl_question_content.addView(commonQuestionView);
        openOrCloseCommonQuestionLayout(true);
    }

    @SuppressLint("CheckResult")
    private void commonQuestionClickCount(String id) {
        ServiceImpl.Companion.getInstance().sendCommonQuestionCount(id)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(objectBaseAPIResponse -> {

                }, throwable -> {

                });
    }

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

        ActionCountUtils.Companion.count("under_age_alert_page|under_age_alert_page_visit");
    }
}
