package com.yidianling.im.bridge;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import androidx.appcompat.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;

import com.google.gson.internal.LinkedTreeMap;
import com.netease.nimlib.sdk.NIMClient;
import com.netease.nimlib.sdk.RequestCallback;
import com.netease.nimlib.sdk.msg.MessageBuilder;
import com.netease.nimlib.sdk.msg.MsgService;
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.umeng.analytics.MobclickAgent;
import com.ydl.webview.H5Params;
import com.ydl.webview.NewH5Activity;
import com.ydl.ydlcommon.base.config.HttpConfig;
import com.ydl.ydlcommon.bean.ShareData;
import com.ydl.ydlcommon.data.PlatformDataManager;
import com.ydl.ydlcommon.data.http.RxUtils;
import com.ydl.ydlcommon.data.http.UpLoadLogUtils;
import com.ydl.ydlcommon.router.YdlCommonRouterManager;
import com.ydl.ydlcommon.ui.LoadingDialogFragment;
import com.ydl.ydlcommon.utils.ActivityManager;
import com.ydl.ydlcommon.utils.BuryPointUtils;
import com.ydl.ydlcommon.utils.NetworkParamsUtils;
import com.ydl.ydlcommon.utils.StringUtils;
import com.ydl.ydlcommon.utils.YDLCacheUtils;
import com.ydl.ydlcommon.utils.log.LogHelper;
import com.ydl.ydlcommon.utils.remind.HttpErrorUtils;
import com.ydl.ydlcommon.view.dialog.CommonDialog;
import com.ydl.ydlcommon.view.dialog.ListDialog;
import com.ydl.ydlcommon.view.dialog.NormalDialog;
import com.yidianling.common.tools.ToastUtil;
import com.yidianling.im.api.bean.IMExpertBuild;
import com.yidianling.im.api.bean.IMRequestCallback;
import com.yidianling.im.api.event.BlackEvent;
import com.yidianling.im.bean.GetReportReason;
import com.yidianling.im.bean.RMBlackCall;
import com.yidianling.im.bean.RemoveHistory;
import com.yidianling.im.bean.Report;
import com.yidianling.im.bean.ReportWorry;
import com.yidianling.im.bean.SetBlackCall;
import com.yidianling.im.config.constants.ImConstants;
import com.yidianling.im.event.UpdateTabUnreadNumEvent;
import com.yidianling.im.helper.MsgReceiveHelper;
import com.yidianling.im.http.ImRetrofitApi;
import com.yidianling.im.preference.ImTempData;
import com.yidianling.im.router.ImIn;
import com.yidianling.im.session.extension.CustomAttachTipMsg;
import com.yidianling.im.session.extension.CustomAttachmentOrderStatus;
import com.yidianling.im.session.extension.CustomAttachmentPhoneCallSystemNotice;
import com.yidianling.im.session.extension.CustomRecommendExpertListMsg;
import com.yidianling.im.session.extension.CustomSystemTips;
import com.yidianling.im.ui.page.fragment.bean.ChatItemBean;
import com.yidianling.im.ui.widget.ChatTeamHisDialog;
import com.yidianling.uikit.business.session.helper.MessageListPanelHelper;
import com.yidianling.uikit.custom.bridge.IP2PCustomActionHandler;
import com.yidianling.uikit.custom.http.response.RecommendExpertBean;

import org.jetbrains.annotations.Nullable;
import org.json.JSONObject;

import java.util.ArrayList;
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;


/**
 * 聊天扩展功能  点击时间处理
 * Created by Wi1ls on 2016/9/23;
 */
public class P2PCustomActionHandlerImpl implements IP2PCustomActionHandler {

    private boolean notPrepared;
    private String toChatUsername;
    private DocInfo docInfo = new DocInfo();
    private Activity mActivity;
    private int blackStatus;
    private int userType;
    /***是否来自倾述页面*/
    public int isFromQingShu = 0;

    public P2PCustomActionHandlerImpl(String toChatUsername,
                                      IMExpertBuild expert) {
        setExpertInfo(toChatUsername, expert);
    }

    @Override
    public void setExpertInfo(String toChatUsername, IMExpertBuild expert) {
        blackStatus = Integer.valueOf(expert.shareData.blackStatus);
        this.toChatUsername = toChatUsername;

        docInfo.toUid = expert.shareData.toUid;
        docInfo.doctorId = expert.shareData.doctorId;
        docInfo.listenerId = expert.shareData.listenerId;
        docInfo.name = expert.shareData.doctorName;
        docInfo.title = expert.shareData.title;
        docInfo.is_online = expert.shareData.is_online;
        docInfo.isChatOnline = expert.shareData.isChatOnline;
        docInfo.cover = expert.shareData.cover;
        docInfo.desc = expert.shareData.desc;
        docInfo.url_share = expert.shareData.url_share;
        docInfo.price = expert.shareData.price;
        docInfo.unitTxt = expert.shareData.unitTxt;
        docInfo.url = expert.shareData.url;

        docInfo.hasAvailableListenOrder = expert.shareData.hasAvailableListenOrder;
        docInfo.listenOrderCommentStatus = expert.shareData.listenOrderCommentStatus;
        docInfo.listenOrderCommentUrl = expert.shareData.listenOrderCommentUrl;
        docInfo.listenOrderUrl = expert.shareData.listenOrderUrl;
        docInfo.listenOrderDesc = expert.shareData.listenOrderDesc;
        docInfo.listenOrderRemainTime = expert.shareData.listenOrderRemainTime;

        docInfo.urlTitle = expert.shareData.urlTitle;
        docInfo.blackStatus = expert.shareData.blackStatus;
        docInfo.orderid = expert.shareData.params.orderid;
        docInfo.is_first = expert.shareData.is_first;
        docInfo.listenerIsOpen = expert.shareData.listenerIsOpen;
        docInfo.tag1 = expert.shareData.tag1;

        docInfo.doctorBriefInfoFeedbackRate = expert.doctorBriefInfo.feedbackRate;
        docInfo.doctorBriefInfoFeedbackRateForShow = expert.doctorBriefInfo.feedbackRateForShow;
        docInfo.doctorBriefInfoHelpLong = expert.doctorBriefInfo.helpLong;
        docInfo.doctorBriefInfoOrderNum = expert.doctorBriefInfo.orderNum;
        docInfo.doctorBriefInfoSmallImage = expert.doctorBriefInfo.smallImage;

        docInfo.isFollowed = expert.shareData.isFollowed;
        docInfo.commentCounter = expert.commentCounter;
        docInfo.commentCounterUrl = expert.commentCounterUrl;
        if (docInfo.commentList == null) {
            docInfo.commentList = new ArrayList();
        }
        docInfo.commentList.clear();
        if (expert.commentList != null) {
            docInfo.commentList.addAll(expert.commentList);
        }
        this.notPrepared = false;
    }

    public P2PCustomActionHandlerImpl(String toChatUsername,
                                      String toName, String head) {
        this.toChatUsername = toChatUsername;
        docInfo.toUid = toChatUsername;
        docInfo.name = toName;
        docInfo.cover = head;
        this.notPrepared = false;
    }

    public P2PCustomActionHandlerImpl(ChatItemBean chatItemBean) {
        this.toChatUsername = String.valueOf(chatItemBean.getToUid());
        this.userType = chatItemBean.getUtype();
        this.notPrepared = true;

        docInfo.toUid = String.valueOf(chatItemBean.getToUid());
        docInfo.name = chatItemBean.getTitle();
        docInfo.cover = chatItemBean.getHead();
    }

    /**
     * 聊天室使用
     */
    public P2PCustomActionHandlerImpl() {

    }

    /**
     * 群聊使用
     */
    public P2PCustomActionHandlerImpl(String doctorId) {
        docInfo.doctorId = doctorId;
    }

    @Override
    public int getUserType() {
        return userType;
    }

    @Override
    public void setUserType(int userType) {
        this.userType = userType;
    }

    @Override
    public int getSelfUserType() {
        return ImIn.INSTANCE.getUserInfo().getUser_type();
    }

    /**
     * 发红包
     */
    @Override
    public void sendRedPacket(Activity activity) {
        ImIn.INSTANCE.sendRedPacketIntent(activity, toChatUsername, 44);
    }

    /**
     * 判定是否是今天第一次发送提醒上线通知，不是的话则不发消息通知|普通消息
     */
    @Override
    public void judgeSendRemindMsg(String sessionId) {
        if (!TextUtils.isEmpty(YDLCacheUtils.Companion.getRemindTime(sessionId))) {
            Long lastRemindTime = Long.parseLong(YDLCacheUtils.Companion.getRemindTime(sessionId));
            Long nowTime = System.currentTimeMillis();
            if ((nowTime - lastRemindTime) / 1000 / 24 / 3600 < 1) {
                ToastUtil.toastShort("已提醒");
                return;
            }
        } else {
            YDLCacheUtils.Companion.saveRemindTime(sessionId, String.valueOf(System.currentTimeMillis()));
        }

        IMMessage message = MessageBuilder.createTextMessage(sessionId, SessionTypeEnum.P2P, "您好，请尽快上线，我在等您");
        message.setStatus(MsgStatusEnum.success);
        CustomMessageConfig config = new CustomMessageConfig();
        config.enableUnreadCount = false;
        message.setConfig(config);
        ImIn.INSTANCE.getImService().createTextMessage(sessionId, "您好，请尽快上线，我在等您", new IMRequestCallback<Void>() {
            @Override
            public void onSuccess(@Nullable Void aVoid) {
            }

            @Override
            public void onFailed(int i) {
            }

            @Override
            public void onException(@Nullable Throwable throwable) {
            }
        });
        ToastUtil.toastShort("已提醒");
    }

    /**
     * 发送专家推荐列表自定义消息
     */
    @Override
    public void sendRecommendExpertListMessage(String sessionId, ArrayList<RecommendExpertBean> recommendExpertList, int type, boolean showExpertList) {

        CustomRecommendExpertListMsg customRecommendExpertListMsg = new CustomRecommendExpertListMsg(recommendExpertList, type, showExpertList);
        IMMessage message = MessageBuilder.createCustomMessage(sessionId, SessionTypeEnum.P2P, customRecommendExpertListMsg);
        message.setStatus(MsgStatusEnum.success);
        CustomMessageConfig config = new CustomMessageConfig();
        config.enableUnreadCount = false;
        message.setConfig(config);
        NIMClient.getService(MsgService.class).saveMessageToLocal(message, true);
    }

    /**
     * 跳转到专家主页
     */
    @Override
    public void toExpertHome(String doctorId, String name, String cover) {
        // 跳转到专家主页
        String junmpurl = ImIn.INSTANCE.getExpertHost() + doctorId;
        String share_title = name + "咨询工作室";
        String share_head = cover;
        String share_context = "";
        String share_url = ImIn.INSTANCE.getShareExpertHost() + doctorId;

        H5Params h5Params = new H5Params(junmpurl, null);
        if (!TextUtils.isEmpty(share_url)) {
            ShareData shareData1 = new ShareData(junmpurl, share_title, share_head, share_context);
            h5Params.setShareData(shareData1);
        }
        h5Params.setShowMenu(true);
        if (mActivity != null) {
            NewH5Activity.start(mActivity, h5Params);
        }
    }

    /**
     * 检查用户是否绑定手机
     */
    @Override
    public boolean isBindPhone(final Activity activity, String toUid) {
        //小壹特殊处理，没有绑定也可以和小壹聊天
        if (toUid.equals(ImConstants.KEFUXIAOYI)) {
            return true;
        }

        try {
            String phone = ImIn.INSTANCE.getUserInfo().getPhone();
            if ("".equals(phone) || phone == null) {
                NormalDialog.Builder builder = new NormalDialog.Builder(activity, "left", true);
                builder.setTitle("");
                builder.setMessage(ImConstants.BIND_PHONE);
                builder.setPositiveButton("果断绑定",
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                activity.startActivity(ImIn.INSTANCE.inputPhoneIntent(activity, ImConstants.BIND_PHONE_ACTION));
                                dialog.dismiss();
                            }
                        });
                builder.setNegativeButton("忍痛放弃",
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        });
                builder.create().show();
                return false;
            } else {
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public boolean HintMessageSend(final Activity activity, ReturnCallBack returnCallBack) {
        final boolean[] flag = {false};
        NormalDialog.Builder builder = new NormalDialog.Builder(activity, "left", true);
        builder.setTitle("");
        builder.setMessage(ImConstants.MESSAGE_IN_NUM);
        builder.setPositiveButton("确定",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        flag[0] = true;
                        returnCallBack.RetCallback();
                        dialog.dismiss();
                    }
                }).setNegativeButton("取消",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        flag[0] = false;
                        dialog.dismiss();
                    }
                });
        builder.create().show();
        return flag[0];
    }

    /**
     * 显示举报dialog
     */
    @Override
    public void showJubao(final Activity activity) {
        GetReportReason cmd = new GetReportReason();
        Disposable disposable = ImRetrofitApi.Companion.getImRetrofitApi().getReportReason(NetworkParamsUtils.getMaps(cmd))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(resp -> {
                    try {
                        if (resp.code != 0) {
                            ToastUtil.toastShort(resp.msg);
                            return;
                        }
                        LinkedTreeMap<String, String> reportReasonsmaps =
                                (LinkedTreeMap<String, String>) resp.data;
                        if (reportReasonsmaps == null) {
                            return;
                        }
                        List<Report> reports = new ArrayList<>();
                        for (Map.Entry<String, String> entry : reportReasonsmaps.entrySet()) {
                            Report report = new Report(entry.getKey(), entry.getValue());
                            reports.add(report);


                        }
                        report(activity, reports);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }, throwable -> HttpErrorUtils.Companion.handleError(activity, throwable));

    }

    @Override
    public void buryPoint(String eventName, JSONObject properties) {
        BuryPointUtils.buryPoint(eventName, properties);
    }

    /**
     * 发送自定义提醒消息
     */
    @Override
    public void sendCustomMsg() {
        CustomAttachTipMsg CustomAttachTipMsg = new CustomAttachTipMsg(ImConstants.FIRST_CHAT_TIP);
        IMMessage message = MessageBuilder.createCustomMessage(toChatUsername, SessionTypeEnum.P2P, CustomAttachTipMsg);
        NIMClient.getService(MsgService.class).sendMessage(message, false).setCallback(new RequestCallback<Void>() {
            @Override
            public void onSuccess(Void param) {

            }

            @Override
            public void onFailed(int code) {
                if (code == 7101) {
                    ToastUtil.toastLong(mActivity, "您已被对方拉黑!");
                } else if (code == 404) {
                    ToastUtil.toastLong(mActivity, "对象不见了!");
                } else {
                    UpLoadLogUtils.INSTANCE.upLoadLog("nim", code, "send message failed");
                }
            }

            @Override
            public void onException(Throwable exception) {

            }
        });
        MessageListPanelHelper.getInstance().notifyAddMessage(message);
    }

    @Override
    public void saveImTempData(String touid, String content) {
        if (touid == null || touid.equals("")) {
            return;
        }
        ImTempData.getInstance().addTempMsg(touid, content);
        EventBus.getDefault().post(new UpdateTabUnreadNumEvent());
    }

    @Override
    public String getImTempData(String touid) {
        return ImTempData.getInstance().getTempMsg(touid) == null ? "" : ImTempData.getInstance().getTempMsg(touid);
    }

    /**
     * 获取群聊历史记录dialog是否已显示过(0未提示，1已提示过)
     */
    @Override
    public void chatTeamHistoryTip(Activity activity) {
        if (!ImIn.INSTANCE.getChatTeamHisShow()) {
            //弹窗提示
            new ChatTeamHisDialog(activity).show();
        }
    }

    /**
     * 短时间内私聊次数过多，给予警示
     */
    @Override
    public void sendMsgToChatTip() {
//        CustomAttachChatTipMsg CustomAttachTipMsg = new CustomAttachChatTipMsg(getInfo().forbide_tip);
//        IMMessage message = MessageBuilder.createCustomMessage(toChatUsername, SessionTypeEnum.P2P, CustomAttachTipMsg);
//        message.setStatus(MsgStatusEnum.success);
//        MsgHelper.onMsgSend(message);

    }

    @Override
    public void h5ActivityStart(Context mActivity, String urlSuff, boolean isNeedFresh) {
        //跳转h5页面
        if (urlSuff == null) {
            ToastUtil.toastShort("参数错误");
            return;
        }
        String url = HttpConfig.Companion.getH5_URL() + urlSuff;

        H5Params h5Params = new H5Params(url, null);
        NewH5Activity.start(mActivity, h5Params);
    }

    @Override
    public void uploadSendMessageError(int errorCode) {
        UpLoadLogUtils.INSTANCE.upLoadLog("nim", errorCode, "send message failed");
    }

    /**
     * 举报
     */
    private void report(final Activity activity, final List<Report> reports) {

        final List<String> dialog_datas = new ArrayList<String>();
        for (Report report : reports) {
            dialog_datas.add(report.getContent());
        }

        int itemTextColor = Color.RED;
        ListDialog.Builder builder1 = new ListDialog.Builder(activity, dialog_datas, itemTextColor);
        builder1.SetLastStr("取消");
        builder1.SetLastButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        builder1.SetOnItemClickLister(new ListDialog.Builder.OnItemClickLister() {
            @Override
            public void onItemClick(final Dialog dialog, View view, int position) {
                ReportWorry cmd = new ReportWorry(Integer.valueOf(ImIn.INSTANCE.getUserInfo().getUid()), Integer.valueOf(reports.get(position).getReport_id()), 0, reports.get(position).getContent(), 2);
                ImRetrofitApi.Companion.getImRetrofitApi().reportWorry(NetworkParamsUtils.getMaps(cmd))
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(resp -> {
                            if (resp.code == 0) {
                                ToastUtil.toastShort(activity, "举报成功");
                            } else {
                                ToastUtil.toastShort(activity, resp.msg);
                            }
                            dialog.dismiss();
                        }, throwable -> {
                            HttpErrorUtils.Companion.handleError(activity, throwable);
                            dialog.dismiss();
                        });

            }

            @Override
            public void onItemLongClick(Dialog dialog, View view, int position) {

            }
        });
        builder1.create().show();
    }


    @Override
    public DocInfo getInfo() {
        return docInfo == null ? new DocInfo() : docInfo;
    }

    @Override
    public Boolean isNotPrepare() {
        return notPrepared;
    }


    @Override
    public boolean deleteMessage(IMMessage message) {
        if (message.getAttachment() instanceof CustomRecommendExpertListMsg) {
            //删除每次加载的消息记录中推荐专家列表消息
            return true;
        } else if (message.getAttachment() instanceof CustomSystemTips) {
            //过滤掉所有不符合条件的后端发送的系统消息
            if (((CustomSystemTips) message.getAttachment()).getHiddenApp() == 1
                    || ((CustomSystemTips) message.getAttachment()).getHiddenApp() == 3) {
                return true;
            }
        } else if (message.getAttachment() instanceof CustomAttachmentOrderStatus) {
            //已开启私聊 && 已经超过一个小时
            if (((CustomAttachmentOrderStatus) message.getAttachment()).isStartChatMessage()
                    && isMessageTimeOut(message)) {
                return true;
            }
        } else if (message.getAttachment() instanceof CustomAttachmentPhoneCallSystemNotice) {
            //(留言 消息 || 邀请开通 消息) && 已经超过一小时
            if ((((CustomAttachmentPhoneCallSystemNotice) message.getAttachment()).isLeaveMessage()
                    || ((CustomAttachmentPhoneCallSystemNotice) message.getAttachment()).isInviteMessage())
                    && isMessageTimeOut(message)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 消息是否超过一小时
     *
     * @param message
     * @return true 超过 false 未超过
     */
    private boolean isMessageTimeOut(IMMessage message) {
        return (System.currentTimeMillis() - message.getTime()) > 3600 * 1000;
    }

    @Override
    public void setDoctorStatus(int status) {
        if (docInfo != null) {
            docInfo.isChatOnline = status;
        }
    }

    @Override
    public void setDoctorBusyNum(int num) {
        if (docInfo != null) {
            docInfo.busyTotal = num;
        }
    }

    @Override
    public void setmActivity(Activity mActivity) {
        this.mActivity = mActivity;
    }

    @Override
    public Activity getmActivity() {
        return mActivity;
    }


    @Override
    public void clickMoreIcon() {
        if (mActivity == null || mActivity.isFinishing()) {
            return;
        }
        List<String> list = new ArrayList<>();
        if (ImConstants.KEFUXIAOYI.equals(toChatUsername) || "4108805".equals(toChatUsername)) {
            list.add("历史聊天记录");
            list.add("客服热线");
        } else {
            list.add("投诉反馈");
            if (blackStatus == 1) {
                list.add("拉黑");
            } else if (blackStatus == 2) {
                list.add("取消拉黑");
            }
            if (userType == 1) {
                list.add("ta的主页");
            }
            if (userType == 2) {
                list.add("访问专家主页");
            }
            list.add("历史聊天记录");
            list.add("删除聊天记录");
        }
        ListDialog.Builder dialog = new ListDialog.Builder(mActivity, list, 0);
        list.add("取消");

        dialog.create().show();

        dialog.SetOnItemClickLister(new ListDialog.Builder.OnItemClickLister() {
            @Override
            public void onItemClick(Dialog dialog, View view, int position) {
                LogHelper.Companion.getInstance().writeLogSync(String.format("聊天界面：%s", list.get(position)));
                switch (list.get(position)) {
                    case "投诉反馈":
                        startFeedback(mActivity);
                        break;
                    case "返回首页":
                        ImIn.INSTANCE.mainIntent(mActivity, 0);
                        break;
                    case "客服热线":
                        showCallDialog();
                        break;
                    case "访问专家主页":
                        skip2ExpertHome();
                        break;
                    case "历史聊天记录":
                        historyMsg();
                        break;
                    case "拉黑":
                        setBlack();
                        break;
                    case "取消拉黑":
                        rmBlack();
                        break;
                    case "删除聊天记录":
                        deleteChatHistory();
                        break;
                    case "ta的主页":
                        showUserHome();
                        break;
                    case "取消":
                        break;
                }
                dialog.dismiss();
            }

            @Override
            public void onItemLongClick(Dialog dialog, View view, int position) {

            }
        });
    }

    /**
     * 删除聊天记录
     */
    private void deleteChatHistory() {
        CommonDialog dialog = CommonDialog.create(mActivity);
        dialog.setMessage("确定删除与ta的聊天记录？");
        dialog.setCancelAble(true);
        dialog.setLeftOnclick("再考虑下", v -> dialog.dismiss());
        dialog.setRightClick("立即删除", v -> {
            LoadingDialogFragment loadingDialog = LoadingDialogFragment.Companion.newInstance("正在删除");
            loadingDialog.show(((AppCompatActivity) mActivity).getSupportFragmentManager(), null);
            RemoveHistory cmd = new RemoveHistory();
            cmd.toUid = getInfo().toUid;
            cmd.type = 1;
            Disposable disposable = ImRetrofitApi.Companion.getImRetrofitApi().rmHistory(NetworkParamsUtils.getMaps(cmd))
                    .subscribeOn(Schedulers.io())
                    .compose(RxUtils.INSTANCE.resultData())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(objectBaseResponse -> {
                        loadingDialog.hide();
                        ToastUtil.toastShort("聊天记录已删除");
                        NIMClient.getService(MsgService.class).clearChattingHistory(cmd.toUid, SessionTypeEnum.P2P);
                        MessageListPanelHelper.getInstance().notifyClearMessages(cmd.toUid);

                    }, throwable -> {
                        loadingDialog.hide();
                        HttpErrorUtils.Companion.handleError(mActivity, throwable);
                    });
        });
        dialog.show();
    }

    private void setBlack() {
        SetBlackCall cmd = new SetBlackCall(toChatUsername);
        Disposable disposable = ImRetrofitApi.Companion.getImRetrofitApi().setBlackCall(NetworkParamsUtils.getMaps(cmd))
                .subscribeOn(Schedulers.io())
                .compose(RxUtils.INSTANCE.resultData())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(objectBaseResponse -> {
                    ToastUtil.toastShort("已加入黑名单");
                    BlackEvent changeEvent = new BlackEvent(true);
                    EventBus.getDefault().post(changeEvent);
                    blackStatus = 2;
                }, throwable -> {
                    HttpErrorUtils.Companion.handleError(mActivity, throwable);
                });
    }


    private void rmBlack() {
        RMBlackCall cmd = new RMBlackCall(toChatUsername);
        Disposable disposable = ImRetrofitApi.Companion.getImRetrofitApi().rmBlackCall(NetworkParamsUtils.getMaps(cmd))
                .subscribeOn(Schedulers.io())
                .compose(RxUtils.INSTANCE.resultData())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(objectBaseResponse -> {
                    ToastUtil.toastShort("已移出黑名单");
                    BlackEvent changeEvent = new BlackEvent(true);
                    EventBus.getDefault().post(changeEvent);
                    blackStatus = 1;
                }, throwable -> {
                    HttpErrorUtils.Companion.handleError(mActivity, throwable);
                });
    }

    //    @Override
//    protected void notifyChange() {
//        super.notifyChange();
//        EventBus.getDefault().post(new NotifyRecentListChangeEvent(1));
//    }

    /**
     * 跳转到专家主页
     */
    private void skip2ExpertHome() {
        // 跳转到专家主页
        if (docInfo.doctorId != null) {
            String junmpurl = ImIn.INSTANCE.getExpertHost() + docInfo.doctorId;
            String share_title = docInfo.name + "咨询工作室";
            String share_head = docInfo.cover;
            String share_context = "";
            String share_url = ImIn.INSTANCE.getShareExpertHost() + docInfo.doctorId;

            H5Params h5Params = new H5Params(junmpurl, null);
            if (!TextUtils.isEmpty(share_url)) {
                ShareData shareData1 = new ShareData(junmpurl, share_title, share_head, share_context);
                h5Params.setShareData(shareData1);
            }
            h5Params.setShowMenu(true);
            if (mActivity != null) {
                NewH5Activity.start(mActivity, h5Params);
            }
        }
    }

    @Override
    public void jump() {
        //预约评价  微问诊评价  倾诉评价

        H5Params h5Params = new H5Params(ImConstants.Companion.getYYPJ() + docInfo.orderid, null);
        NewH5Activity.start(mActivity, h5Params);
    }

    @Override
    public void h5Video() {
        H5Params h5Params = new H5Params(ImConstants.Companion.getH5VIDEO_INFO(), null);
        NewH5Activity.start(mActivity, h5Params);
    }


    /**
     * 判断是否需要发送自定义消息
     *
     * @param isCheckFrom 是否需要检查是否从倾述流程进入
     */
    @Override
    public void isNeedSendMsg(boolean isCheckFrom) {
        //从倾述进入私聊
        //未上线前提下：
        // 未留言，自动发送留言
        //已留言：不处理
        if (!isCheckFrom || isFromQingShu == 1) {//是从倾述进入
            //判断当前是否在线
            if (docInfo.is_online == 2) {//离线
                //判断今天是否有给老师留过言
                String localTime = YDLCacheUtils.Companion.getNoticeSendTime(YdlCommonRouterManager.INSTANCE.getYdlCommonRoute().getUid() + "", docInfo.toUid);
                if (!StringUtils.compareTime(localTime)) {//不是同一天
                    //自动发送老师现在不在，请留言的提示
                    CustomAttachmentPhoneCallSystemNotice systemNotice = new CustomAttachmentPhoneCallSystemNotice("2");
                    IMMessage message = MessageBuilder.createCustomMessage(toChatUsername, SessionTypeEnum.P2P, systemNotice);
                    message.setStatus(MsgStatusEnum.success);
                    CustomMessageConfig config = new CustomMessageConfig();
                    config.enableUnreadCount = false;
                    message.setConfig(config);
                    YDLCacheUtils.Companion.saveNoticeSendTime(YdlCommonRouterManager.INSTANCE.getYdlCommonRoute().getUid() + "", getInfo().toUid, System.currentTimeMillis() + "");
                    NIMClient.getService(MsgService.class).saveMessageToLocalEx(message, false, message.getTime()).setCallback(new RequestCallback<Void>() {
                        @Override
                        public void onSuccess(Void aVoid) {
                        }

                        @Override
                        public void onFailed(int i) {
                            YDLCacheUtils.Companion.saveNoticeSendTime(YdlCommonRouterManager.INSTANCE.getYdlCommonRoute().getUid() + "", getInfo().toUid, "");
                        }

                        @Override
                        public void onException(Throwable throwable) {
                            YDLCacheUtils.Companion.saveNoticeSendTime(YdlCommonRouterManager.INSTANCE.getYdlCommonRoute().getUid() + "", getInfo().toUid, "");

                        }
                    });
                }
            }
        }
    }


    /**
     * 倾诉
     */
    @Override
    public void confide() {
        if (1 == docInfo.listenerIsOpen && !TextUtils.isEmpty(docInfo.doctorId) && !docInfo.doctorId.equals("0")) {
            H5Params h5Params = new H5Params(ImConstants.Companion.getYTZDETAIL() + docInfo.doctorId + "?id=" + docInfo.listenerId + "&toConfide=1", null);
            String share_title = "壹点灵电话倾诉";
            String share_context = "壹点灵电话倾诉";
            ShareData shareData1 = new ShareData(HttpConfig.Companion.getMH5_URL() + "listen", share_title, null, share_context);
            h5Params.setShareData(shareData1);
            NewH5Activity.start(mActivity, h5Params);
        } else {
            if (userType == 2) {//专家
                //发送邀请老师的通知
                CustomAttachmentPhoneCallSystemNotice systemNotice = new CustomAttachmentPhoneCallSystemNotice("1");
                IMMessage message = MessageBuilder.createCustomMessage(toChatUsername, SessionTypeEnum.P2P, systemNotice);
                message.setStatus(MsgStatusEnum.success);
                CustomMessageConfig config = new CustomMessageConfig();
                config.enableUnreadCount = false;
                message.setConfig(config);
                NIMClient.getService(MsgService.class).saveMessageToLocalEx(message, false, message.getTime());
                MessageListPanelHelper.getInstance().notifyAddMessage(message);
            } else {
                ToastUtil.toastShort("对方还未开通该服务");
            }
        }
    }

    /**
     * 帮助
     */
    @Override
    public void help() {

        H5Params h5Params = new H5Params("http://static.yidianling.com/mobile/html/chat_help_app.html", null);
        h5Params.setShowMenu(true);
        NewH5Activity.start(mActivity, h5Params);
    }

    @Override
    public void makeColections(String toUid) {
        H5Params h5Params = new H5Params(HttpConfig.Companion.getMH5_URL() + "zx/chooseCounselor?toUid=" + toUid, null);
        NewH5Activity.start(mActivity, h5Params);
    }

    @Override
    public void clear(String accid) {
        MsgReceiveHelper.updateNum(accid, 0);
    }

    @Override
    public void put(Activity a) {
        //添加activity
        ActivityManager.Companion.getInstance().addStack(a);
    }

    @Override
    public void showHelp(String url) {
        H5Params h5Params = new H5Params(url, null);
        NewH5Activity.start(mActivity, h5Params);

    }

    @Override
    public void resumeUm(Activity activity) {
        MobclickAgent.onResume(activity);
    }

    @Override
    public void pauseUm(Activity activity) {
        MobclickAgent.onPause(activity);
    }

    private void historyMsg() {
        H5Params h5Params = new H5Params(HttpConfig.Companion.getH5_URL() + "consult/history2?toUid=" + toChatUsername, null);
        h5Params.setShowMenu(true);
        NewH5Activity.start(mActivity, h5Params);
    }

    @Override
    public void showDingdan(String url) {
        if (url.contains("book")) {

            H5Params h5Params = new H5Params(url + "orderid=" + docInfo.orderid, null);
            h5Params.setShowMenu(true);
            NewH5Activity.start(mActivity, h5Params);
        } else {

            H5Params h5Params = new H5Params(url, null);
            NewH5Activity.start(mActivity, h5Params);
        }
    }

    @Override
    public void showZhuanjPage() {
        skip2ExpertHome();
    }

    /**
     * 跳转用户主页
     */
    @Override
    public void showUserHome() {
        if (ImIn.INSTANCE.membersIntent(mActivity, docInfo.toUid) != null) {
            mActivity.startActivity(ImIn.INSTANCE.membersIntent(mActivity, docInfo.toUid));
        }
    }


    private void showCallDialog() {
        try {
            final String tel = PlatformDataManager.INSTANCE.getRam().getGlobalInfo() == null ? "400-765-1010" : PlatformDataManager.INSTANCE.getRam().getGlobalInfo().info.tel;

            String con = "\n400-765-1010\n早8:30-凌晨2:00";

            if (PlatformDataManager.INSTANCE.getRam().getGlobalInfo() != null && PlatformDataManager.INSTANCE.getRam().getGlobalInfo().info != null) {
                con = PlatformDataManager.INSTANCE.getRam().getGlobalInfo().info.tel + "\n" + PlatformDataManager.INSTANCE.getRam().getGlobalInfo().info.work_time;
            }

            new CommonDialog(mActivity)
                    .setTitle("欢迎致电壹点灵客服热线")
                    .setMessage(con)
                    .setLeftOnclick("取消", v1 -> {

                    }).setRightClick("拨打", v12 -> {
                Intent phoneIntent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + tel));
                mActivity.startActivity(phoneIntent);
            }).show();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void popCallDialog(Context context) {
        showCallDialog();
    }

    @Override
    public void startFeedback(Context context) {
        ImIn.INSTANCE.feedBackIntent((Activity) context);
    }

    @Override
    public void startHelp(Context context) {

        H5Params params = new H5Params(HttpConfig.Companion.getH5_URL() + "help/", "");
        params.setShowMenu(true);
        NewH5Activity.start(context, params);
    }
}
