package com.easemob.veckit;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import androidx.annotation.Nullable;

import com.easemob.veckit.bean.EntityBean;
import com.easemob.veckit.bean.VideoStyleBean;
import com.easemob.veckit.floating.FloatWindowManager;
import com.easemob.veckit.utils.Utils;
import com.easemob.veckit.utils.VecKitOptions;
import com.hyphenate.agora.FunctionIconItem;
import com.hyphenate.agora.ZuoXiSendRequestObj;
import com.hyphenate.chat.AgoraMessage;
import com.hyphenate.chat.ChatClient;
import com.hyphenate.chat.ChatManager;
import com.hyphenate.chat.EMCmdMessageBody;
import com.hyphenate.chat.FlatFunctionUtils;
import com.hyphenate.chat.Message;
import com.hyphenate.chat.VecConfig;
import com.hyphenate.exceptions.HyphenateException;
import com.hyphenate.helpdesk.callback.ValueCallBack;
import com.hyphenate.util.EMLog;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;
import java.util.Map;
import java.util.UUID;

public class VECKitCalling extends Activity {
    private final static String TAG = "VECKitCalling";

    public static String callingUUID = "";

    public static String cancelCallingUUID = "";

    private String mToChatUserName;
    private ProgressDialog mDialog;

    // 主动请求
    public static void callingRequest(Context context, String vecImServiceNumber, String configId) {
        // TODO 临时给中意使用 不显示发起页面
        // VecKitOptions.getVecKitOptions().setShowCallingView(false);

        ChatClient.getInstance().changeConfigId(configId);
        callingRequest(context, vecImServiceNumber, configId, null, null, null, 0, 0, "");
    }

    // 主动请求

    /**
     * 主动请求 用在询前引导页面，点击条目发起视频通话
     *
     * @param context                context
     * @param vecImServiceNumber     vec视频的IM服务号
     * @param configId               configId
     * @param guideSessionId         会话id
     * @param visitorUserId          访客id
     * @param relatedImServiceNumber 会话IM服务号
     */
    public static void callingRequest(Context context, String vecImServiceNumber, String configId, String guideSessionId,
                                      String visitorUserId, String relatedImServiceNumber,
                                      int queueId, int menuId, String queueType) {
        VecKitOptions.getVecKitOptions().setGuideConfigId(configId);
        VecKitOptions.getVecKitOptions().setGuideSessionId(guideSessionId);
        VecKitOptions.getVecKitOptions().setGuideVisitorUserId(visitorUserId);
        VecKitOptions.getVecKitOptions().setRelatedImServiceNumber(relatedImServiceNumber);
        VecKitOptions.getVecKitOptions().setGuideQueueId(queueId);
        VecKitOptions.getVecKitOptions().setGuideMenuId(menuId);
        VecKitOptions.getVecKitOptions().setGuideQueueType(queueType);

        /*Intent intent = new Intent(context, VECKitCalling.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.putExtra(VideoCallWindowService.CURRENT_CHAT_USER_NAME, vecImServiceNumber);
        context.startActivity(intent);*/

        if (!TextUtils.isEmpty(guideSessionId) && !TextUtils.isEmpty(relatedImServiceNumber)) {
            // TODO 临时给中意使用 不显示发起页面
            VecKitOptions.getVecKitOptions().setShowCallingView(true);
        }

        //AgoraMessage.newAgoraMessage().setVecImServiceNumber(vecImServiceNumber);
        EMLog.e(TAG, "通过训前引导 主动发起请求 callingRequest vecImServiceNumber = " + vecImServiceNumber + "，configId = " + configId + "，isShowCallingView = " + VecKitOptions.getVecKitOptions().isShowCallingView());
        if (VecKitOptions.getVecKitOptions().isShowCallingView()) {
            Intent intent = new Intent(context, VECKitCalling.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.putExtra(VideoCallWindowService.CURRENT_CHAT_USER_NAME, vecImServiceNumber);
            context.startActivity(intent);
        } else {
            noHavView(context, vecImServiceNumber);
        }
    }

    // 满意度评价
    /*public static void callingEvaluation(Context context, String content){
        if (!VecConfig.newVecConfig().isPopupView()){
            CallVideoActivity.startDialogTypeRetry(context, content);
        }
    }*/

    // 满意度评价
    public static void callingEvaluation(Context context, String from, String content) {
        if (!VecConfig.newVecConfig().isPopupView()) {
            CallVideoActivity.startDialogTypeRetry(context, from, content);
        }
    }

    // 被动请求
    public static void callingResponse(Context context, Intent intent) {
        if (intent.hasExtra("message")) {
            Message message = (Message) intent.getParcelableExtra("message");
            Map<String, Object> exts = message.ext();
            if (exts.containsKey(Message.KEY_MSGTYPE)) {
                try {
                    JSONObject msgtype = message.getJSONObjectAttribute(Message.KEY_MSGTYPE);
                    if (msgtype.has("sendVisitorTicket") && !msgtype.isNull("sendVisitorTicket")) {
                        JSONObject sendVisitorTicket = msgtype.optJSONObject("sendVisitorTicket");
                        if (sendVisitorTicket != null && sendVisitorTicket.has("callingUUID") && !sendVisitorTicket.isNull("callingUUID")) {
                            String tmpUUID = sendVisitorTicket.optString("callingUUID");
                            Log.d(TAG, "测试结果：" + tmpUUID);
                            //如果访客发起的视频，已经被访客取消之后，坐席接听，判断UUID是否一致
                            if (!TextUtils.isEmpty(tmpUUID) && tmpUUID.equals(cancelCallingUUID)) {
                                Log.d(TAG, "测试结果：" + tmpUUID + " 已取消");
                                cancelCallingUUID = "";
                                return;
                            }
                        }
                    }
                } catch (HyphenateException e) {
                    e.printStackTrace();
                }
            }
        }

        // CallVideoActivity.callingResponse(context, intent);
        EMLog.e(TAG, "VEC 页面 被动收到通知 是否显示呼叫页面 = " + VecKitOptions.getVecKitOptions().isShowCallingView());
        if (VecKitOptions.getVecKitOptions().isShowCallingView()) {
            CallVideoActivity.callingResponse(context, intent);
        } else {
            int navHeight = 0;
            String toChatUserName = intent.getStringExtra("from");
            EMLog.e(TAG, "VEC 页面 被动收到通知 是否显示呼叫页面 toChatUserName = " + toChatUserName);
            // 先获取本地样式，本地样式没有，获取网络
            String localData = getLocalData(context, toChatUserName);
            if (!TextUtils.isEmpty(localData)) {
                try {
                    EntityBean entityBean = new EntityBean(localData);
                    VideoStyleBean videoStyleBean = entityBean.getVideoStyleBean(context);
                    VecConfig.newVecConfig().setCameraState(videoStyleBean.getFunctionSettings().isVisitorCameraOff());
                } catch (Exception e) {
                    e.printStackTrace();
                }
                getStyle(true, context, intent, toChatUserName, navHeight);
            } else {
                // 请求网络，覆盖本地样式
                getStyle(false, context, intent, toChatUserName, navHeight);
            }
        }

        /*// 1是坐席主动发送邀请，0是访客主动邀请，坐席响应
        int zuo_xi_active = intent.getIntExtra("zuo_xi_active", 0);
        if (zuo_xi_active == 0){
            if (VECKitCalling.sShowCallingView){
                CallVideoActivity.callingResponse(context, intent);
            }else {
                int navHeight = 0;
                String toChatUserName = intent.getStringExtra("from");

                // 先获取本地样式，本地样式没有，获取网络
                String localData = getLocalData(context, toChatUserName);
                if (!TextUtils.isEmpty(localData)){
                    try {
                        EntityBean entityBean = new EntityBean(localData);
                        VideoStyleBean videoStyleBean = entityBean.getVideoStyleBean(context);
                        VecConfig.newVecConfig().setCameraState(videoStyleBean.getFunctionSettings().isVisitorCameraOff());
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                    getStyle(true, context, intent, toChatUserName, navHeight);
                }else {
                    // 请求网络，覆盖本地样式
                    getStyle(false, context, intent, toChatUserName, navHeight);
                }
            }
        }else {
            CallVideoActivity.callingResponse(context, intent);
        }*/
    }

    private static void openCallingService(Context context, Intent intent, String toChatUserName, int navHeight) {
        if (FloatWindowManager.getInstance().checkPermission(context)) {
            intent.putExtra("nav_height", navHeight);
            VideoCallWindowService.show(context, toChatUserName, intent);
        } else {
            CallActivity.show(context, toChatUserName, intent);
        }
    }

    private static void getStyle(boolean isRun, Context context, Intent intent, String toChatUserName, int navHeight) {
        if (isRun) {
            openCallingService(context, intent, toChatUserName, navHeight);
            netStyle(context, toChatUserName, null);
        } else {
            netStyle(context, toChatUserName, new ValueCallBack<String>() {
                @Override
                public void onSuccess(String s) {
                    openCallingService(context, intent, toChatUserName, navHeight);
                }

                @Override
                public void onError(int i, String s) {
                    openCallingService(context, intent, toChatUserName, navHeight);
                }
            });
        }
    }

    private static void netStyle(Context context, String toChatUserName, ValueCallBack<String> callBack) {
        String tenantId = ChatClient.getInstance().tenantId();// "77556"
        String configId = getConfigId();
        AgoraMessage.asyncInitStyle(tenantId, configId, new ValueCallBack<String>() {
            @Override
            public void onSuccess(String value) {
                try {
                    JSONObject jsonObject = new JSONObject(value);
                    if (!jsonObject.has("status")) {
                        if (callBack != null) {
                            callBack.onSuccess("");
                        }
                        return;
                    }
                    String status = jsonObject.getString("status");
                    if (!"ok".equalsIgnoreCase(status)) {
                        if (callBack != null) {
                            callBack.onSuccess("");
                        }
                        return;
                    }

                    // 存起来
                    JSONObject entity = jsonObject.getJSONObject("entity");
                    String json = entity.toString();
                    saveLocalData(context, json, toChatUserName);
                    EntityBean entityBean = new EntityBean(json);
                    VideoStyleBean videoStyleBean = entityBean.getVideoStyleBean(context);
                    VecConfig.newVecConfig().setCameraState(videoStyleBean.getFunctionSettings().isVisitorCameraOff());

                    if (callBack != null) {
                        callBack.onSuccess("");
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    if (callBack != null) {
                        callBack.onSuccess("");
                    }
                }

            }

            @Override
            public void onError(int error, String errorMsg) {
                if (callBack != null) {
                    callBack.onError(error, errorMsg);
                }
            }
        });
    }

    private static void saveLocalData(Context context, String entity, String toChatUserName) {
        // 保存本地
        SharedPreferences sharedPreferences = context.getSharedPreferences("video_style", MODE_PRIVATE);
        SharedPreferences.Editor edit = sharedPreferences.edit();
        edit.putString(String.format(CallVideoActivity.JSON_KEY, toChatUserName), entity);
        edit.apply();
    }

    private static String getLocalData(Context context, String toChatUserName) {
        SharedPreferences sharedPreferences = context.getSharedPreferences("video_style", MODE_PRIVATE);
        return sharedPreferences.getString(String.format(CallVideoActivity.JSON_KEY, toChatUserName), "");
    }


    // VEC 坐席主动发起视频邀请 通知
    public static void onAgentRequest(Context context, String msg, String sessionId, Message message) {
        Intent intent = new Intent();
        intent.putExtra("zuo_xi_active", 1); // 1 为坐席主动发送视频邀请
        intent.putExtra("msg", msg);
        intent.putExtra("to", message.to());
        intent.putExtra("from", message.from());
        intent.putExtra("message", message);
        intent.putExtra("sessionId", sessionId);
        callingResponse(context, intent);
    }

    // VEC 坐席主动发起视频邀请，访客接听，响应
    public static void onVisitorAnswerResponse(Context context, ZuoXiSendRequestObj obj, String sessionId, Message message) {
        Intent intent = new Intent();
        intent.putExtra("zuo_xi_active", 2); // 1 为坐席主动发送视频邀请
        intent.putExtra("zuoXiSendRequestObj", obj);
        intent.putExtra("to", message.to());
        intent.putExtra("from", message.from());
        intent.putExtra("message", message);
        intent.putExtra("sessionId", sessionId);
        callingResponse(context, intent);
    }

    // VEC 访客主动发送视频邀请，坐席接通
    public static void onAgentAnswerResponse(Context context, ZuoXiSendRequestObj obj, String sessionId, Message message) {
        Intent intent = new Intent();
        intent.putExtra("zuo_xi_active", 0); // 1 为坐席主动发送视频邀请
        intent.putExtra("zuoXiSendRequestObj", obj);
        intent.putExtra("to", message.to());
        intent.putExtra("from", message.from());
        intent.putExtra("message", message);
        intent.putExtra("sessionId", sessionId);
        callingResponse(context, intent);
    }

    // 满意度评价
    public static void onEvaluation(Context context, String content, Message message) {
        if (!VecConfig.newVecConfig().isPopupView()) {
            CallVideoActivity.startDialogTypeRetry(context, message.from(), content);
        }
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Intent intent = getIntent();
        mToChatUserName = intent.getStringExtra(VideoCallWindowService.CURRENT_CHAT_USER_NAME);
        mDialog = new ProgressDialog(this);
        mDialog.setCanceledOnTouchOutside(false);
        mDialog.setCancelable(false);
        mDialog.setMessage(Utils.getString(getApplicationContext(), R.string.vec_loading));

        EMLog.e(TAG, "VECKitCalling onCreate mToChatUserName = " + mToChatUserName);

        // 请求灰度
        // getTenantIdFunctionIcons();

        String configId = getConfigId();
        if (TextUtils.isEmpty(configId)) {
            Toast.makeText(VECKitCalling.this, Utils.getString(getApplicationContext(), R.string.vec_config_setting), Toast.LENGTH_LONG).show();
            finish();
            return;
        }

        mDialog.show();
        if (VecConfig.newVecConfig().isEnableVecVideo()) {
            requestInfo();
        } else {
            showToast(VECKitCalling.this, Utils.getString(getApplicationContext(), R.string.vec_no_permission));
            if (mDialog != null && mDialog.isShowing()) {
                mDialog.dismiss();
            }
            finish();
        }
    }

    private void request() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                String tenantId = ChatClient.getInstance().tenantId();// "77556"
                String configId = getConfigId();
                if (TextUtils.isEmpty(configId)) {
                    mDialog.dismiss();
                    Toast.makeText(VECKitCalling.this, Utils.getString(getApplicationContext(), R.string.vec_config_setting), Toast.LENGTH_LONG).show();
                    finish();
                    return;
                }
                AgoraMessage.asyncInitStyle(tenantId, configId, new ValueCallBack<String>() {
                    @Override
                    public void onSuccess(String value) {
                        try {
                            JSONObject jsonObject = new JSONObject(value);
                            if (!jsonObject.has("status")) {
                                return;
                            }
                            String status = jsonObject.getString("status");
                            if (!"ok".equalsIgnoreCase(status)) {
                                return;
                            }

                            // 存起来
                            JSONObject entity = jsonObject.getJSONObject("entity");
                            if (isFinishing()) {
                                return;
                            }

                            String json = entity.toString();
                            to(json);

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }

                    @Override
                    public void onError(int error, String errorMsg) {
                        to("");
                    }
                });
            }
        });

    }

    /*private void getSettingShareScreen() {
        // 同步方法获取
        try {
            String settingShareScreen = ChatClient.getInstance().chatManager().getSettingShareScreen(ChatClient.getInstance().tenantId());
            Log.e("VECKitCalling","getSettingShareScreen = "+settingShareScreen);
            JSONObject object = new JSONObject(settingShareScreen);
            if (object.has("status")){
                String status = object.getString("status");
                if ("OK".equalsIgnoreCase(status)){
                    if (object.has("entities")){
                        JSONArray entities = object.getJSONArray("entities");
                        JSONObject jsonObject = entities.getJSONObject(0);
                        boolean optionValue = jsonObject.getBoolean("optionValue");
                        Log.e("ppppppppp","optionValue = "+optionValue);
                        VecConfig.newVecConfig().setShareScreen(optionValue);
                    }
                }
            }
        }catch (Exception e){
            e.printStackTrace();
            Log.e("VECKitCalling","getSettingShareScreen error = "+e.getMessage());
        }

    }*/

    private void to(String json) {
        runOnUiThread(() -> {
            mDialog.dismiss();
            CallVideoActivity.callingRequest(getApplicationContext(), mToChatUserName, json);
            finish();
        });
    }


    /**
     * 坐席发起视频邀请。访客发送接通信令
     *
     * @param content 显示内容
     */
    public static void acceptCallFromZuoXi(String content) {
        String to = AgoraMessage.newAgoraMessage().getVecImServiceNumber();
        AgoraMessage.acceptVecCallFromZuoXi(content, to);
    }

    /**
     * 坐席发起视频邀请，访客未接通状态。访客发送挂断信令
     *
     * @param content 显示内容
     */
    public static void endVecCallFromZuoXi(String content) {
        String to = AgoraMessage.newAgoraMessage().getVecImServiceNumber();
        AgoraMessage.endVecCallFromZuoXi(content, to);
        VecKitOptions.getVecKitOptions().setShowCallingView(true);
    }

    /**
     * 视频已接通。发送挂断信令
     *
     * @param callBack 回调函数
     */
    public static void endCallFromOn(String sessionId, String visitorId, ValueCallBack<String> callBack) {
        AgoraMessage.endVecCallFromOn(sessionId, visitorId, callBack);
        VecKitOptions.getVecKitOptions().setShowCallingView(true);
    }

    /**
     * 主动发起视频邀请，坐席未接通状态。主动发送挂断信令
     */
    public static void endCallFromOff() {
        cancelCallingUUID = callingUUID;
        callingUUID = "";
        String to = AgoraMessage.newAgoraMessage().getVecImServiceNumber();
        AgoraMessage.endVecCallFromOff(to);
        VecKitOptions.getVecKitOptions().setShowCallingView(true);
    }

    /**
     * 主动发起视频邀请
     *
     * @param content            文本内容
     * @param vecImServiceNumber im服务号
     */
    public static void callVecVideo(String content, String vecImServiceNumber) {
        //AgoraMessage.callVecVideo(content, vecImServiceNumber);

        // 通过回调返回Message，给消Message添加业务标识
        AgoraMessage.callVecVideo(content, vecImServiceNumber, new AgoraMessage.MessageCall() {
            @Override
            public void getMessage(Message message) {
                /*JSONObject sessionExt = null;
                try {
                    sessionExt = message.getJSONObjectAttribute("sessionExt");
                } catch (Exception var3) {
                    var3.printStackTrace();
                }

                if (sessionExt == null){
                    sessionExt = new JSONObject();
                }*/

                callingUUID = UUID.randomUUID().toString();
                try {
                    JSONObject sessionExt = new JSONObject();
                    sessionExt.put("callingUUID", callingUUID);
//                    sessionExt.put("businessType","业务类型Android");
//                    sessionExt.put("businessSubtype","业务子类型Android");
                    sessionExt.put("source", "relatedSession");
                    message.setAttribute("sessionExt", sessionExt);
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        });

        /*VecConfig.newVecConfig().setPopupView(true);
        Message message = Message.createVecVideoInviteSendMessage(content, vecImServiceNumber);
        try {
            JSONObject object = new JSONObject();
            object.put("业务标识路由定义的key","业务标识路由对应的值");
            message.setAttribute(Message.KEY_WEICHAT,object);
        } catch (Exception var3) {
            var3.printStackTrace();
        }
        ChatClient.getInstance().chatManager().sendMessage(message, new Callback() {
            public void onSuccess() {
                if (VecConfig.newVecConfig().isEnableReport()) {
                    ChatClient.getInstance().chatManager().sendVecReport(vecImServiceNumber);
                }

            }

            public void onError(int code, String error) {
            }

            public void onProgress(int progress, String status) {
            }
        });*/


        /*Message sendMessage = Message.createSendMessage(Message.Type.CMD);
        sendMessage.setTo(vecImServiceNumber);



        ChatClient.getInstance().chatManager().sendMessage(sendMessage);*/
    }


    /**
     * 训前引导 主动发起视频邀请
     *
     * @param content                文本内容
     * @param vecImServiceNumber     im服务号 视频
     * @param sessionId              在线会话id
     * @param relatedVisitorUserId   访客id
     * @param relatedImServiceNumber 当前会话的IM服务号
     */
    public static void callVecVideo(String content, String vecImServiceNumber, String sessionId, String relatedVisitorUserId, String relatedImServiceNumber) {

        int guideQueueId = VecKitOptions.getVecKitOptions().getGuideQueueId();
        int guideMenuId = VecKitOptions.getVecKitOptions().getGuideMenuId();
        String guideQueueType = VecKitOptions.getVecKitOptions().getGuideQueueType();

        AgoraMessage.callVecVideo(content, vecImServiceNumber, sessionId, relatedVisitorUserId, relatedImServiceNumber,
                guideQueueId, guideMenuId, guideQueueType, new AgoraMessage.MessageCall() {
                    @Override
                    public void getMessage(Message message) {
                        callingUUID = UUID.randomUUID().toString();
                        try {
                            JSONObject sessionExt = new JSONObject();
//                            sessionExt.put("businessType", "ship");
//                            sessionExt.put("businessSubtype", "回访");
                            sessionExt.put("source", "relatedSession");
                            sessionExt.put("callingUUID", callingUUID);
                            message.setAttribute("sessionExt", sessionExt);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });

        /*VecConfig.newVecConfig().setPopupView(true);
        Message message = Message.createVecVideoInviteSendMessage(content, vecImServiceNumber);
        try {
            if (!TextUtils.isEmpty(sessionId)) {
                // 询前引导需要的参数
                JSONObject sessionExt = new JSONObject();
                sessionExt.put("relatedSessionId", sessionId);
                sessionExt.put("relatedVisitorUserId", relatedVisitorUserId);
                sessionExt.put("source", "relatedSession");
                sessionExt.put("relatedImServiceNum", relatedImServiceNumber);

                sessionExt.put("queueId", VecKitOptions.getVecKitOptions().getGuideQueueId());
                sessionExt.put("menuId", VecKitOptions.getVecKitOptions().getGuideMenuId());
                sessionExt.put("queueType", VecKitOptions.getVecKitOptions().getGuideQueueType());

                // String guideQueueId, String guideMenuId, String guideQueueType
                message.setAttribute("sessionExt", sessionExt);
            }

            JSONObject object = new JSONObject();
            object.put("业务标识路由定义的key","业务标识路由对应的值");
            message.setAttribute(Message.KEY_WEICHAT,object);

        } catch (Exception var7) {
            var7.printStackTrace();
        }

        ChatClient.getInstance().chatManager().sendMessage(message, new Callback() {
            public void onSuccess() {
                if (VecConfig.newVecConfig().isEnableReport()) {
                    ChatClient.getInstance().chatManager().sendVecReport(vecImServiceNumber);
                }

            }

            public void onError(int code, String error) {
            }

            public void onProgress(int progress, String status) {
            }
        });*/
    }


    // 辅助功能，手电筒，闪光灯相关信令
    public static void sendNotify(String action, String type, String state, String msg) {
        String toUserName = AgoraMessage.newAgoraMessage().getVecImServiceNumber();
        Message message = Message.createSendMessage(Message.Type.CMD);
        message.setBody(new EMCmdMessageBody(action));
        message.setTo(toUserName);
        try {
            JSONObject obj = new JSONObject();
            JSONObject flashlightcallback = new JSONObject();
            flashlightcallback.put("action", state);
            obj.put("msg", msg);
            obj.put(type, flashlightcallback);

            message.setAttribute("type", "agorartcmedia/video");
            message.setAttribute("msgtype", obj);
            message.setAttribute("targetSystem", "kefurtc");

        } catch (Exception e) {
            e.printStackTrace();
        }
        ChatManager.getInstance().sendMessage(message);
    }

    // 接通，挂断，或者未接通挂断
    @SuppressWarnings("SameParameterValue")
    private static Message requestOnAndOffMessage(int callId, String toUserName) {
        Message message = Message.createSendMessage(Message.Type.CMD);
        message.setBody(new EMCmdMessageBody(""));
        message.setTo(toUserName);

        try {
            JSONObject object = new JSONObject();
            JSONObject call = new JSONObject();
            call.put("callId", ((callId > 0) ? String.valueOf(callId) : "null"));
            object.put("visitorCancelInvitation", call);

            message.setAttribute("type", "agorartcmedia/video");
            message.setAttribute("msgtype", object);
            message.setAttribute("targetSystem", "kefurtc");
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return message;
    }

    private static void getTenantIdFunctionIcons() {
        // 动态获取功能按钮，在视频页面使用到
        AgoraMessage.asyncGetTenantIdFunctionIcons(ChatClient.getInstance().tenantId(), new ValueCallBack<List<FunctionIconItem>>() {
            @Override
            public void onSuccess(List<FunctionIconItem> value) {
                FlatFunctionUtils.get().setIconItems(value);
            }

            @Override
            public void onError(int error, String errorMsg) {

            }
        });
    }

    private void requestInfo() {
        AgoraMessage.asyncGetInfo(ChatClient.getInstance().tenantId(), new ValueCallBack<String>() {
            @Override
            public void onSuccess(String value) {
                parseInfoData(value);
                request();
            }

            @Override
            public void onError(int error, String errorMsg) {
                request();
            }
        });
    }

    private void parseInfoData(String value) {
        try {
            JSONObject data = new JSONObject(value);
            JSONObject entity = data.getJSONObject("entity");
            VecConfig.newVecConfig().setTenantName(entity.getString("name"));
            String avatar = entity.getString("avatar");
            int i = avatar.indexOf("kefu.sh.absoloop.com");
            if (i == -1 && avatar.startsWith("http")) {
                VecConfig.newVecConfig().setAvatarImage(ChatClient.getInstance().kefuRestServer().concat(avatar));
            } else {
                if (i > -1) {
                    avatar = avatar.substring(i + "kefu.sh.absoloop.com".length());
                }
                VecConfig.newVecConfig().setAvatarImage(ChatClient.getInstance().kefuRestServer().concat(avatar));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void showToast(Context context, String content) {
        Toast.makeText(context.getApplicationContext(), content, Toast.LENGTH_LONG).show();
    }

    private static String getConfigId() {
        String relatedImServiceNumber = VecKitOptions.getVecKitOptions().getRelatedImServiceNumber();
        if (!TextUtils.isEmpty(relatedImServiceNumber)) {
            return VecKitOptions.getVecKitOptions().getGuideConfigId();
        }
        return ChatClient.getInstance().getConfigId();
    }

    public static String getGuideSessionId() {
        return VecKitOptions.getVecKitOptions().getGuideSessionId();
    }

    public static String getGuideImServiceNumber() {
        return VecKitOptions.getVecKitOptions().getRelatedImServiceNumber();
    }

    public static String getVisitorUserId() {
        return VecKitOptions.getVecKitOptions().getGuideVisitorUserId();
    }

    private static void getSettingShareScreen(Context context, String vecImServiceNumber) {
        ChatClient.getInstance().chatManager().asyncGetSettingShareScreen(ChatClient.getInstance().tenantId(), new ValueCallBack<String>() {
            @Override
            public void onSuccess(String value) {
                try {
                    JSONObject object = new JSONObject(value);
                    if (object.has("status")) {
                        String status = object.getString("status");
                        if ("OK".equalsIgnoreCase(status)) {
                            if (object.has("entities")) {
                                JSONArray entities = object.getJSONArray("entities");
                                JSONObject jsonObject = entities.getJSONObject(0);
                                boolean optionValue = jsonObject.getBoolean("optionValue");
                                VecConfig.newVecConfig().setShareScreen(optionValue);
                            }
                        }
                    }
                    calling(context, vecImServiceNumber);
                } catch (Exception e) {
                    e.printStackTrace();
                    calling(context, vecImServiceNumber);
                    Log.e("VECKitCalling", "getSettingShareScreen error = " + e.getMessage());
                }
            }

            @Override
            public void onError(int error, String errorMsg) {
                calling(context, vecImServiceNumber);
            }
        });
    }

    private static void noHavView(Context context, String vecImServiceNumber) {
        if (VecConfig.newVecConfig().isEnableVecVideo()) {
            AgoraMessage.newAgoraMessage().setVecImServiceNumber(vecImServiceNumber);
            getSettingShareScreen(context, vecImServiceNumber);
        } else {
            Log.e("VECKitCalling", "isEnableVecVideo = false vec没开通，不可用！");
        }
    }

    private static void calling(Context context, String vecImServiceNumber) {
        // CallVideoActivity.callingRequest(context, vecImServiceNumber, json);
        String guideSessionId = VECKitCalling.getGuideSessionId();
        String visitorUserId = VECKitCalling.getVisitorUserId();
        String relatedImServiceNumber = VECKitCalling.getGuideImServiceNumber();
        if (TextUtils.isEmpty(guideSessionId)) {
            VECKitCalling.callVecVideo(Utils.getString(context, R.string.vec_agent_to_visitor), vecImServiceNumber);
        } else {
            VECKitCalling.callVecVideo(Utils.getString(context, R.string.vec_agent_to_visitor), vecImServiceNumber, guideSessionId, visitorUserId, relatedImServiceNumber);
        }
    }

}
