package com.cooleshow.student.widgets.helper;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.text.TextUtils;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.JavascriptInterface;

import com.alibaba.android.arouter.launcher.ARouter;
import com.cooleshow.base.common.WebConstants;
import com.cooleshow.base.router.RouterPath;
import com.cooleshow.usercenter.constants.UserConstants;
import com.cooleshow.usercenter.helper.UserHelper;
import com.gyf.immersionbar.ImmersionBar;

import org.json.JSONObject;

import io.rong.imkit.RongIM;
import io.rong.imlib.model.UserInfo;

/**
 * Description:
 * Copyright  : Copyright (c) 2016
 * Company    : 大雅
 * Author     : 刘瑞
 * Date       : 2018/11/12 15:23
 */
public class JsInterfaceAccomPanyUtils extends Object {
    private static final String TAG = "JsInterfaceAccomPanyUtils";

    private Activity activity;
    JSONObject resultJson;

    public JsInterfaceAccomPanyUtils(Activity activity) {
        this.activity = activity;

    }

    /*
     *统一方法
     */
    @JavascriptInterface
    public void postMessage(String message) {
        activity.runOnUiThread(() -> {
            try {
                JSONObject jsonObject = new JSONObject(message);
                String api = jsonObject.getString("api");
                if ("back".equals(api)) {
                    activity.finish();
                } else if ("login".equals(api)) {
                    UserHelper.saveUserToken("");
                    ARouter.getInstance().build(RouterPath.UserCenter.PATH_VERIFY_LOGIN)
                            .withString(UserConstants.PHONE_NUM_KEY, UserHelper.getUserPhone())
                            .addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK)
                            .navigation();
                    activity.finish();
                } else if ("openConversationActivity".equals(api)) {
                    JSONObject contentBean = jsonObject.getJSONObject("content");
                    if (null != contentBean) {
                        RongIM.getInstance().startPrivateChat(activity, contentBean.getString("userId"), contentBean.getString("name"));
                        if (!TextUtils.isEmpty(contentBean.getString("img"))) {
                            RongIM.getInstance().refreshUserInfoCache(new UserInfo(contentBean.getString("userId"),
                                    contentBean.getString("name"),
                                    Uri.parse(contentBean.getString("img"))));
                        }
                    }
                } else if ("videoUpdate".equals(api)) {
                    if (onListener != null) {
                        onListener.videoUpdate(jsonObject);
                    }
                } else if ("setRequestedOrientation".equals(api)) {
                    JSONObject content = jsonObject.getJSONObject("content");
                    int orientation = content.getInt("orientation");
                    activity.setRequestedOrientation(orientation);
                    if (onListener != null)
                        onListener.onSendMessage(content.toString());
                } else if ("keepScreenLongLight".equals(api)) {
                    JSONObject content = jsonObject.getJSONObject("content");
                    boolean isOpenLight = content.getBoolean("isOpenLight");
                    keepScreenLongLight(isOpenLight);
                    if (onListener != null)
                        onListener.onSendMessage(content.toString());
                } else if ("setStatusBarTextColor".equals(api)) {
                    JSONObject content = jsonObject.getJSONObject("content");
                    boolean statusBarTextColor = content.getBoolean("statusBarTextColor");
                    if (onListener != null)
                        onListener.setStatusBarTextColor(statusBarTextColor, jsonObject);
                } else if ("isSpecialShapedScreen".equals(api)) {
                    JSONObject content = jsonObject.getJSONObject("content");
                    content.put("isSpecialShapedScreen", ImmersionBar.hasNotchScreen(activity));
                    content.put("notchHeight", ImmersionBar.getNotchHeight(activity));
                    if (onListener != null)
                        onListener.onSendMessage(jsonObject.toString());
                } else if ("openWebView".equals(api)) {
                    JSONObject content = jsonObject.getJSONObject("content");
                    boolean isHideTitle = false;
                    boolean statusBarTextColor = false;
                    boolean isOpenLight = false;
                    int orientation = -1;
                    try {
                        isHideTitle = content.getBoolean("isHideTitle");
                        statusBarTextColor = content.getBoolean("statusBarTextColor");
                        isOpenLight = content.getBoolean("isOpenLight");
                        orientation = content.getInt("orientation");
                    } catch (Exception e) {
                    }

                    String path = RouterPath.WebCenter.ACTIVITY_HTML;
                    if (orientation == 0) {
                        path = RouterPath.WebCenter.ACTIVITY_HORIZONTAL_SCREEN_HTML;
                    }
                    ARouter.getInstance().build(path)
                            .withString(WebConstants.WEB_URL, content.optString("url"))
                            .withBoolean("isHideTitle", isHideTitle)
                            .withBoolean("statusBarTextColor", statusBarTextColor)
                            .withBoolean("isOpenLight", isOpenLight)
                            .withInt("orientation", orientation)
                            .navigation();
                } else if ("openAccompanyWebView".equals(api)) {
                    JSONObject content = jsonObject.getJSONObject("content");
                    boolean isHideTitle = false;
                    boolean statusBarTextColor = false;
                    boolean isOpenLight = false;
                    int orientation = -1;
                    try {
                        isHideTitle = content.getBoolean("isHideTitle");
                        statusBarTextColor = content.getBoolean("statusBarTextColor");
                        isOpenLight = content.getBoolean("isOpenLight");
                        orientation = content.getInt("orientation");
                    } catch (Exception e) {
                    }

                    ARouter.getInstance().build(RouterPath.WebCenter.ACTIVITY_ACCOMPANY_HTML)
                            .withString("url", content.getString("url"))
                            .withBoolean("isHideTitle", isHideTitle)
                            .withBoolean("statusBarTextColor", statusBarTextColor)
                            .withBoolean("isOpenLight", isOpenLight)
                            .withInt("orientation", orientation)
                            .navigation();

                } else if ("startEvaluating".equals(api)) {
                    if (onListener != null) {
                        onListener.startEvaluating(jsonObject);
                    }
                } else if ("endEvaluating".equals(api)) {
                    if (onListener != null) {
                        onListener.endEvaluating(jsonObject);
                    }
                } else if ("cancelEvaluating".equals(api)) {
                    if (onListener != null) {
                        onListener.cancelEvaluating();
                        onListener.onSendMessage(message);
                    }
                } else if ("startRecording".equals(api)) {
                    if (onListener != null) {
                        onListener.startRecording(jsonObject);
                    }
                } else if ("pauseRecording".equals(api)) {
                    if (onListener != null) {
                        onListener.pauseRecording(jsonObject);
                    }
                } else if ("resumeRecording".equals(api)) {
                    if (onListener != null) {
                        onListener.resumeRecording(jsonObject);
                    }
                } else if ("isWiredHeadsetOn".equals(api)) {
                    if (onListener != null) {
                        onListener.isWiredHeadsetOn(jsonObject);
                    }
                } else if ("proxyMessage".equals(api)) {
                    if (onListener != null) {
                        onListener.proxyMessage(jsonObject);
                    }
                } else if ("openCamera".equals(api)) {
                    if (onListener != null) {
                        onListener.openCamera(jsonObject);
                    }
                } else if ("closeCamera".equals(api)) {
                    if (onListener != null) {
                        onListener.closeCamera(jsonObject);
                    }
                } else if ("startCapture".equals(api)) {
                    if (onListener != null) {
                        onListener.startCapture(jsonObject);
                    }
                } else if ("endCapture".equals(api)) {
                    if (onListener != null) {
                        onListener.endCapture(jsonObject);
                    }
                } else if ("endRecording".equals(api)) {
                    if (onListener != null) {
                        onListener.endRecording(jsonObject);
                    }
                } else if ("startSoundCheck".equals(api)) {
                    if (onListener != null) {
                        onListener.startSoundCheck(jsonObject);
                    }
                } else if ("endSoundCheck".equals(api)) {
                    if (onListener != null) {
                        onListener.endSoundCheck(jsonObject);
                    }
                } else if ("proxyServiceMessage".equals(api)) {
                    if (onListener != null) {
                        onListener.proxyServiceMessage(jsonObject);
                    }
                } else if ("keepScreenLongLight".equals(api)) {
                    if (onListener != null) {
                        onListener.keepScreenLongLight(jsonObject);
                    }
                }
                //分享
                else if ("shareAchievements".equals(api)) {
                    if (onListener != null) {
                        onListener.shareAchievements(jsonObject);
                    }
                }
                // 分段上传
                else if ("measureStart".equals(api)) {
                    if (onListener != null) {
                        onListener.measureStart(jsonObject);
                    }
                }
                //分段上传结束
                else if ("allMeasureEnd".equals(api)) {
                    if (onListener != null) {
                        onListener.allMeasureEnd(jsonObject);
                    }
                }
                //初始化
                else if ("cloudDetail".equals(api)) {
                    if (onListener != null) {
                        onListener.cloudDetail(jsonObject);
                    }
                }
                //开始播放
                else if ("cloudPlay".equals(api)) {
                    if (onListener != null) {
                        onListener.cloudPlay(jsonObject);
                    }
                }
                //播放暂停
                else if ("cloudSuspend".equals(api)) {
                    if (onListener != null) {
                        onListener.cloudSuspend(jsonObject);
                    }
                }
                //播放进度跳转
                else if ("cloudSetCurrentTime".equals(api)) {
                    if (onListener != null) {
                        onListener.cloudSetCurrentTime(jsonObject);
                    }
                }
                //调速
                else if ("cloudChangeSpeed".equals(api)) {
                    if (onListener != null) {
                        onListener.cloudChangeSpeed(jsonObject);
                    }
                }
                //实现原音伴奏切换，基于传入参数控制声道
                else if ("cloudSwitch".equals(api)) {
                    if (onListener != null) {
                        onListener.cloudSwitch(jsonObject);
                    }
                }
                //实现音量控制基于传入参数控制声道
                else if ("cloudVolume".equals(api)) {
                    if (onListener != null) {
                        onListener.cloudVolume(jsonObject);
                    }
                } else if ("cloudGetMediaStatus".equals(api)) {
                    if (onListener != null) {
                        onListener.cloudGetMediaStatus(jsonObject);
                    }
                } else if ("cloudMetronome".equals(api)) {
                    if (onListener != null) {
                        onListener.cloudMetronome(jsonObject);
                    }
                } else if ("cloudDestroy".equals(api)) {
                    if (onListener != null) {
                        onListener.cloudDestroy(jsonObject);
                    }
                } else if ("joinLiveRoom".equals(api)) {
                    //进入直播间
                    JSONObject content = jsonObject.getJSONObject("content");
                    if (onListener != null) {
                        onListener.joinLiveRoom(content.getString("roomId"), content.getString("teacherId"));
                    }
                } else if ("joinChatGroup".equals(api)) {
                    //进入聊天
                    JSONObject content = jsonObject.getJSONObject("content");
                    if (onListener != null) {
                        onListener.joinChatGroup(content.getString("type"), content.getString("id"));
                    }
                } else if ("setAddress".equals(api)) {
                    //跳转地址页面
                    ARouter.getInstance().build(RouterPath.BaseCenter.MINE_ADDRESS_LIST)
                            .navigation(activity, 1011);
                } else if ("paymentOrder".equals(api)) {
                    //支付
                    JSONObject content = jsonObject.getJSONObject("content");
                    if (onListener != null) {
                        onListener.paymentOrder(content.getString("orderNo"), content.getString("payChannel"), content.getString("payInfo"));
                    }
                }
                if ("savePicture".equalsIgnoreCase(api)) {
                    JSONObject content = jsonObject.getJSONObject("content");
                    if (onListener != null) {
                        onListener.savePicture(content.getString("base64"),content.getString("uuid"));
                    }
                }
            } catch (Exception e) {

            }
        });

    }

    private void keepScreenLongLight(boolean isOpenLight) {
        Window window = activity.getWindow();
        if (isOpenLight) {
            window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        } else {
            window.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

        }

    }

    public onGetMethodsListener onListener;

    public void setOnGetMethodsListener(onGetMethodsListener onListener) {
        this.onListener = onListener;
    }

    public interface onGetMethodsListener {
        void onSendMessage(String message);

        void setStatusBarTextColor(boolean statusBarTextColor, JSONObject message);

        void startEvaluating(JSONObject message);


        void startRecording(JSONObject message);

        void endRecording(JSONObject message);

        void keepScreenLongLight(JSONObject message);

        /**
         * 开始校音
         *
         * @param message
         */
        void startSoundCheck(JSONObject message);

        void endSoundCheck(JSONObject message);

        void endEvaluating(JSONObject jsonObject);

        void cancelEvaluating();

        void resumeRecording(JSONObject jsonObject);

        void pauseRecording(JSONObject jsonObject);

        void isWiredHeadsetOn(JSONObject jsonObject);

        void proxyMessage(JSONObject jsonObject);

        void proxyServiceMessage(JSONObject jsonObject);

        void openCamera(JSONObject jsonObject);

        void closeCamera(JSONObject jsonObject);

        void startCapture(JSONObject jsonObject);

        void endCapture(JSONObject jsonObject);

        void videoUpdate(JSONObject jsonObject);

        void shareAchievements(JSONObject message);

        void measureStart(JSONObject message);

        void allMeasureEnd(JSONObject message);

        /**
         * 进入页面初始化方法
         * 初始化midi文件，初始速度，默认拍号的分子和分母
         * {
         * api: 'cloudDetail',
         * content: {
         * midi: ''，
         * denominator: 4,
         * numerator: 4,
         * // xml整体原始速度
         * originalSpeed: 90,
         * }
         *
         * @param message
         */
        void cloudDetail(JSONObject message);

        /**
         * 播放
         * {
         * api: 'cloudPlay',
         * content: {
         * // 当前曲目id
         * songID: 0,
         * // xml整体原始速度
         * originalSpeed: 90,
         * // 当前选择速度
         * speed: 90,
         * // 开始时间(ms)
         * startTime: 0
         * }
         * })
         * <p>
         * // 返回数据
         * <p>
         * {
         * api: 'cloudPlay',
         * content: {
         * // 当前曲目id
         * songID: 0,
         * // xml整体原始速度
         * originalSpeed: 90,
         * // 当前选择速度
         * speed: 90,
         * // 开始时间(ms)
         * startTime: 0
         * }
         * }
         *
         * @param message
         */
        void cloudPlay(JSONObject message);

        /**
         * 暂停
         * {
         * api: 'cloudSuspend',
         * content: {
         * // 当前曲目id
         * songID: 0,
         * }
         * })
         * <p>
         * // 返回数据
         * {
         * api: 'cloudSuspend',
         * content: {
         * // 当前曲目id
         * songID: 0,
         * // 暂停位置时间(ms)
         * currentTime: 0
         * }
         * }
         *
         * @param message
         */
        void cloudSuspend(JSONObject message);


        /**
         * 跳转指定位置
         * {
         * api: 'cloudSetCurrentTime',
         * content: {
         * // 当前曲目id
         * songID: 0,
         * // 指定位置时间(ms)
         * currentTime: 0
         * }
         * }
         *
         * @param message
         */
        void cloudSetCurrentTime(JSONObject message);

        /**
         * 调速 范围(45-270整数)
         * {
         * api: 'cloudChangeSpeed',
         * content: {
         * // 当前曲目id
         * songID: 0,
         * // 调整速度
         * speed: 90
         * // xml整体原始速度
         * originalSpeed: 90,
         * }
         * }
         *
         * @param message
         */
        void cloudChangeSpeed(JSONObject message);

        /**
         * 原声/伴奏切换
         * {
         * api: 'cloudSwitch',
         * content: {
         * // 当前曲目id
         * songID: 0,
         * // 需要静音的渠道，为空全部不静音
         * parts: [
         * ''
         * ]
         * }
         * }
         *
         * @param message
         */
        void cloudSwitch(JSONObject message);

        void cloudVolume(JSONObject message);

        /**
         * 获取播放状态
         * {
         * api: 'cloudGetMediaStatus'
         * })
         * <p>
         * // 返回
         * <p>
         * {
         * api: 'cloudGetMediaStatus',
         * content: {
         * status: 'init' | 'play' | 'suspend'
         * }
         * }
         *
         * @param message
         */
        void cloudGetMediaStatus(JSONObject message);

        /**
         * 节拍器控制
         *
         * @param message
         */
        void cloudMetronome(JSONObject message);

        /**
         * 销毁
         *
         * @param message
         */
        void cloudDestroy(JSONObject message);
        /**
         * 进入直播间
         *
         * @param roomId
         * @param teacherId
         */
        void joinLiveRoom(String roomId, String teacherId);

        /**
         * 进入聊天
         *
         * @param type // single 单人 multi 多人
         * @param id
         */
        void joinChatGroup(String type, String id);

        /**
         * 支付
         *
         * @param orderNo
         * @param payChannel
         * @param payInfo
         */
        void paymentOrder(String orderNo, String payChannel, String payInfo);
        /**
         * 保存图片
         * @param base64
         */
        void savePicture(String base64,String uuid);
    }

}
