package com.yyrh.factory;

import static com.yyrh.constant.Constants.CLICK_INTERVAL;
import static com.yyrh.constant.URLConstants.PAYMENTWAY;

import android.Manifest;
import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.text.TextUtils;

import com.dolin.zap.Zap;
import com.yyrh.constant.RoleInfo;
import com.yyrh.core.SDKDrive;
import com.yyrh.core.entity.ResultInfo;
import com.yyrh.core.entity.SdkBackLoginInfo;
import com.yyrh.core.entity.bean.InitBean;
import com.yyrh.core.impl.floatball.FloatCenterServiceManager;
import com.yyrh.core.internal.IRequestCallback;
import com.yyrh.core.network.Host;
import com.yyrh.core.network.SdkRequest;
import com.yyrh.networking.NetRequestApi;
import com.yyrh.sdk.SDKEntry;
import com.yyrh.sdk.SdkCallback;
import com.yyrh.sdk.YyrhSdkManager;
import com.yyrh.sdk.callback.ExitCallback;
import com.yyrh.sdk.callback.InitCallback;
import com.yyrh.sdk.callback.LoginCallback;
import com.yyrh.sdk.callback.LogoutCallback;
import com.yyrh.sdk.callback.PayCallback;
import com.yyrh.sdk.callback.PayOrderCallback;
import com.yyrh.sdk.callback.RealNameMsgCallback;
import com.yyrh.utils.FileUtils;
import com.yyrh.utils.MMKVUtils;
import com.yyrh.utils.YYLog;
import com.yythird.sdk.ChannelSDK;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.concurrent.atomic.AtomicInteger;

import cn.yyxx.support.device.DeviceInfoUtils;

public class SdkManager {

    private static SdkManager manager = null;

    private ISdkOperation operation;

    private InitCallback initCallback = null;
    private LoginCallback loginCallback = null;
    private LogoutCallback logoutCallback = null;
    private PayCallback payCallback = null;
    private ExitCallback exitCallback = null;

    private long clickLoginTime = 0L;

    public InitBean initBean = null;
    public String channelTag = "";
    public boolean isLandscape = false;
    private static boolean hasReadIds = false;
    private static String deviceIds = "";
    private String roleCTime = "";


    private final AtomicInteger timeCount = new AtomicInteger(0);

    public final SdkCallback sdkCallback = new SdkCallback() {
        @Override
        public void onShowPolicyAgree() {

        }

        @Override
        public void onShowPolicyDisagree() {

        }

        @Override
        public void onShowPolicyHide() {

        }

        @Override
        public void onShowPolicyError() {

        }

        @Override
        public void onLoginSuccess(String token) {
            if (loginCallback == null) {
                return;
            }
            loginCallback.onLoginSuccess(token);
        }

        @Override
        public void onLoginFailed(String msg) {
            if (loginCallback == null) {
                return;
            }
            loginCallback.onLoginFailed(msg);
        }

        @Override
        public void onLoginError(String msg) {
            if (loginCallback == null) {
                return;
            }
            loginCallback.onLoginError(msg);
        }

        @Override
        public void realNameMsgCallback(boolean isRealName, String birthday) {

        }

        @Override
        public void onSetChannelTagCallback(String msg) {

        }

        @Override
        public void onInitCallback(boolean success, String msg) {
            if (initCallback == null) {
                return;
            }
            if (success) {
                initCallback.onInitSuccess(msg);
            } else {
                initCallback.onInitFailed(msg);
            }
        }

        @Override
        public void onLoginChannelCallback(String msg) {

        }

        @Override
        public void onLogOutCallback(String msg) {
            if (logoutCallback == null) {
                return;
            }
            logoutCallback.onLogoutSuccess();
        }

        @Override
        public void onPayFinishCallback(boolean success, String msg) {
            if (payCallback == null) {
                return;
            }
            if (success) {
                payCallback.onPaySuccess(msg);
            } else {
                payCallback.onPayFailed(msg);
            }
        }

        @Override
        public void onExiGameCallback(boolean success, String msg) {
            if (exitCallback == null) {
                return;
            }
            exitCallback.onExit(success);
        }

        @Override
        public void onPayExtParamCallback(HashMap<String, String> payInfo, String url) {

        }

        @Override
        public void onGetChannelRealNameCallback(boolean isRealName, String report_type, String birthday) {

        }

        @Override
        public void onLoginChannelFail(String msg) {

        }

        @Override
        public void onLoginChannelSuccess(String msg) {

        }

        @Override
        public void onUploadUserRealNameInfo(String report_type, String msg) {

        }

        @Override
        public void onGetOaidCallback(boolean isSuccess, String oaid) {
            // 获取ids回调
            deviceIds = oaid;
            if (isSuccess) {
                if (Build.VERSION.SDK_INT > Build.VERSION_CODES.P) {
                    initCallback.onGetOaid(true, oaid);
                } else {
                    initCallback.onGetOaid(false, "");
                }
            } else {
                initCallback.onGetOaid(false, "");
            }
            SDKDrive.getInstance().setParam("ifa", oaid);
            hasReadIds = true;
            YYLog.d("device ids initialize finish...");
        }

        @Override
        public String onGetChannelUid() {
            return SdkBackLoginInfo.getInstance().userId;
        }

        @Override
        public void onShowGameExit() {

        }
    };

    private SdkManager() {
    }

    public static SdkManager defaultManager() {
        if (manager == null) {
            synchronized (SdkManager.class) {
                if (manager == null) {
                    manager = new SdkManager();
                }
            }
        }
        return manager;
    }

    public void attachBaseContext(Application application, Context context) {
        YYLog.initZap(application);
        SDKDrive.getInstance().initDrive(application);
        if (Host.BASEURL.equals("https://sdkapi.ykklayo.com")) {
            Host.MODEL = 1;
        } else {
            Host.MODEL = 0;
        }
    }

    public void initApplication(Application application) {
        MMKVUtils.getInstance().init(application);
        this.channelTag = FileUtils.readAssetsFileByKey(application, "YyrhParam.cnf", "CHANNELTAG");
    }

    public void initSdk(final Activity activity, final InitCallback callback, boolean isDebug) {
        this.initCallback = callback;
        int orientation = activity.getRequestedOrientation();
        this.isLandscape = orientation != ActivityInfo.SCREEN_ORIENTATION_PORTRAIT && orientation != ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT &&
                orientation != ActivityInfo.SCREEN_ORIENTATION_USER_PORTRAIT && orientation != ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT;
        ChannelSDK.getInstance().SDKInit(activity, sdkCallback);
        initDeviceInfo(activity);

        if (!hasReadIds) {
            YYLog.e("还未完成设备信息加载，将延迟初始化");
            // TODO showDialog
            new Thread(new Runnable() {
                @Override
                public void run() {
                    while (!hasReadIds) {
                        try {
                            YYLog.e("还未完成设备信息加载，将延迟1s初始化");
                            Thread.sleep(1000);
                            timeCount.getAndIncrement();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                    activity.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if (TextUtils.isEmpty(deviceIds)) {
                                YYLog.e("加载设备信息失败，共延迟" + timeCount + "s初始化，将进行初始化操作...");
                            } else {
                                YYLog.i("加载设备信息成功，共延迟" + timeCount + "s初始化，将进行初始化操作...");
                            }
                            // TODO hideDialog
                            startSdkInit(activity);
                        }
                    });
                }
            }).start();
        } else {
            YYLog.i("加载设备信息成功，开始初始化...");
            startSdkInit(activity);
        }
    }

    private void initDeviceInfo(Activity activity) {
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.P) {
            SDKDrive.getInstance().setParam("ifa_type", "2");
            ChannelSDK.getInstance().SDKGetOaid();
        } else {
            String ids = "";
            if (ActivityCompat.checkSelfPermission(activity, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
                // 没有授权用android id
                ids = DeviceInfoUtils.getAndroidDeviceId(activity);
                SDKDrive.getInstance().setParam("ifa_type", "3");
            } else {
                // 如果授权了
                ids = DeviceInfoUtils.getImei(activity);
                SDKDrive.getInstance().setParam("ifa_type", "1");
            }
            sdkCallback.onGetOaidCallback(true, ids);
        }
    }

    private void startSdkInit(final Activity activity) {
        SdkRequest.initSdk(activity, new IRequestCallback() {
            @Override
            public void onResponse(ResultInfo resultInfo) {
                if (resultInfo.code == 1) {
                    // 初始化成功
                    initBean = InitBean.toBean(resultInfo.data);
                    initSdkOperation(activity);
                    sdkCallback.onInitCallback(true, "sdk初始化成功");
                } else {
                    if (TextUtils.isEmpty(resultInfo.msg)) {
                        sdkCallback.onInitCallback(false, "sdk初始化失败");
                    } else {
                        sdkCallback.onInitCallback(false, resultInfo.msg);
                    }
                }
            }
        });
    }

    private void initSdkOperation(Activity activity) {
        if (initBean.sdkLogin == 1 && !channelTag.equals("YYRHSDK")) {
            this.operation = new ChannelSdkOperation();
        } else {
            this.operation = new YyrhSdkOperation();
            FloatCenterServiceManager.getInstance().init(activity);
        }
    }

    public void login(Activity activity, LoginCallback callback) {
        this.loginCallback = callback;
        if (operation == null) {
            YYLog.i("登录失败，SDK未初始化或初始化失败");
            callback.onLoginFailed("登录失败，SDK未初始化或初始化失败");
            return;
        }
        if (System.currentTimeMillis() - clickLoginTime < CLICK_INTERVAL) {
            YYLog.i("调用登录接口太频繁，拦截此次操作");
            return;
        }
        clickLoginTime = System.currentTimeMillis();
        operation.login(activity);
    }

    public void uploadRoleInfo(String type, Activity activity, RoleInfo roleInfo) {
        if (operation == null) {
            YYLog.i("上报角色信息失败，SDK未初始化或初始化失败");
            return;
        }
        this.roleCTime = roleInfo.getRoleCreateTime();
        operation.uploadRoleInfo(type, activity, roleInfo);
    }

    public void reportAdEvent(String event, JSONObject json) {
        if (operation == null) {
            YYLog.i("上报广告事件失败，SDK未初始化或初始化失败");
            return;
        }
        operation.reportAdEvent(event, json);
    }

    public void pay(Activity activity, HashMap<String, Object> map) {
        if (operation == null) {
            YYLog.i("支付失败，SDK未初始化或初始化失败");
            return;
        }
        map.put("role_ctime", roleCTime);
        if (ChannelSDK.getInstance().SDKGetPstatus()) {
            // 强制使用自己支付
            forcePay(activity, map);
        } else {
            operation.pay(activity, map);
        }
    }

    private void forcePay(final Activity activity, HashMap<String, Object> map) {

        NetRequestApi.payOrderInit(PAYMENTWAY, map, activity, new PayOrderCallback() {
            @Override
            public void onPaySuccess(HashMap<String, Object> map) {
                SDKEntry.getSdkInstance().adSdkCallback.onCreateOrder(map);
                YyrhSdkManager.defaultManager().yyrhPay(activity, map);
            }

            @Override
            public void onPayFailed(String msg) {
                SDKEntry.getSdkInstance().sdkCallback.onPayFinishCallback(false, msg);
            }
        });
    }

    public void exit(Activity activity, ExitCallback callback) {
        this.exitCallback = callback;
        if (operation == null) {
            return;
        }
        operation.exit(activity);
    }

    public void logOut() {
        if (operation == null) {
            YYLog.i("用户注销失败，SDK未初始化或初始化失败");
            return;
        }
        operation.logOut();
    }

    public void setSDKLogoutListener(Activity activity, LogoutCallback callback) {
        this.logoutCallback = callback;
        if (operation == null) {
            YYLog.i("设置用户注销回调失败，SDK未初始化或初始化失败");
            return;
        }
        operation.setSDKLogoutListener(activity, sdkCallback);
    }

    public void getRealNameInfo(Activity activity, RealNameMsgCallback realNameMsgCallback) {
        if (operation == null) {
            YYLog.i("获取实名信息失败，SDK未初始化或初始化失败");
            return;
        }
        operation.getRealNameInfo(activity, realNameMsgCallback);
    }

    public String getCurrentUserId() {
        if (operation == null) {
            YYLog.i("获取用户ID失败，SDK未初始化或初始化失败");
            return "";
        }
        return SdkBackLoginInfo.getInstance().userId;
    }

    /**
     * 生命周期
     */
    public void sdkOnStart(Activity activity) {
        if (operation == null) {
            return;
        }
        operation.sdkOnStart(activity);
    }

    public void sdkOnCreate(Activity activity, Bundle savedInstanceState) {
        if (operation == null) {
            return;
        }
        operation.sdkOnCreate(activity, savedInstanceState);
    }

    public void sdkOnPause(Activity activity) {
        if (operation == null) {
            return;
        }
        operation.sdkOnPause(activity);
    }

    public void sdkOnResume(Activity activity) {
        if (operation == null) {
            return;
        }
        operation.sdkOnResume(activity);
    }

    public void sdkOnRestart(Activity activity) {
        if (operation == null) {
            return;
        }
        operation.sdkOnRestart(activity);
    }

    public void sdkOnStop(Activity activity) {
        if (operation == null) {
            return;
        }
        operation.sdkOnStop(activity);
    }


    public void sdkOnDestroy(Activity activity) {
        Zap.recycle();
        if (operation == null) {
            return;
        }
        operation.sdkOnDestroy(activity);
    }


    public void sdkOnNewIntent(Activity activity, Intent intent) {
        if (operation == null) {
            return;
        }
        operation.sdkOnNewIntent(activity, intent);
    }

    public void onActivityResult(Activity ac, int requestCode, int resultCode, Intent data) {
        if (operation == null) {
            return;
        }
        operation.onActivityResult(ac, requestCode, resultCode, data);
    }

    public void onConfigurationChanged(Configuration newConfigs) {
        if (operation == null) {
            return;
        }
        operation.onConfigurationChanged(newConfigs);
    }

    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        if (operation == null) {
            return;
        }
        operation.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    public void onWindowFocusChanged(Activity activity, boolean hasFocus) {
        if (operation == null) {
            return;
        }
        operation.onWindowFocusChanged(activity, hasFocus);
    }
}
