package com.easemob.helpdeskdemo.ui;

import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.text.TextUtils;
import android.util.Log;

import com.easemob.helpdeskdemo.utils.Calling;
import com.easemob.veckit.VECKitCalling;
import com.google.gson.Gson;
import com.hyphenate.chat.ChatClient;
import com.hyphenate.chat.CustomBroadcastManager;
import com.hyphenate.chat.IBroadcastCallback;
import com.hyphenate.helpdesk.callback.ValueCallBack;
import com.hyphenate.helpdesk.model.TransferGuideMenuInfo;
import com.hyphenate.util.EMLog;

public class GuideMenuUtils implements IBroadcastCallback {
    private final static String TAG = "GuideMenuUtils";
    private static GuideMenuUtils sGuideMenuUtils;
    private final Gson gson = new Gson();

    public static GuideMenuUtils getGuideMenuUtils() {
        if (sGuideMenuUtils == null){
            synchronized (GuideMenuUtils.class){
                if (sGuideMenuUtils == null){
                    sGuideMenuUtils = new GuideMenuUtils();
                }
            }
        }
        return sGuideMenuUtils;
    }


    public static void sendBroadcast(Context context, TransferGuideMenuInfo.Item item,
                                     String vecImServiceNumber, String configId, String cecImServiceNumber, String sessionId){
        // TransferGuideMenuInfo.Item
        try {
            Gson gson = new Gson();
            Intent intent = new Intent("guide.menu.item.action");
            intent.putExtra("data",gson.toJson(item));
            intent.putExtra("vecImServiceNumber",vecImServiceNumber);
            intent.putExtra("configId",configId);
            intent.putExtra("cecImServiceNumber",cecImServiceNumber);
            intent.putExtra("sessionId", sessionId);
            CustomBroadcastManager.getCustomBroadcastManager().sendBroadcast(context.getApplicationContext(),intent);
//            context.getApplicationContext().sendBroadcast(intent);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    // 需要在对应的聊天页面注册广播
    public void registerReceiver(Context context){
        try {
            IntentFilter filter = new IntentFilter("guide.menu.item.action");
//            context.getApplicationContext().registerReceiver(this, filter);
            CustomBroadcastManager.getCustomBroadcastManager().registerReceiver(this,filter);
            Log.e(TAG,"registerReceiver");
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    // 需要在对应的聊天页面注销广播
    public void unregisterReceiver(Context context){
        try {
//            context.getApplicationContext().unregisterReceiver(this);
            CustomBroadcastManager.getCustomBroadcastManager().unregisterReceiver(this);
            Log.e(TAG,"unregisterReceiver");
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        try{
            String data = intent.getStringExtra("data");
            String cecImServiceNumber = intent.getStringExtra("cecImServiceNumber");
            TransferGuideMenuInfo.Item item = gson.fromJson(data, TransferGuideMenuInfo.Item.class);
            int queueId = Integer.parseInt(item.getQueueId());
            int menuId = Integer.parseInt(item.getMenuId());
            String queueType = item.getQueueType();
            EMLog.e(TAG,"点击询前引导条目 data = "+data);

            if (item.getQueueType().equalsIgnoreCase("independentVideo")){
                closeCec(cecImServiceNumber, new ValueCallBack<String>() {
                    @Override
                    public void onSuccess(String value) {
                        sendVec(context, intent, value, cecImServiceNumber, queueId, menuId, queueType);
                    }

                    @Override
                    public void onError(int error, String errorMsg) {
                        Log.e(TAG,"询前引导 independentVideo closeCec 关闭会话失败 onError = "+errorMsg);
                        sendVec(context, intent,"",cecImServiceNumber, queueId, menuId, "");
                    }
                });

            }else if (item.getQueueType().equalsIgnoreCase("video")){
                Calling.callingRequestFromClickGuideMenu(context, cecImServiceNumber);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    private void sendVec(Context context, Intent intent, String sessionId, String relatedImServiceNumber,
                         int queueId, int menuId, String queueType){
        String vecImServiceNumber = intent.getStringExtra("vecImServiceNumber");
        String configId = intent.getStringExtra("configId");
        String sid = intent.getStringExtra("sessionId");
        sessionId = TextUtils.isEmpty(sessionId) ? sid : sessionId;
        if (!TextUtils.isEmpty(configId)){
            EMLog.e(TAG,"点击训前引导发送vec视频 sendVec vecImServiceNumber = "+vecImServiceNumber);
            VECKitCalling.callingRequest(context, vecImServiceNumber, configId, sessionId, mVisitorId,
                    relatedImServiceNumber, queueId, menuId, queueType);
        }else {
            EMLog.e(TAG,"点击训前引导发送vec视频 configId 为空！");
        }

    }

    private volatile String mVisitorId;
    public void closeCec(String imService, final ValueCallBack<String> valueCallBack){
        Log.d(TAG,"closeCec imService = "+imService);
        ChatClient.getInstance().chatManager().asyncVisitorId(imService, new ValueCallBack<String>() {
            @Override
            public void onSuccess(String value) {
                Log.d(TAG,"asyncVisitorId = "+value);
                mVisitorId = value;
                getSessionIdFromMessage(imService, new ValueCallBack<String>() {
                    @Override
                    public void onSuccess(String value) {
                        Log.d(TAG,"getCurrentSessionId = "+value);
                        String tenantId = ChatClient.getInstance().tenantId();
                        ChatClient.getInstance().chatManager().asyncCecClose(tenantId, mVisitorId, value, new ValueCallBack<String>() {
                            @Override
                            public void onSuccess(String value) {
                                Log.d(TAG,"asyncCecClose = "+value);
                                if (valueCallBack != null){
                                    valueCallBack.onSuccess(value);
                                }
                            }

                            @Override
                            public void onError(int error, String errorMsg) {
                                Log.d(TAG,"asyncCecClose errorMsg = "+errorMsg);
                                if (valueCallBack != null){
                                    valueCallBack.onError(error, errorMsg);
                                }
                            }
                        });
                    }

                    @Override
                    public void onError(int error, String errorMsg) {
                        Log.d(TAG,"getCurrentSessionId errorMsg = "+errorMsg);
                        if (valueCallBack != null){
                            valueCallBack.onError(error, errorMsg);
                        }
                    }
                });
            }

            @Override
            public void onError(int error, String errorMsg) {
                Log.d(TAG,"asyncVisitorId errorMsg = "+errorMsg);
                if (valueCallBack != null){
                    valueCallBack.onError(error, errorMsg);
                }
            }
        });


    }

    private void getSessionIdFromMessage(String imService, ValueCallBack<String> callBack){
        ChatClient.getInstance().chatManager().getCurrentSessionId(imService, new ValueCallBack<String>() {
            @Override
            public void onSuccess(String value) {
                Log.e(TAG,"getCurrentSessionId = "+value);
                if (callBack != null){
                    callBack.onSuccess(value);
                }
            }

            @Override
            public void onError(int error, String errorMsg) {
                Log.e(TAG,"getCurrentSessionId errorMsg = "+errorMsg);
                if (callBack != null){
                    callBack.onError(error, errorMsg);
                }
            }
        });
    }

}
