package com.datarecovery.master.sdk.qiyu;

import android.app.AlertDialog;
import android.app.Application;
import android.content.Context;
import android.content.DialogInterface;
import android.text.TextUtils;
import android.widget.Toast;

import com.atmob.common.data.KVUtils;
import com.atmob.common.logging.AtmobLog;
import com.atmob.common.runtime.ContextUtil;
import com.datarecovery.master.BuildConfig;
import com.datarecovery.master.R;
import com.datarecovery.master.data.repositories.AccountRepository;
import com.datarecovery.master.dialog.CommonSureDialog;
import com.datarecovery.master.module.browser.BrowserActivity;
import com.datarecovery.master.utils.SystemUtil;
import com.qiyukf.nimlib.sdk.RequestCallback;
import com.qiyukf.nimlib.sdk.StatusBarNotificationConfig;
import com.qiyukf.unicorn.api.OnMessageItemClickListener;
import com.qiyukf.unicorn.api.UICustomization;
import com.qiyukf.unicorn.api.Unicorn;
import com.qiyukf.unicorn.api.YSFOptions;
import com.qiyukf.unicorn.api.YSFUserInfo;
import com.qiyukf.unicorn.api.event.EventCallback;
import com.qiyukf.unicorn.api.event.EventProcessFactory;
import com.qiyukf.unicorn.api.event.SDKEvents;
import com.qiyukf.unicorn.api.event.UnicornEventBase;
import com.qiyukf.unicorn.api.event.entry.RequestPermissionEventEntry;

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

public class QiYuHelper {

    private static final String TAG = "QiYuHelper";

    private static final String ysfAppId = BuildConfig.QIYU_APP_KEY;
    private static final String VISITOR_KEY = "visitor_key";

    public static void init(Application application) {
        Unicorn.config(application, ysfAppId, options(), new GlideImageLoader(application));
    }

    public static void initSdk() {
        Unicorn.initSdk();
        if (TextUtils.isEmpty(AccountRepository.token)) {
            setVisitorInfo();
        }
    }


    private static void setVisitorInfo() {
        YSFUserInfo userInfo = new YSFUserInfo();
        userInfo.userId = getUserId();
        String appName = ContextUtil.getContext().getString(R.string.app_name) + "-访客";
        // CRM 扩展字段
        userInfo.data = "[\n" +
                "    {\"key\":\"real_name\", \"value\":\"" + appName + "\"},\n" +
                getAppCommonInfo() +
                "]";
        Unicorn.setUserInfo(userInfo, new RequestCallback<Void>() {
            @Override
            public void onSuccess(Void aVoid) {
                AtmobLog.d(TAG, "set visitor info success");
            }

            @Override
            public void onFailed(int errorCode) {
                AtmobLog.d(TAG, "set visitor info failed, errorCode: " + errorCode);
            }

            @Override
            public void onException(Throwable throwable) {
                AtmobLog.d(TAG, "set visitor info exception: " + throwable.getMessage());
            }
        });
    }


    private static YSFOptions options() {
        YSFOptions options = new YSFOptions();
        options.statusBarNotificationConfig = new StatusBarNotificationConfig();
        options.onMessageItemClickListener = BrowserActivity::start;
        options.sdkEvents = new SDKEvents();
        options.sdkEvents.eventProcessFactory = eventType -> {
            if (eventType == 5) {
                return new RequestPermissionEvent();
            }
            return null;
        };
        return options;
    }

    public static class RequestPermissionEvent implements UnicornEventBase<RequestPermissionEventEntry> {
        private final Map<String, String> h5MessageHandlerMap = new HashMap<>();


        public RequestPermissionEvent() {
            h5MessageHandlerMap.put("android.permission.RECORD_AUDIO", "麦克风");
            h5MessageHandlerMap.put("android.permission.CAMERA", "相机");
            h5MessageHandlerMap.put("android.permission.READ_EXTERNAL_STORAGE", "存储");
            h5MessageHandlerMap.put("android.permission.WRITE_EXTERNAL_STORAGE", "存储");
            h5MessageHandlerMap.put("android.permission.READ_MEDIA_AUDIO", "多媒体文件");
            h5MessageHandlerMap.put("android.permission.READ_MEDIA_IMAGES", "多媒体文件");
            h5MessageHandlerMap.put("android.permission.READ_MEDIA_VIDEO", "多媒体文件");
            h5MessageHandlerMap.put("android.permission.POST_NOTIFICATIONS", "通知栏权限");
        }

        /**
         * @param requestPermissionEventEntry 获取权限相关的类
         * @param context                     当前界面的 context 对象，使用之前请判断是否为 null
         * @param callback                    sdk 的回调对象  注意：如果该事件 sdk 不需要回调的时候，这个对象会为 null，所以当使用的时候需要做一下非null判断
         */
        @Override
        public void onEvent(RequestPermissionEventEntry requestPermissionEventEntry, Context context, EventCallback<RequestPermissionEventEntry> callback) {

            //申请权限的场景
            //从本地选择媒体文件(视频和图片):0
            //拍摄视频场景:1
            //保存图片到本地:2
            //保存视频到本地:3
            //选择本地视频:4
            //选择本地文件:5
            //选择本地图片:6
            //拍照:7
            //录音:8
            //视频客服:9
            //通知栏权限:10
            int type = requestPermissionEventEntry.getScenesType();
            String content = null;
            switch (type) {
                case 4:
                    content = "使用视频权限，用于发送视频文件，与在线客服联系并协助您解答疑惑";
                    break;
                case 0:
                case 5:
                    content = "使用存储权限，用于发送文件，与在线客服联系并协助您解答疑惑";
                    break;
                case 6:
                    content = "使用相册权限，用于发送图片文件，与在线客服联系并协助您解答疑惑";
                    break;
                case 7:
                    content = "使用相机拍摄权限，用于发送图片，与在线客服联系并协助您解答疑惑";
                    break;
                case 8:
                    content = "使用麦克风录音权限，用于发送语音，与在线客服联系并协助您解答疑惑";
                    break;
            }
            if (TextUtils.isEmpty(content)) {
                callback.onProcessEventSuccess(requestPermissionEventEntry);
            } else {
                CommonSureDialog permissionDialog = new CommonSureDialog(context);
                permissionDialog.setDialogTitle(R.string.dialog_kind_tips);
                permissionDialog.setDialogContent(content);
                permissionDialog.setOnDialogClickListener(() -> callback.onProcessEventSuccess(requestPermissionEventEntry));
                permissionDialog.show();
            }
        }

    }

    /**
     * 账号注销使用
     */
    public static void logout() {
        Unicorn.logout();
        KVUtils.getDefault().putString(VISITOR_KEY, null);
    }

    public static void openServiceActivity(Context context) {
        Unicorn.openServiceActivity(context, "客服", null);
    }

    private static String getUserId() {
        String userId;
        if (TextUtils.isEmpty(userId = KVUtils.getDefault().getString(VISITOR_KEY, null))) {
            userId = UUID.randomUUID().toString();
            KVUtils.getDefault().putString(VISITOR_KEY, userId);
        }
        return userId;
    }

    public static void setUserInfo(String phone, String serverUserId, String token) {
        YSFUserInfo userInfo = new YSFUserInfo();
        // App 的用户 ID
        userInfo.userId = getUserId();
        // 当且仅当开发者在管理后台开启了 authToken 校验功能时，该字段才有效
//        userInfo.authToken = token;
        String appName = ContextUtil.getContext().getString(R.string.app_name) + "-已登录";
        // CRM 扩展字段
        userInfo.data = "[\n" +
                "    {\"key\":\"real_name\", \"value\":\"" + appName + "\"},\n" +
                "    {\"index\":0, \"key\":\"version\", \"label\":\"用户Id\", \"value\":\"" + serverUserId + "\" },\n" +
                getAppCommonInfo() +
                "]";
        Unicorn.setUserInfo(userInfo, new RequestCallback<Void>() {
            @Override
            public void onSuccess(Void aVoid) {
                AtmobLog.d(TAG, "set visitor info success");
            }

            @Override
            public void onFailed(int errorCode) {
                AtmobLog.d(TAG, "set visitor info failed, errorCode: " + errorCode);
            }

            @Override
            public void onException(Throwable throwable) {
                AtmobLog.d(TAG, "set visitor info exception: " + throwable.getMessage());
            }
        });
    }

    private static String getAppCommonInfo() {
        String info = "    {\"index\":1, \"key\":\"version\", \"label\":\"应用版本\", \"value\":\"v" + SystemUtil.getVersionName(ContextUtil.getContext()) + "\" },\n" +
                "    {\"index\":2, \"key\":\"appName\", \"label\":\"应用名称\", \"value\":\"" + ContextUtil.getContext().getString(R.string.app_name) + "\" },\n" +
                "    {\"index\":3, \"key\":\"packageName\", \"label\":\"包名\", \"value\":\"" + ContextUtil.getApplication().getPackageName() + "\" },\n";
        return info;
    }
}
