package com.cooleshow.teacher.widgets.helper;

import static com.cooleshow.base.common.WebConstants.WEB_URL;

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.WebApi;
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    : 大雅
 * Date       : 2018/11/12 15:23
 */
public class JsInterfaceUtils extends Object {


    private Activity activity;
    JSONObject resultJson;


    public JsInterfaceUtils(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();
                    return;
                }
                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();
                    return;
                }
                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"))));
                        }
                    }
                    return;
                }
                if (TextUtils.equals("chooseFile", api)) {
                    //选择文件
                    if (onListener != null) {
                        onListener.chooseFile(jsonObject);
                    }
                    return;
                }
                if ("setRequestedOrientation".equals(api)) {
                    JSONObject content = jsonObject.getJSONObject("content");
                    int orientation = content.getInt("orientation");
                    activity.setRequestedOrientation(orientation);
                    if (onListener != null) {
                        onListener.onSendMessage(content.toString());
                    }
                    return;
                }

                if ("keepScreenLongLight".equals(api)) {
                    JSONObject content = jsonObject.getJSONObject("content");
                    boolean isOpenLight = content.getBoolean("isOpenLight");
                    keepScreenLongLight(isOpenLight);
                    if (onListener != null) {
                        onListener.onSendMessage(content.toString());
                    }
                    return;
                }

                if ("setStatusBarTextColor".equals(api)) {
                    JSONObject content = jsonObject.getJSONObject("content");
                    boolean statusBarTextColor = content.getBoolean("statusBarTextColor");
                    if (onListener != null) {
                        onListener.setStatusBarTextColor(statusBarTextColor);
                    }
                    return;
                }
                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());
                    }
                    return;
                }
                if ("getToken".equals(api)) {
                    JSONObject content = jsonObject.getJSONObject("content");
                    String userToken = UserHelper.getUserToken();
                    String[] s = userToken.split(" ");
                    content.put("tokenType", s[0]);
                    content.put("accessToken", s[1]);

                    if (onListener != null) {
                        onListener.onSendMessage(jsonObject.toString());
                    }
                    return;
                }

                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(WEB_URL, content.getString("url"))
                            .withBoolean("isHideTitle", isHideTitle)
                            .withBoolean("statusBarTextColor", statusBarTextColor)
                            .withBoolean("isOpenLight", isOpenLight)
                            .withInt("orientation", orientation)
                            .navigation();
                    return;
                }
                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(WEB_URL, content.getString("url"))
                            .withBoolean("isHideTitle", isHideTitle)
                            .withBoolean("statusBarTextColor", statusBarTextColor)
                            .withBoolean("isOpenLight", isOpenLight)
                            .withInt("orientation", orientation)
                            .navigation();
                    return;

                }

                if ("onAccompanySelectResult".equals(api)) {
                    JSONObject content = jsonObject.getJSONObject("content");
                    if (onListener != null) {
                        onListener.onAccompanySelecResult(String.valueOf(content.getInt("id")), content.getString("name"));
                    }
                    return;

                }
                if ("downloadFile".equals(api)) {
                    JSONObject content = jsonObject.getJSONObject("content");
                    if (onListener != null) {
                        onListener.downloadFile(content.getString("downloadUrl"));
                    }
                    return;

                }

                //分享
                if ("shareAchievements".equals(api)) {
                    if (onListener != null) {
                        onListener.shareAchievements(jsonObject);
                    }
                    return;
                }

                if ("backIconChange".equals(api)) {
                    if (onListener != null) {
                        onListener.backIconChange(jsonObject);
                    }
                    return;
                }
                if ("getNavHeight".equals(api)) {
                    if (onListener != null) {
                        onListener.getNavHeight(jsonObject);
                    }
                    return;
                }
                /**
                 * { status: 0 隐藏 1 显示 }
                 */
                if ("setBarStatus".equals(api)) {
                    if (onListener != null) {
                        onListener.setBarStatus(jsonObject);
                    }
                    return;
                }
                if ("authToBack".equalsIgnoreCase(api)) {
                    if (onListener != null) {
                        onListener.authToBack(jsonObject);
                    }
                    return;
                }
                //进入直播间
                if ("joinLiveRoom".equals(api)) {
                    JSONObject content = jsonObject.getJSONObject("content");
                    if (onListener != null) {
                        onListener.joinLiveRoom(content.optString("roomId"), content.optString("teacherId"));
                    }
                    return;
                }
                //进入聊天
                if ("joinChatGroup".equals(api)) {
                    JSONObject content = jsonObject.getJSONObject("content");
                    if (onListener != null) {
                        onListener.joinChatGroup(content.getString("type"), content.getString("id"));
                    }
                    return;
                }
                //跳转地址页面
                if ("setAddress".equals(api)) {
                    ARouter.getInstance().build(RouterPath.BaseCenter.MINE_ADDRESS_LIST)
                            .navigation(activity, 1011);
                    return;
                }
                //支付
                if ("paymentOrder".equals(api)) {
                    JSONObject content = jsonObject.getJSONObject("content");
                    if (onListener != null) {
                        onListener.paymentOrder(content.getString("orderNo"), content.getString("payChannel"), content.getString("payInfo"));
                    }
                    return;
                }
                if ("savePicture".equalsIgnoreCase(api)) {
                    JSONObject content = jsonObject.getJSONObject("content");
                    if (onListener != null) {
                        onListener.savePicture(content.getString("base64"), content.getString("uuid"));
                    }
                    return;
                }

                if (TextUtils.equals(WebApi.OPEN_PAGE_SUCCESS, api)) {
                    JSONObject content = jsonObject.getJSONObject("content");
                    if (content != null) {
                        String page = content.optString("page");
                        if (TextUtils.equals(WebApi.WITHDRAW_TAG, page)) {
                            activity.finish();
                        }
                    }
                    return;
                }

                if (TextUtils.equals(WebApi.openCourseDetail, api)) {
                    JSONObject content = jsonObject.getJSONObject("content");
                    String courseId = content.optString("courseId");
                    if (!TextUtils.isEmpty(courseId)) {
                        ARouter.getInstance().build(RouterPath.CourseCenter.PIANO_ROOM_COURSE_DETAIL)
                                .withString("course_id", courseId)
                                .navigation();
                    }
                    return;
                }
            } 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 setOnItemClickListener(onGetMethodsListener onListener) {
        this.onListener = onListener;
    }

    public interface onGetMethodsListener {
        void onSendMessage(String message);

        void setStatusBarTextColor(boolean statusBarTextColor);

        void onAccompanySelecResult(String id, String name);

        void downloadFile(String url);

        /**
         * 选择文件
         *
         * @param message
         */
        void chooseFile(JSONObject message);

        //分享
        void createRightNavToShareButton(String image, String url);

        void shareAchievements(JSONObject message);

        /**
         * 顶部栏返回按钮颜色
         * {iconStyle:  black , white}
         *
         * @param message
         */
        void backIconChange(JSONObject message);

        /**
         * 返回顶部高度
         * 顶部栏高度
         * 以及dpi
         *
         * @param message
         */
        void getNavHeight(JSONObject message);

        /**
         * 顶部栏控制
         *
         * @param message
         */
        void setBarStatus(JSONObject message);

        void authToBack(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);
    }

}
