P2PCustomActionHandlerImpl.java 37.8 KB
Newer Older
konghaorui committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
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 android.support.v7.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;
konghaorui committed
44
import com.yidianling.im.api.bean.IMExpertBuild;
konghaorui committed
45
import com.yidianling.im.api.bean.IMRequestCallback;
konghaorui committed
46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
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;
64
import com.yidianling.im.ui.page.fragment.bean.ChatItemBean;
konghaorui committed
65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88
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 {

89
    private boolean notPrepared;
konghaorui committed
90 91 92 93 94 95 96 97 98
    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) {
99 100 101 102
        setExpertInfo(toChatUsername,expert);
    }
    
    public void setExpertInfo(String toChatUsername,IMExpertBuild expert) {
konghaorui committed
103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134
        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;
徐健 committed
135
        docInfo.doctorBriefInfoFeedbackRateForShow = expert.doctorBriefInfo.feedbackRateForShow;
konghaorui committed
136 137 138
        docInfo.doctorBriefInfoHelpLong = expert.doctorBriefInfo.helpLong;
        docInfo.doctorBriefInfoOrderNum = expert.doctorBriefInfo.orderNum;
        docInfo.doctorBriefInfoSmallImage = expert.doctorBriefInfo.smallImage;
139

140
        docInfo.isFollowed = expert.shareData.isFollowed;
141 142 143 144 145 146
        docInfo.commentCounter = expert.commentCounter;
        docInfo.commentCounterUrl = expert.commentCounterUrl;
        if (docInfo.commentList == null) {
            docInfo.commentList = new ArrayList();
        }
        docInfo.commentList.clear();
147 148 149
        if (expert.commentList != null) {
            docInfo.commentList.addAll(expert.commentList);
        }
150
        this.notPrepared = false;
konghaorui committed
151 152 153 154 155 156 157 158
    }

    public P2PCustomActionHandlerImpl(String toChatUsername,
                                      String toName, String head) {
        this.toChatUsername = toChatUsername;
        docInfo.toUid = toChatUsername;
        docInfo.name = toName;
        docInfo.cover = head;
159 160 161 162 163 164 165 166 167 168 169
        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();
konghaorui committed
170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201
    }

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

    }

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

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

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

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

    //发红包
    @Override
    public void sendRedPacket(Activity activity) {
//        Bundle bundle = new Bundle();
//        bundle.putString("to_uid",toChatUsername);
//        ImIn.INSTANCE.SendRedPacketActivity(activity,bundle,44);
konghaorui committed
202
        ImIn.INSTANCE.sendRedPacketIntent(activity, toChatUsername,44);
konghaorui committed
203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223
    }

    //判定是否是今天第一次发送提醒上线通知,不是的话则不发消息通知|普通消息
    @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);
konghaorui committed
224
        ImIn.INSTANCE.getImService().createTextMessage(sessionId, "您好,请尽快上线,我在等您", new IMRequestCallback<Void>() {
konghaorui committed
225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242
            @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) {
243

konghaorui committed
244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276
        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);
    }

    //跳转到专家主页
    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) {
        //小壹特殊处理,没有绑定也可以和小壹聊天
277
        if (toUid.equals(ImConstants.KEFUXIAOYI)) {
konghaorui committed
278 279 280 281 282 283 284 285 286 287 288 289 290
            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) {
291
                                activity.startActivity(ImIn.INSTANCE.inputPhoneIntent(activity, ImConstants.BIND_PHONE_ACTION));
konghaorui committed
292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482
                                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) {
konghaorui committed
483
                                ToastUtil.toastShort(activity, "举报成功");
konghaorui committed
484 485
                                dialog.dismiss();
                            } else {
konghaorui committed
486
                                ToastUtil.toastShort(activity, resp.msg);
konghaorui committed
487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512
                                dialog.dismiss();
                            }
                        }, throwable -> {
                            HttpErrorUtils.Companion.handleError(activity, throwable);
                            dialog.dismiss();
                        });

            }

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

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

    private List<String> list = new ArrayList<>();
//    ChooseListDialogFragment chooseListDialogFragment_ = ChooseListDialogFragment_.builder().build();


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

513 514 515 516 517
    @Override
    public Boolean isNotPrepare() {
        return notPrepared;
    }

konghaorui committed
518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587

    @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.clear();
588
        if (ImConstants.KEFUXIAOYI.equals(toChatUsername) || "4108805".equals(toChatUsername)) {
konghaorui committed
589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625
            list.add("历史聊天记录");
//            list.add("返回首页");
            list.add("客服热线");
        } else {
            list.add("投诉反馈");
            if (blackStatus == 1) {
                list.add("拉黑");
            } else if (blackStatus == 2) {
                list.add("取消拉黑");
            }
//            list.add("返回首页");
            if (userType == 1) {
                list.add("ta的主页");
            }
            if (userType == 2)
                list.add("访问专家主页");
            list.add("历史聊天记录");
            list.add("删除聊天记录");
        }
        ListDialog.Builder builderm = new ListDialog.Builder(mActivity, list, 0);
        builderm.SetLastStr("取消");
        builderm.SetLastButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        builderm.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);
                        dialog.dismiss();
                        break;
                    case "返回首页":
konghaorui committed
626
                        ImIn.INSTANCE.mainIntent(mActivity, 0);
konghaorui committed
627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924
                        dialog.dismiss();
                        break;
                    case "客服热线":
                        showCallDialog();
                        dialog.dismiss();
                        break;
                    case "访问专家主页":
                        skip2ExpertHome();
                        dialog.dismiss();
                        break;
                    case "历史聊天记录":
                        historyMsg();
                        dialog.dismiss();
                        break;
                    case "拉黑":
                        setBlack();
                        dialog.dismiss();
                        break;
                    case "取消拉黑":
                        rmBlack();
                        dialog.dismiss();
                        break;
                    case "删除聊天记录":
                        deleteChatHistory();
                        dialog.dismiss();
                        break;
                    case "ta的主页":
                        showUserHome();
                        dialog.dismiss();
                        break;
                }
            }

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

            }
        });
        builderm.create().show();


    }

    //删除聊天记录
    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() {//跳转到专家主页
        // 跳转到专家主页
        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 {
925
            final String tel = PlatformDataManager.INSTANCE.getRam().getGlobalInfo() == null ? "400-765-1010" : PlatformDataManager.INSTANCE.getRam().getGlobalInfo() .info.tel;
konghaorui committed
926

927
            String con = "\n400-765-1010\n早8:30-凌晨2:00";
konghaorui committed
928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953

            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) {
konghaorui committed
954
        ImIn.INSTANCE.feedBackIntent((Activity) context);
konghaorui committed
955 956 957 958 959 960 961 962 963 964
    }

    @Override
    public void startHelp(Context context) {
        
        H5Params params = new H5Params(HttpConfig.Companion.getH5_URL() + "help/", "");
        params.setShowMenu(true);
        NewH5Activity.start(context, params);
    }
}