package com.datarecovery.master.sdk.qiyu;

import android.app.Application;
import android.content.Context;
import android.text.TextUtils;

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.utils.SystemUtil;
import com.qiyukf.nimlib.sdk.RequestCallback;
import com.qiyukf.nimlib.sdk.StatusBarNotificationConfig;
import com.qiyukf.unicorn.api.Unicorn;
import com.qiyukf.unicorn.api.YSFOptions;
import com.qiyukf.unicorn.api.YSFUserInfo;

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();
        return options;
    }

    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) + "-" + phone;
        // CRM 扩展字段
        userInfo.data = "[\n" +
                "    {\"key\":\"real_name\", \"value\":\"" + appName + "\"},\n" +
                "    {\"key\":\"mobile_phone\", \"hidden\":false, \"value\":\"" + phone + "\"},\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;
    }
}
