package com.ydl.js;


import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.text.TextUtils;
import android.util.Log;

import com.alibaba.android.arouter.launcher.ARouter;
import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.ydl.confide.api.IConfideService;
import com.ydl.confide.event.ChangeAnotherExpertEvent;
import com.ydl.js.bean.TimeDataBean;
import com.ydl.js.http.JsHttpImpl;
import com.ydl.js.moduler.service.JsImpl;
import com.ydl.media.audio.AudioPlayer;
import com.ydl.media.view.PlayerFloatHelper;
import com.ydl.webview.H5JsBean;
import com.ydl.webview.H5Params;
import com.ydl.webview.NewH5Activity;
import com.ydl.ydl_router.manager.YDLRouterManager;
import com.ydl.ydlcommon.base.config.HttpConfig;
import com.ydl.ydlcommon.modular.ModularServiceManager;
import com.ydl.ydlcommon.modular.ModularServiceManagerKt;
import com.ydl.ydlcommon.router.IYDLRouterConstant;
import com.ydl.ydlcommon.router.YdlCommonOut;
import com.ydl.ydlcommon.utils.ActivityManager;
import com.ydl.ydlcommon.utils.ImageUtil;
import com.ydl.ydlcommon.utils.remind.ToastHelper;
import com.ydl.ydlcommon.view.dialog.YDLShareDialog;
import com.yidianling.common.tools.LogUtil;
import com.yidianling.common.tools.ToastUtil;
import com.yidianling.consultant.api.IConsultantService;
import com.yidianling.im.api.event.CloseBottomWebviewEvent;
import com.yidianling.im.api.service.IImService;
import com.yidianling.user.api.bean.UserResponseBean;
import com.yidianling.user.api.service.IAppService;
import com.yidianling.user.api.service.IUserService;
import com.yidianling.ydl_pay.common.CommonPayDialog;
import com.yidianling.ydl_pay.pay.PayActivity;
import com.yidianling.ydl_pay.pay.PayParams;

import org.jetbrains.annotations.Nullable;

import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

import de.greenrobot.event.EventBus;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

/**
 * webview 点击事件监听 抽象类
 * Created by harvie on 2017/7/4 0004.
 */
public class NewH5_WVClickAbstractListener implements NewH5_WebViewClientClickListener {

    //上次点击时间
    private long lastClickTime = 0L;
    private static final int FAST_CLICK_DELAY_TIME = 500;  // 快速点击间隔

    public Activity mActivity;
    private OptionsPickerView<String> pvOptions;

    public NewH5_WVClickAbstractListener(Activity activity) {
        this.mActivity = activity;
    }

    /**
     * 打开h5页面
     *
     * @param params
     */
    @Override
    public void openH5(H5JsBean.H5JsCmd.Params params) {
        LogUtil.d("openH5 params: " + params.toString());
        H5Params h5Params = new H5Params(params.getUrl(), null);
        h5Params.setShareData(params.getShare());
        h5Params.setShowMenu(params.getDot_flag());
        NewH5Activity.start(mActivity, h5Params);
    }

    @Override
    public void courseList() {
        LogUtil.d("course_list");
        YDLRouterManager.Companion.router(IYDLRouterConstant.ROUTER_BASE);
    }

    @Override
    public void activeDetail(String id) {
        LogUtil.d("active_detail");
        try {
           JsModularService.Companion.getIDynamicService().startTrendsDetail(mActivity, Integer.parseInt(id), false, false, false, false, 0);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 小壹
     */
    @Override
    public void contactYi() {
        LogUtil.d("contactYi");
        try {
           JsModularService.Companion.getImService().startP2PSession(mActivity, -1, "14", "14", "客服小壹", "14");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 课程专属客服
     */
    @Override
    public void contactCourseCustomerService() {
        try {
            JsModularService.Companion.getImService().startP2PSession(mActivity, -1, "4108805", "4108805", "课程小助手-壹壹", "4108805");
        } catch (Exception e) {
        }
    }

    /**
     * 跳转话题详情
     *
     * @param topic_id
     */
    @Override
    public void openTopicDetail(String topic_id) {
        LogUtil.d("OpenTopicDetail");
        try {
            Intent intents = JsModularService.Companion.getIDynamicService().topicDetailIntent(mActivity, false, topic_id);
            mActivity.startActivity(intents);
        } catch (Exception e) {
        }
    }

    /**
     * 会员主页
     *
     * @param id
     */
    @Override
    public void openMember(String id) {
        LogUtil.d("OpenMember");
        try {
            Intent intentm = JsModularService.Companion.getIDynamicService().membersIntent(mActivity, id);
            mActivity.startActivity(intentm);
        } catch (Exception e) {
        }
    }

    /**
     * 跳转发布动态
     */
    @Override
    public void sendTrend() {
        LogUtil.d("SendTrend");
        try {
            Intent intenta = JsModularService.Companion.getIDynamicService().publishTrendIntent(mActivity);
            mActivity.startActivity(intenta);
        } catch (Exception e) {
        }
    }

    /**
     * 发送测试题到动态
     *
     * @param cover1
     * @param title1
     * @param purl1
     * @param share_url1
     */
    @Override
    public void sendResultTrend(final String cover1, final String title1, final String purl1, final String share_url1) {
        LogUtil.d("SendResultTrend");
        mActivity.runOnUiThread(() -> {
            YDLShareDialog dialog = YDLShareDialog.Companion.style1(mActivity, title1, share_url1, title1, cover1);
            dialog.setCallBack(type -> {
                if (1 == type) {
                    if (JsModularService.Companion.getIUserService().loginByOneKeyLogin(mActivity, true)) {
                        //跳转到发布页面
                        try {
                            Intent intentp = JsModularService.Companion.getIDynamicService().publishTrendIntent(mActivity, purl1, cover1, title1);
                            mActivity.startActivity(intentp);
                        } catch (Exception e) {
                        }
                    }
                }
            });
            dialog.show(mActivity.getFragmentManager(), "lose");
        });
    }

    /**
     * 跳转选择用户界面发送消息
     */
    @Override
    public void sendInfo(H5JsBean.H5JsCmd.Params params) {
        LogUtil.d("SendInfo");
        try {
            Intent intent = JsModularService.Companion.getITestsApiService()
                    .getSelectConversationActivityIntent(mActivity, 1, params.getShare().getTitle(),
                            params.getShare().getCover(), params.getId(), params.getUrl(),
                            params.getShare().getShare_url());
            mActivity.startActivity(intent);
        } catch (Exception e) {
        }
    }

    /**
     * 打开专家搜索列表
     *
     * @param params
     */
    @Override
    public void searchList(H5JsBean.H5JsCmd.Params params) {
        try {
            ModularServiceManager.INSTANCE.provide(IConsultantService.class).startExpertSearchActivity(mActivity, "0", "", 0);
        } catch (Exception e) {
        }
    }

    /**
     * 专家主页
     *
     * @param params
     */
    @Override
    public void openExpertsHome(H5JsBean.H5JsCmd.Params params) {
        LogUtil.d("OpenExpertsHome");
        openH5(params);
    }


    /**
     * 开始测试
     */
    @Override
    public void openTest(H5JsBean.H5JsCmd.Params params) {
        LogUtil.d("OpenTest");
        openH5(params);
    }

    /**
     * 私聊
     *
     * @param id
     * @param toUid
     * @param canTalk
     * @param accessToken
     */
    @Override
    public void chat(int id, int toUid, int canTalk, String accessToken, int isFromQingShu, boolean closeReplaceChat) {
        LogUtil.d("chat");
        if ((toUid + "").equals("14")) {
            //找客服私聊不需要积分
            contactYi();
        } else {
            try {
                if (closeReplaceChat) {
                    ModularServiceManager.INSTANCE.provide(IImService.class)
                            .startChatCloseReplaceChat(mActivity, String.valueOf(toUid));
                } else {

                    ModularServiceManager.INSTANCE.provide(IImService.class)
                            .startChat(mActivity, String.valueOf(toUid), 0x001, canTalk, isFromQingShu, false);
                }
            } catch (Exception e) {
            }
        }
    }

    /**
     * 跳转私聊并发送消息
     *
     * @param id
     * @param toUid
     * @param canTalk
     * @param accessToken
     * @param isFromQingShu
     */
    @Override
    public void chatSendMessage(int id, int toUid, int canTalk, String accessToken, int isFromQingShu) {
        if (toUid == 0) {
            ToastUtil.toastShort("参数错误，请刷新页面后重试");
            return;
        }
        try {
            ModularServiceManager.INSTANCE.provide(IImService.class).createTextMessage(String.valueOf(toUid), "你好，我想找你倾诉，请尽快上线私聊我，我在等你。", new com.yidianling.im.api.bean.IMRequestCallback<Void>() {
                @Override
                public void onSuccess(@Nullable Void aVoid) {

                }

                @Override
                public void onFailed(int i) {
                    String message = "发送失败";
                    if (i == 7101) {
                        message = "您已被对方拉黑！";
                    }
                    ToastUtil.toastShort(message);
                }

                @Override
                public void onException(@Nullable Throwable throwable) {
                    ToastUtil.toastShort("发送异常");
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            ModularServiceManager.INSTANCE.provide(IImService.class)
                    .startChat(mActivity, String.valueOf(toUid), 0x001, canTalk, 0, false);
        } catch (Exception e) {
        }
    }

    //群聊
    @Override
    public void chatTeam(int tid, int doctorId) {
        LogUtil.d("chatTeam");
        //群聊直播
        Log.e("js", "群聊直播---------");
        if (tid == 0) {
            ToastUtil.toastShort("群信息有误，请联系客服");
            return;
        }
        JsModularService.Companion.getImService().startTeamSession(mActivity, tid + "",doctorId + "");
    }

    /**
     * 跳转登录
     */
    @Override
    public void jumpLogin(H5JsBean.H5JsCmd.Params jsData) {
        if (mActivity != null) {
            if (mActivity instanceof NewH5Activity) {
                ((NewH5Activity) mActivity).successPage = jsData.getSourceUrl();
            }
            JsModularService.Companion.getIUserService().loginByOneKeyLogin(mActivity, true);
        }
    }

    /**
     * Fm详情
     *
     * @param id
     */
    @Override
    public void openFmDetail(int id) {
        LogUtil.d("OpenFmDetail");
        //电台播放
        try {
            Intent intent = JsModularService.Companion.getIFMService().fmDetailIntent(mActivity, id);
            mActivity.startActivity(intent);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void openArticle() {
        LogUtil.d("OpenArticle");
        YDLRouterManager.Companion.router(IYDLRouterConstant.ROUTER_ARTICLE_LIST);
    }

    @Override
    public void openFmList() {
        LogUtil.d("OpenFmList");
        //电台播放
        try {
            Intent intent = JsModularService.Companion.getIFMService().fmListIntent(mActivity);
            mActivity.startActivity(intent);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void sendSubscriptionTimeMessage(String to_uid) {
        LogUtil.d("sendSubSriptTimeMessage");

        try {
            ModularServiceManager.INSTANCE.provide(IImService.class).sendSubscriptionTimeMessage(to_uid, "请尽快添加可预约时间", new com.yidianling.im.api.bean.IMRequestCallback<Void>() {
                @Override
                public void onSuccess(@Nullable Void aVoid) {
                    if (mActivity instanceof NewH5Activity) {
                        ((NewH5Activity) mActivity).dismissProgressDialog();
                    }
                }

                @Override
                public void onFailed(int i) {
                    if (mActivity instanceof NewH5Activity) {
                        ((NewH5Activity) mActivity).dismissProgressDialog();
                    }
                    String message = "发送失败";
                    if (i == 7101) {
                        message = "您已被对方拉黑！";
                    }
                    ToastHelper.Companion.show(message);
                }

                @Override
                public void onException(@Nullable Throwable throwable) {
                    if (mActivity instanceof NewH5Activity) {
                        ((NewH5Activity) mActivity).dismissProgressDialog();
                    }
                    ToastHelper.Companion.show("发送异常");
                }
            });
        } catch (Exception e) {
        }

        try {
            ModularServiceManager.INSTANCE.provide(IImService.class)
                    .startChat(mActivity, to_uid, 0x001, 0, 0, false);
        } catch (Exception e) {
        }
    }


    @Override
    public void pay(H5JsBean.H5JsCmd.Params jsData) {
        LogUtil.d("pay");
        PayParams payParams = new PayParams();
        payParams.setPayId(jsData.getPayId());
        payParams.setNeedPay(Float.valueOf(jsData.getMoney()));
        payParams.setTitle("预约咨询");
        payParams.setVisibleIndemnity(true);
        payParams.setMerchantType(jsData.getMerchantType());
        if (mActivity != null) {
            if (mActivity instanceof NewH5Activity) {
                ((NewH5Activity) mActivity).successPage = jsData.getSucc();
            }
            mActivity.startActivityForResult(PayActivity.Companion.newIntent(mActivity, payParams), 33);
        }
    }

    //专家收款
    @Override
    public void payReceipt(H5JsBean.H5JsCmd.Params jsData) {
        LogUtil.d("pay_receipt");
        PayParams payParams = new PayParams();
        payParams.setPayId(jsData.getPayId());
        payParams.setNeedPay(Float.valueOf(jsData.getMoney()));
        payParams.setTitle("预约咨询");
        payParams.setVisibleIndemnity(true);
        payParams.setMerchantType(jsData.getMerchantType());
        if (mActivity != null) {
            if (mActivity instanceof NewH5Activity) {
                ((NewH5Activity) mActivity).successPage = jsData.getSucc();
            }
            mActivity.startActivityForResult(PayActivity.Companion.newIntent(mActivity, payParams), 33);
        }
    }


    @Override
    public void payCourse(H5JsBean.H5JsCmd.Params jsData) {
        LogUtil.d("pay_course");
        PayParams payParams = new PayParams();
        payParams.setPayId(jsData.getPayId());
        payParams.setNeedPay(Float.valueOf(jsData.getMoney()));
        payParams.setTitle("课程");
        payParams.setMerchantType(jsData.getMerchantType());
        if (mActivity != null) {
            if (mActivity instanceof NewH5Activity) {
                ((NewH5Activity) mActivity).successPage = jsData.getSucc();
            }
            mActivity.startActivityForResult(PayActivity.Companion.newIntent(mActivity, payParams), 33);
        }
    }

    @Override
    public void payTest(H5JsBean.H5JsCmd.Params jsData) {
        LogUtil.d("pay_course");
        if (!TextUtils.isEmpty(jsData.getPayId()) || jsData.getTest_items_id() != 0) {
            //设置支付结果页
            if (mActivity != null) {
                if (mActivity instanceof NewH5Activity) {
                    ((NewH5Activity) mActivity).successPage = jsData.getSucc();
                }
            }
            PayParams payParams = new PayParams();

            if (TextUtils.isEmpty(jsData.getPayId()) && jsData.getTest_items_id() != 0) {
                //创建支付订单
                payParams.setNeedPay(jsData.getPrice());
                payParams.setPayId(String.valueOf(jsData.getTest_items_id()));
                payParams.setTitle("心理测试");
                payParams.setBtnPayText("(￥" + jsData.getPrice() + ") 确认付款");
                payParams.setInlet(PayParams.INLET_TEST);
                payParams.setMerchantType(jsData.getMerchantType());
                mActivity.startActivityForResult(PayActivity.Companion.newIntent(mActivity, payParams), 44);
            } else if (!TextUtils.isEmpty(jsData.getPayId()) && !TextUtils.isEmpty(jsData.getOrderId())) {
                //待支付订单跳转
                payParams.setInlet(PayParams.INLET_NORMAL);
                payParams.setPayId(jsData.getPayId());
                payParams.setNeedPay(jsData.getPrice());
                payParams.setTitle("心理测试");
                payParams.setType(2);
                float couponMoney = TextUtils.isEmpty(jsData.getCouponMoney()) ? 0f : Float.valueOf(jsData.getCouponMoney());
                payParams.setBtnPayText("（￥" + new DecimalFormat("0.00").format(jsData.getPrice() - couponMoney) + "）确认付款");
                payParams.setCoupon_money(couponMoney);
                payParams.setMerchantType(jsData.getMerchantType());
                mActivity.startActivityForResult(PayActivity.Companion.newIntent(mActivity, payParams), 44);
            } else {
                //直接支付
                payParams.setPayId(jsData.getPayId());
                payParams.setNeedPay(Float.valueOf(jsData.getMoney()));
                payParams.setTitle("测评");
                payParams.setMerchantType(jsData.getMerchantType());
                mActivity.startActivityForResult(PayActivity.Companion.newIntent(mActivity, payParams), 44);
            }
        }
    }

    /**
     * 查看测试结果
     *
     * @param jsData
     */
    @Override
    public void viewTestResult(H5JsBean.H5JsCmd.Params jsData) {
        if (jsData.getTestResultId() != 0) {
            try {
                JsModularService.Companion.getITestsApiService().testH5Result(jsData.getTestResultId().toString());
            } catch (Exception e) {
            }
        }
    }

    @Override
    public void ydlNative(H5JsBean.H5JsCmd jsData) {
        LogUtil.d("ydlNative");
        //用于子类统计数据的  不做业务处理
    }

    @Override
    public void openOrderDetail(H5JsBean.H5JsCmd.Params params) {
        openH5(params);
    }

    @Override
    public void expertProduct(H5JsBean.H5JsCmd.Params params) {
        openH5(params);
    }

    @Override
    public void order(H5JsBean.H5JsCmd.Params params) {
        openH5(params);
    }

    @Override
    public void toOrderCt(H5JsBean.H5JsCmd.Params params) {
        openH5(params);
    }

    @Override
    public void showDocList(H5JsBean.H5JsCmd.Params params) {

    }

    @Override
    public void goodExpert() {

    }

    @Override
    public void copyWechat(H5JsBean.H5JsCmd.Params params) {
        String weixin_id = params.getWeixin();
        //获取剪贴板管理器：
        @SuppressLint("WrongConstant") ClipboardManager cm = (ClipboardManager) mActivity.getSystemService(Context.CLIPBOARD_SERVICE);
        // 创建普通字符型ClipData
        ClipData mClipData = ClipData.newPlainText("Label", weixin_id);
        // 将ClipData内容放到系统剪贴板里。
        cm.setPrimaryClip(mClipData);
    }

    @Override
    public void goWechat() {
        LogUtil.d("GoweChat");
        try {
            Intent intent = mActivity.getPackageManager().getLaunchIntentForPackage("com.tencent.mm");
            mActivity.startActivity(intent);
        } catch (ActivityNotFoundException e) {
            ToastUtil.toastLong(mActivity, "您的手机尚未安装微信或者微信版本太低!");
        }
    }

    @Override
    public void listenOrderDetail(H5JsBean.H5JsCmd.Params params) {
        openH5(params);
    }

    @Override
    public void detailSub(H5JsBean.H5JsCmd.Params params) {
        openH5(params);
    }

    @Override
    public void openAgreement(H5JsBean.H5JsCmd.Params params) {
        openH5(params);
    }

    @Override
    public void modifyEval(H5JsBean.H5JsCmd.Params params) {
        openH5(params);
    }


    @Override
    public void visitEval(H5JsBean.H5JsCmd.Params params) {
        LogUtil.d("VistEval");
        openH5(params);
    }

    @Override
    public void coursePlay(H5JsBean.H5JsCmd.Params params) {
        if (TextUtils.isEmpty(params.getCourse_id())) {
            ToastUtil.toastShort("参数错误，请重试");
            return;
        }
        try {
            JsModularService.Companion.getICourseService().startCoursePlayActivity(mActivity,
                    Integer.valueOf(params.getCourse_id()), params.getCoursePlayUrl(), 1, params.getMediaType());
        } catch (Exception e) {
        }
    }

    @Override
    public void closeFloatView() {
        mActivity.runOnUiThread(() -> {
            try {
                if (PlayerFloatHelper.Companion.isShow()) {
                    PlayerFloatHelper.Companion.removeResetView();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
    }

    @Override
    public void courseWriteComment(H5JsBean.H5JsCmd.Params params) {
        try {
            JsModularService.Companion.getICourseService().startCourseCommentActivity(mActivity, Objects.requireNonNull(params.getCourse_id()));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void courseComment(H5JsBean.H5JsCmd.Params params) {
        LogUtil.d("courseComment");
        //课程评论列表
        try {
            JsModularService.Companion.getICourseService().startCourseReplyActivity(mActivity, params.getCourse_id());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void listenTel(H5JsBean.H5JsCmd.Params jsData) {

    }

    @Override
    public void voiceBroadcast(H5JsBean.H5JsCmd.Params params) {
    }

    /**
     * axb拨号逻辑
     *
     * @param params
     */
    @Override
    public void tel(H5JsBean.H5JsCmd.Params params) {
        try {
            ModularServiceManager.INSTANCE.provide(IConfideService.class).showAxbConfirmDialog(mActivity, 1, params.getPhoneNumber());
        } catch (Exception e) {
        }
    }

    /**
     * 声网拨号逻辑
     *
     * @param jsData
     */
    @Override
    public void listenAgora(H5JsBean.H5JsCmd.Params jsData) {
    }

    @Override
    public void setTitle(H5JsBean.H5JsCmd.Params jsData) {

    }


    //倾诉链接java接口，支持axb和声网，双呼由h5发起
    @Override
    public void confideConnect(H5JsBean.H5JsCmd.Params jsData) {
        //h5activity中实现
    }

    @Override
    public void confidePay(H5JsBean.H5JsCmd.Params jsData) {
        //h5中实现
    }

    @Override
    public void back() {
        //h5中实现
        mActivity.finish();
    }

    @Override
    public void saveImage(H5JsBean.H5JsCmd.Params jsData) {
        ImageUtil.savePicture(mActivity, jsData.getImageBase64());
    }

    @Override
    public void sendToExpert(H5JsBean.H5JsCmd.Params jsData) {

        //专家解读
        ARouter.getInstance().build("/test/select_conversation")
                .withInt("flag", 1)
                .withString("title", jsData.getShare().getTitle())
                .withString("head", jsData.getShare().getCover())
                .withInt("id", jsData.getTest_items_id())
                .withString("share_url", jsData.getShare().getShare_url())
                .withString("url", HttpConfig.Companion.getH5_URL() + "ceshi/result/" + jsData.getTestResultId())
                .navigation();

    }

    /**
     * 调用公共支付的
     *
     * @param jsData
     */
    @Override
    public void commonPay(H5JsBean.H5JsCmd.Params jsData) {
        if (System.currentTimeMillis() - lastClickTime < FAST_CLICK_DELAY_TIME) {
            return;
        }
        lastClickTime = System.currentTimeMillis();

        UserResponseBean.UserInfo userInfo = JsModularService.Companion.getIUserService().getUserInfo();
        if (userInfo != null) {
            mActivity.runOnUiThread(() -> {
                CommonPayDialog.Build build = new CommonPayDialog.Build(mActivity)
                        .setCourseId(Objects.requireNonNull(jsData.getGoodsId()))
                        .setToken(Objects.requireNonNull(userInfo.getAccessToken()))
                        .setUid(userInfo.getUid())
                        .setIsTestEnvironment(false)
                        .setFfrom(YdlCommonOut.Companion.getChannelName())
                        .setListener(new CommonPayDialog.OnPayResultListener() {
                            @Override
                            public void onSuccesed() {
                                if (mActivity instanceof NewH5Activity) {
                                    ((NewH5Activity) mActivity).refresh();
                                }
                            }

                            @Override
                            public void onFailed() {

                            }
                        });
                build.build().show();
            });
        }
    }

    @Override
    public void onOrderByApp(H5JsBean.H5JsCmd.Params params) {
        LogUtil.d("onorder_by_app");
        //预约下单
//        DownOrderActivity.Companion.start(mContext, params.getProduct_id());
        //新版走h5下单流程，此处不需要了
    }

    @Override
    public void orderSetTime(H5JsBean.H5JsCmd.Params params) {
        //预约下单选择时间
        LogUtil.d("order_set_time");
        Intent in = mActivity.getIntent();
        in.putExtra("schedule_id", params.getSchedule_id());
        in.putExtra("schedule_time", params.getSchedule_time());
        mActivity.setResult(Activity.RESULT_OK, in);
        mActivity.finish();
        mActivity.overridePendingTransition(0, R.anim.app_activity_open_down);
    }

    @Override
    public void searchServiceDoc(int cateId) {
        try {
            ModularServiceManager.INSTANCE.provide(IConsultantService.class).startExpertSearchActivity(mActivity, String.valueOf(cateId));
        } catch (Exception e) {
        }
    }

    @Override
    public void openTestDetail(H5JsBean.H5JsCmd.Params params) {
        try {
            JsModularService.Companion.getITestsApiService().testDetailH5(String.valueOf(params.getTest_items_id()));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void shareAction(H5JsBean.H5JsCmd.Params params) {
        if (mActivity != null) {
            if (mActivity instanceof NewH5Activity) {
                ((NewH5Activity) mActivity).showShareMenu(params);
            }
        }
    }

    @Override
    public void openTestList() {
        YDLRouterManager.Companion.router(IYDLRouterConstant.ROUTER_TEST_HOME);
    }

    @Override
    public void feedBack() {
        try {
            ModularServiceManager.INSTANCE.provide(IAppService.class).feedBackIntent(mActivity);
        } catch (Exception e) {
        }
    }

    @Override
    public void phoneCall() {
        try {
            ModularServiceManager.INSTANCE.provide(IConfideService.class).startCondifeHomePage(mActivity, false);
        } catch (Exception e) {
        }
    }

    @Override
    public void chatSchedule(H5JsBean.H5JsCmd.Params params) {
        try {
            ModularServiceManager.INSTANCE.provide(IImService.class)
                    .chatScheule(mActivity, params.getUser_url(), params.getDoc_url(), params.getDsmId(), params.getTitle(), params.getToUid());
        } catch (Exception e) {
        }

    }

    @Override
    public void invite(H5JsBean.H5JsCmd.Params params) {
        if (mActivity != null && null != params && null != params.getShare()) {
            YDLShareDialog dialog = YDLShareDialog.Companion.style4(mActivity, params.getShare().getTitle(), params.getShare().getShare_url(), params.getShare().getDesc(), params.getShare().getCover());
            dialog.show(mActivity.getFragmentManager(), "lose");
        }
    }

    @Override
    public void balance(H5JsBean.H5JsCmd.Params params) {
        if (!JsModularService.Companion.getIUserService().loginByOneKeyLogin(mActivity, true)) {
            return;
        }
        try {
            ModularServiceManager.INSTANCE.provide(IAppService.class).accountHistoryIntent(mActivity);
        } catch (Exception e) {
        }
    }

    @Override
    public void switchDownRefresh(H5JsBean.H5JsCmd.Params params) {
         if (mActivity != null && mActivity instanceof NewH5Activity) {
            ((NewH5Activity) mActivity).hasShowDownRefresh(params.getSwitch());
        }
    }

    @Override
    public void refresh() {
        if (mActivity instanceof NewH5Activity) {
            ((NewH5Activity) mActivity).refresh();
        }
    }

    @Override
    public void recharge() {
        if (!JsModularService.Companion.getIUserService().loginByOneKeyLogin(mActivity, true)) {
            return;
        }
        try {
            ModularServiceManager.INSTANCE.provide(IAppService.class).rechargeActivityIntent(mActivity);
        } catch (Exception e) {
        }
    }

    @Override
    public void bindPhone() {
        try {
            ModularServiceManager.INSTANCE.provide(IUserService.class).wxBindToInputhonePage(mActivity);
        } catch (Exception e) {
        }
    }

    @Override
    public void openRightTopMenu() {
        if (mActivity instanceof NewH5Activity) {
            ((NewH5Activity) mActivity).openRightTopMenu();
        }
    }

    @Override
    public void openShareMenu(H5JsBean.H5JsCmd.Params params) {
        if (mActivity instanceof NewH5Activity) {
            ((NewH5Activity) mActivity).openShareMenu(params);
        }
    }

    @Override
    public void hideStatusBar() {
        if (mActivity instanceof NewH5Activity) {
            ((NewH5Activity) mActivity).hideJavaTitleBar();
        }
    }

    @Override
    public void showStatusBar() {
        if (mActivity instanceof NewH5Activity) {
            ((NewH5Activity) mActivity).showTitleBar();
        }
    }

    @Override
    public void closeWebKit() {
        if (mActivity instanceof NewH5Activity) {
            ((NewH5Activity) mActivity).closeWebKit();
        }
    }

    @Override
    public void goHome(H5JsBean.H5JsCmd.Params params) {
        //关闭所有页面返回首页
        JsModularService.Companion.getIAppService().mainIntent(mActivity,params.getSelectTab(), false);
        //关闭当前H5页面
        mActivity.finish();
    }

    @SuppressLint("CheckResult")
    @Override
    public void sendUnReadNum(String callbackFuncName, String uid) {

        try {
            //在uid用户类型确定为专家的情况下，根据uid调用接口判断是进入专家私聊还是助理私聊
            ModularServiceManager.INSTANCE.provide(IImService.class)
                    .getChatUid(mActivity, uid, responseUid -> {
                        final StringBuffer sb = new StringBuffer();
                        sb.append(callbackFuncName);
                        sb.append("('");

                        int unReadNum = ModularServiceManager.INSTANCE.provide(IImService.class).getUnReadByUid(responseUid);
                        sb.append(unReadNum);

                        sb.append(",");

                        int unReadAllNum = ModularServiceManager.INSTANCE.provide(IImService.class).getAllUnReadNum();
                        sb.append(unReadAllNum);

                        sb.append("')");
                        if (mActivity != null && mActivity instanceof NewH5Activity) {
                            ((NewH5Activity) mActivity).callJSFunc(sb.toString());
                        }
                    });
        } catch (Exception e) {
        }
    }


    @Override
    public void switchPushStatus(H5JsBean.H5JsCmd.Params params) {
        if (params.getSwitchStatus() == 1) {
            JsImpl.Companion.setH5Open(true);
        } else {
            JsImpl.Companion.setH5Open(false);
        }
    }

    @Override
    public void shouldShowTitleBar(boolean isShowTitleBar) {
        if (isShowTitleBar && mActivity instanceof NewH5Activity) {
            ((NewH5Activity) mActivity).notCoverTitleBar();
        } else {
            ((NewH5Activity) mActivity).coverJavaTitleBar();
        }
    }

    @Override
    public void setSelfPageType(int selfType) {
        if (mActivity instanceof NewH5Activity) {
            ((NewH5Activity) mActivity).setSelfPageType(selfType);
        }
    }

    @Override
    public void setBootomFitViewColor(String color) {
        if (mActivity instanceof NewH5Activity) {
            ((NewH5Activity) mActivity).setBottomViewColor(color);
        }
    }

    /**
     * 打开时间选择器
     */
    @SuppressLint("CheckResult")
    @Override
    public void openTimePicker(String jsCallBackName, String day, String doctorId, String orderId) {
        ArrayList<String> options1Items = new ArrayList<>();
        ArrayList<List<String>> options2Items = new ArrayList<>();
        ArrayList<List<List<String>>> options3Items = new ArrayList<>();

        // 所构造的时间数据
        ArrayList<List<String>> TIMELIST = new ArrayList<>();
        JsHttpImpl.Companion.getInstance().getTimePickerData(day, doctorId, orderId)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(response -> {
                    if (response.code == 200) {
                        for (int i = 0; i < response.data.size(); i++) {  // 遍历服务时间
                            TimeDataBean timeDataBean = response.data.get(i);
                            options1Items.add(String.valueOf(timeDataBean.getServiceTime()));

                            // 构造时间数据
                            for (int j = 0; j < response.data.size(); j++) {
                                List<String> list = new ArrayList<>();
                                for (int k = 0; k < timeDataBean.getTimes().size(); k++) {
                                    String[] times = timeDataBean.getTimes().get(k).split("-");
                                    list.add(times[0]);
                                    int timeInterval = (int) ((getTimeToDate(times[1]) - getTimeToDate(times[0])) / 1000 / 60 / 10);
                                    for (int l = 0; l < timeInterval; l++) {
                                        String time = getHourMin(getTimeToDate(list.get(list.size() - 1)) + 10 * 60 * 1000);
                                        list.add(time);
                                    }
                                }
                                TIMELIST.add(list);
                            }

                            ArrayList<String> amList = new ArrayList<>(); // 上午、下午集合(第二级)
                            ArrayList<List<String>> timeList = new ArrayList<>(); //  上午或者下午对应的时间 （第三级）
                            for (int j = 0; j < 2; j++) {
                                List<String> tmList = new ArrayList<>(); // 上午或者下午对应的时间集合
                                if (j == 0) {
                                    for (int k = 0; k < TIMELIST.get(i).size(); k++) {
                                        if (getTimeToDate(TIMELIST.get(i).get(k)) <= getTimeToDate("12:00")) {
                                            tmList.add(TIMELIST.get(i).get(k));
                                        }
                                    }
                                    if (tmList.size() > 0) {
                                        amList.add("上午");
                                    }
                                } else {
                                    for (int k = 0; k < TIMELIST.get(i).size(); k++) {
                                        if (getTimeToDate(TIMELIST.get(i).get(k)) > getTimeToDate("12:00")) {
                                            tmList.add(TIMELIST.get(i).get(k));
                                        }
                                    }
                                    if (tmList.size() > 0) {
                                        amList.add("下午");
                                    }
                                }
                                if (tmList.size() > 0) {
                                    timeList.add(tmList);
                                }
                            }
                            options2Items.add(amList);
                            options3Items.add(timeList);
                        }
                        pvOptions = new OptionsPickerBuilder(mActivity, (options1, options2, options3, v) -> {
                            // 选择完时间回调给前端
                            if (mActivity instanceof NewH5Activity) {
                                ((NewH5Activity) mActivity).callJSFunc("saveChooseTimer(\"" + options3Items.get(options1).get(options2).get(options3) + "," + options1Items.get(options1) + "\")");
                            }
                            LogUtil.e("saveChooseTimer(\"" + options3Items.get(options1).get(options2).get(options3) + "," + options1Items.get(options1) + "\")");
                        })
                                .setTitleText("请选择开始时间")
                                .setDividerColor(Color.TRANSPARENT)
                                .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
                                .setLabels("分钟", "", "")
                                .setCyclic(false, false, false)
                                .setContentTextSize(20)
                                .isRestoreItem(true)
                                .build();
                        pvOptions.setPicker(options1Items, options2Items, options3Items);
                        pvOptions.show();
                    }
                }, e -> {
                    ToastUtil.toastShort(e.getMessage());
                });

    }

    // 关闭当前h5页面并刷新上一个h5页面
    @Override
    public void goBackAndReload(String url) {
        H5Params h5Params = new H5Params(url, null);
        NewH5Activity.start(mActivity, h5Params);
        if (ActivityManager.Companion.getInstance().getSecondTaskActivity() != null) {
            ActivityManager.Companion.getInstance().getSecondTaskActivity().finish();
        }
        mActivity.finish();
    }

    @Override
    public void toThirdApp(String url) {
        mActivity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (!TextUtils.isEmpty(url)) {
                    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                    mActivity.startActivity(intent);
                }
            }
        });
    }

    @Override
    public void getNextExpertStatus(String doctorID, String title, String uid, String linkUrl) {
        EventBus.getDefault().post(new ChangeAnotherExpertEvent(doctorID, title, uid, linkUrl));
    }

    @Override
    public void chatCloseBottomWebView() {
        EventBus.getDefault().post(new CloseBottomWebviewEvent(true));
        ModularServiceManager.INSTANCE.provide(IImService.class).dismissConsultServiceDialog();
    }

    @Override
    public void resourceToPreview(H5JsBean.H5JsCmd.Params params) {
        List<H5JsBean.MediaInfo> dataList = params.getDataList();
        ModularServiceManagerKt.findRouteService(IConsultantService.class).resourceToPreview(dataList,params,mActivity);
    }

    @Override
    public void showDocBooking(H5JsBean.H5JsCmd.Params params) {
        ModularServiceManager.INSTANCE.provide(IImService.class).showConsultServiceDialog(mActivity, params.getToUid() + "", params.getDoctorId() + "");
    }

    @Override
    public void reloadUrl(String url) {
        if (mActivity instanceof NewH5Activity) {
            mActivity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    ((NewH5Activity) mActivity).loadUrl(url);
                }
            });

        }
    }

    /**
     * 时间字符串转时间戳
     *
     * @param time
     * @return
     */
    private long getTimeToDate(String time) {
        @SuppressLint("SimpleDateFormat")
        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
        Date date = new Date();
        try {
            date = sdf.parse(time);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return date.getTime();
    }

    /**
     * 根据时间戳获取时分
     *
     * @return
     */
    private String getHourMin(long time) {
        @SuppressLint("SimpleDateFormat")
        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
        return sdf.format(new Date(time));
    }


    @Override
    public void playMeditation(int mediaId, long meditationId, int meditationType, String mediaCoverUrl) {

        if (mActivity instanceof NewH5Activity) {
            ARouter.getInstance().build("/muse/play")
                    .withLong("MEDITATION_ID", meditationId)
                    .withLong("MEDIA_ID", mediaId)
                    .withInt("MEDITATION_TYPE", meditationType)
                    .withString("MEDIA_COVER_URL", mediaCoverUrl)
                    .navigation();}
    }

    @Override
    public void switchSound(int mediaId, long meditationId, int meditationType, int businessType,
                            String buried, String mediaUrl, String mediaCoverUrl,
                            String title, String desc, int status) {

        if (mActivity instanceof NewH5Activity) {
            ((NewH5Activity) mActivity).switchSound(mediaId, meditationId, meditationType,
                    businessType, buried, mediaUrl, mediaCoverUrl, title, desc, status);
        } else if ("ChooseMusicActivity".equals(mActivity.getClass().getSimpleName())) {
            JsModularService.Companion.getIMuseService().switchSound(mActivity,mediaId, meditationId, meditationType,
                    businessType, buried, mediaUrl, mediaCoverUrl, title, desc, status);
        }
    }

    @Override
    public void setBG(String rgb, String alpha) {
        if (mActivity instanceof NewH5Activity) {
            ((NewH5Activity) mActivity).setBG(rgb, alpha);
        }
    }

    @Override
    public void showCommentArticleDialog(H5JsBean.H5JsCmd.Params params) {
        if (mActivity instanceof NewH5Activity){
            ((NewH5Activity)mActivity).showCommentArticleDialog(params.getTitle());
        }
    }
}
