package com.yyrh.sdk;

import static com.yyrh.constant.Constants.LOGOUT;
import static com.yyrh.constant.SDKSettings.isOpenRealName;
import static com.yyrh.constant.SDKSettings.isVefityRealName;
import static com.yyrh.ui.floatmenu.FloatViewManager.DESTORY_FLOAT;
import static com.yyrh.ui.floatmenu.FloatViewManager.SHOW_FLOAT;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Handler;
import android.support.v4.app.ActivityCompat;
import android.text.TextUtils;
import android.util.Log;

import com.dolin.zap.Zap;
import com.yyrh.constant.SDKSettings;
import com.yyrh.core.SDKDrive;
import com.yyrh.core.entity.ResultInfo;
import com.yyrh.core.entity.bean.InitBean;
import com.yyrh.core.impl.login.LoginActivity;
import com.yyrh.core.internal.IImplCallback;
import com.yyrh.core.internal.IRequestCallback;
import com.yyrh.core.network.SdkRequest;
import com.yyrh.factory.SdkManager;
import com.yyrh.imei.ImeiUtil;
import com.yyrh.networking.NetRequestApi;
import com.yyrh.sdk.callback.InitCallback;
import com.yyrh.sdk.callback.LoginCallback;
import com.yyrh.sdk.callback.RealNameMsgCallback;
import com.yyrh.sdk.callback.ShowPolicyCallback;
import com.yyrh.sdk.callback.UserPolicyCallback;
import com.yyrh.ui.activity.UseLoginActivity;
import com.yyrh.ui.dialog.AutoLoginDialog;
import com.yyrh.ui.dialog.CustomExitGameDialog;
import com.yyrh.ui.dialog.EmailDialog;
import com.yyrh.ui.dialog.PrivacyPolicyDialog;
import com.yyrh.ui.dialog.SingleButtonDialog;
import com.yyrh.ui.dialog.WvPageListDialog;
import com.yyrh.ui.dialog.WvPayYyrhDialog;
import com.yyrh.ui.floatmenu.FloatViewManager;
import com.yyrh.ui.fragment.FragmentUtils;
import com.yyrh.ui.userlist.DatabaseHelper;
import com.yyrh.utils.InspectSimulator;
import com.yyrh.utils.ResourceUtil;
import com.yyrh.utils.Utils;
import com.yyrh.utils.YYLog;
import com.yythird.sdk.ChannelSDK;

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

import cn.yyxx.support.device.DeviceInfoUtils;

public class YyrhSdkManager {


    private static volatile YyrhSdkManager manager = null;

    private Context context;

    private InitCallback initCallback = null;
    private LoginCallback loginCallback = null;

    private static InitBean initBean = null;
    private static boolean hasReadIds = false;
    private static String deviceIds = "";

    private volatile AtomicInteger timeCount = new AtomicInteger(0);

    private SdkCallback mSdkCallback = new SdkCallback() {
        @Override
        public void onShowPolicyAgree() {

        }

        @Override
        public void onShowPolicyDisagree() {

        }

        @Override
        public void onShowPolicyHide() {

        }

        @Override
        public void onShowPolicyError() {

        }

        @Override
        public void onLoginSuccess(String token) {

        }

        @Override
        public void onLoginFailed(String msg) {

        }

        @Override
        public void onLoginError(String msg) {

        }

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

        }

        @Override
        public void onSetChannelTagCallback(String msg) {

        }

        @Override
        public void onInitCallback(boolean success, String msg) {

        }

        @Override
        public void onLoginChannelCallback(String msg) {

        }

        @Override
        public void onLogOutCallback(String msg) {

        }

        @Override
        public void onPayFinishCallback(boolean success, String msg) {

        }

        @Override
        public void onExiGameCallback(boolean success, String msg) {

        }

        @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 null;
        }

        @Override
        public void onShowGameExit() {

        }
    };

    public void initSdk(final Activity activity, final InitCallback callback, boolean isDebug) {
        // 初始化设备参数
        this.initCallback = callback;
        ChannelSDK.getInstance().SDKInit(activity, mSdkCallback);
        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, callback);
                        }
                    });
                }
            }).start();
        } else {
            YYLog.i("加载设备信息成功，开始初始化...");
            startSdkInit(activity, callback);
        }
    }

    public 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");
            }
            mSdkCallback.onGetOaidCallback(true, ids);
        }
    }

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

    public void login(Activity activity, LoginCallback callback) {
        this.loginCallback = callback;
        LoginActivity.start(activity, true, false, new IImplCallback() {
            @Override
            public void onResult(int code, String result) {

            }
        });
    }


    private YyrhSdkManager() {
    }

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

    public void queryOrder(final String order, final HashMap<String, Object> payMap) {

        String status = Utils.getParamCnfValuebyKey(context, "YyrhAdParam.cnf", "QUERY_ORDER");
        if (status.equals("YES")) {
            new Handler().postDelayed(new Runnable() {

                @Override
                public void run() {
                    NetRequestApi.queryOrder(order, payMap);
                }
            }, 5000);
        }


    }


    public void yyrhShowPolicy(final Activity activity, final UserPolicyCallback userPolicyCallback) {

        YYLog.i("yyrhShowPolicy ");


        String isShowPolicy = Utils.getSharedPreferences("yyrh", "yyrhShowPolicy", context);

        if (isShowPolicy.equals("")) {

            NetRequestApi.initAgreement(activity, new ShowPolicyCallback() {

                @Override
                public void onShow(String agreement_url) {
                    YYLog.i("need to display the policy");
                    new PrivacyPolicyDialog(activity, ResourceUtil.getStyleId(activity, "hnyy_base_dialog"), agreement_url,
                            new PrivacyPolicyDialog.OnClosePageListener() {
                                @Override
                                public void onUserAgreePolicy() {

                                    YYLog.i("User agree policy");

                                    Utils.setSharedPreferences("yyrh", "yyrhShowPolicy", "1", context);
                                    userPolicyCallback.onAgree();
                                }

                                @Override
                                public void onUserDisagreePolicy() {
                                    YYLog.i("User disagree policy");
                                    userPolicyCallback.onDisagree();
                                }
                            }).show();


                }

                @Override
                public void onHide() {
                    YYLog.i(" don't need to display the policy");
                    userPolicyCallback.onHide();
                }

                @Override
                public void onError() {
                    YYLog.i(" request policy error");
                    userPolicyCallback.onError();
                }
            });


        } else {
            YYLog.i("The user has agreed to the policy");
            userPolicyCallback.onAgree();
        }


    }

    public void yyrhInitDevice(final Activity activity, boolean isDebug) {
        SDKSettings.isDebug = isDebug;
        String isdebug = Utils.GetApplicationMetaData(context, "yyrh_debug");
        if (isdebug.equals("true")) {
            SDKSettings.isDebug = true;
        }
        SDKSettings.initSetting(activity);

        if (Build.VERSION.SDK_INT > 28) {
            ChannelSDK.getInstance().SDKGetOaid();
        } else {
            SDKSettings.imei = ImeiUtil.getImei(context);
            SDKEntry.getSdkInstance().sdkCallback.onGetOaidCallback(true, SDKSettings.imei);
        }
    }


    public void yyrhInit(final Activity activity) {
//        SdkRequest.initSdk(context, new IRequestCallback() {
//            @Override
//            public void onResponse(ResultInfo resultInfo) {
//                if (resultInfo.code==1){
//                    // 初始化成功
//                }else {
//                    // 失败
//                    ChannelSDK.getInstance().SDKInitFail(resultInfo.msg);
//                    SDKEntry.getSdkInstance().sdkCallback
//                }
//            }
//        });

//        NetRequestApi.init(activity, new InitCallback() {
//            @Override
//            public void onInitSuccess(String msg) {
//                SdkManager.defaultManager().onInitSuccess(activity);
//                ChannelSDK.getInstance().SDKInitSuccess(msg);
//                SDKEntry.getSdkInstance().sdkCallback.onInitCallback(true, msg);
//
//            }
//
//            @Override
//            public void onInitFailed(String msg) {
//                ChannelSDK.getInstance().SDKInitFail(msg);
//                SDKEntry.getSdkInstance().sdkCallback.onInitCallback(false, msg);
//                SingleButtonDialog.Builder builder = new SingleButtonDialog.Builder(activity);
//                builder.setPositiveButton(new DialogInterface.OnClickListener() {
//                    @Override
//                    public void onClick(DialogInterface dialog, int which) {
//                        System.exit(0);
//                    }
//                });
//                builder.Create(msg).show();
//            }
//
//            @Override
//            public void onInitError(String _strError) {
//
//                ChannelSDK.getInstance().SDKInitFail(_strError);
//                SDKEntry.getSdkInstance().sdkCallback.onInitCallback(false, _strError);
//
//                SingleButtonDialog.Builder builder = new SingleButtonDialog.Builder(activity);
//                builder.setPositiveButton(new DialogInterface.OnClickListener() {
//                    @Override
//                    public void onClick(DialogInterface dialog, int which) {
//
//                        System.exit(0);
//
//                    }
//                });
//                builder.Create(_strError).show();
//            }
//
//            @Override
//            public void onGetOaid(boolean isSuccess, String oaid) {
//
//            }
//
//            @Override
//            public void onShowGameExit() {
//
//            }
//
//        });

        SDKSettings.isSimulator = InspectSimulator.isSimulator(activity);
        Log.i("idSimu:", SDKSettings.isSimulator);
    }

    public void yyrhLogin(Activity activity) {
//        operateFloatViewInUIThread(activity, DESTORY_FLOAT);
//        SharedPreferences sp = activity.getSharedPreferences("yyrh", Activity.MODE_PRIVATE);
//        if (!Utils.judgeStrNull(sp.getString("username", "")) &&
//                !SDKSettings.LOGINTAG.equals(LOGOUT)) {
//            autoLogin(activity);
//
//        } else if (SDKSettings.LOGINTAG.equals(LOGOUT)) {
//
//            showLoginView(activity, FragmentUtils.SDK_USER_SWITCH_ACCOUNT);
//
//        } else {
//
//            if (InitConfig.fristShowPage.equals("phone")) {
//
//                showLoginView(activity, FragmentUtils.SDK_PHONE_REGISTER_TAG);
//
//            } else {
//
//                showLoginView(activity, FragmentUtils.SDK_REGISTER_TAG);
//
//            }
//
//        }

    }

    private void showLoginView(Activity activity, int type) {


        Intent intent = new Intent(activity, UseLoginActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);

        intent.putExtra("fragmentTag", type);


        intent.putExtra("orientation", activity.getRequestedOrientation());

        activity.startActivity(intent);

    }


    private void autoLogin(final Activity activity) {
        AutoLoginDialog.Builder builder = new AutoLoginDialog.Builder(activity);
        builder.setPositiveButton(new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                //取消回调
                dialog.dismiss();

                showLoginView(activity, FragmentUtils.SDK_USER_SWITCH_ACCOUNT);

            }
        }).setCloseDialogCallback(new AutoLoginDialog.CloseDialogCallback() {

            @Override
            public void onclose() {

            }

            @Override
            public void onLoginFail() {
                showLoginView(activity, FragmentUtils.SDK_USER_SWITCH_ACCOUNT);
            }
        });

        builder.Create().show();
    }

    public void yyrhLogout() {

        SDKSettings.loginData = null;
        final Activity activity = (Activity) context;

        operateFloatViewInUIThread(activity, DESTORY_FLOAT);

        SDKSettings.LOGINTAG = LOGOUT;
        SDKEntry.getSdkInstance().sdkCallback.onLogOutCallback("Game Logout.");

    }


    public void yyrhPay(final Activity activity, final HashMap<String, Object> map) {

        final String url = (String) map.get("url");
        if (Utils.judgeStrNull(url)) {
            return;
        }

        activity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                new WvPayYyrhDialog(activity, ResourceUtil.getStyleId(activity, "hnyy_base_dialog"), url, map).show();
            }
        });

    }

    public void yyrhExitGame(final Activity activity) {
        CustomExitGameDialog.Builder builder = new CustomExitGameDialog.Builder(activity);
        builder.setPositiveButton(new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

                FloatViewManager.defaultManager(activity).destroyFloat();

                dialog.dismiss();
                SDKEntry.getSdkInstance().adSdkCallback.onExitGame(activity);
                SDKEntry.getSdkInstance().sdkCallback.onExiGameCallback(true, "Exit Game.");
            }
        });
        builder.setnegativeButton(new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });

        builder.Create().show();
    }

    public void uploadRoleInfo(String type, Activity activity, String roleId, String roleName, String roleLevel, String serverId,
                               String serverName, String hasGold, String vipLevel, String role_power, String partyId, String partyName, String createTime, String charge) {
        NetRequestApi.upLoadingRoleInfo(type, activity, roleId, roleName, roleLevel, serverId,
                serverName, hasGold, vipLevel, role_power, partyId, partyName, createTime, charge);

    }


    public void saveUserLoginInfo(final Context context, final String account, String pwd, String login_token, final String token) {


        HashMap<String, String> map = new HashMap();
        map.put("username", account);
        map.put("password", pwd);
        map.put("login_token", login_token);
        Utils.setSharedPreferences("yyrh", map, context);

        String timeStamp = System.currentTimeMillis() + "";

        String delete_sql = "delete from user where name = '" + account + "'";

        String insert_sql = "insert into user(name,pwd,login_token,time) values('" + account
                + "','" + pwd + "','" + login_token + "','" + timeStamp + "')";

        DatabaseHelper.excuteSql(context, delete_sql);
        DatabaseHelper.excuteSql(context, insert_sql);


        operateRealNameDialog(token);

    }

    void operateRealNameDialog(final String token) {
        if (isOpenRealName) {

            if (!isVefityRealName) {

                if (SDKSettings.isForceRealName) {

                    new WvPageListDialog(context, ResourceUtil.getStyleId(context, "hnyy_half_black_dialog"), SDKSettings.loginData.authentication,
                            new WvPageListDialog.OnClosePageListener() {
                                @Override
                                public void onClose() {

                                    if (SDKSettings.loginData.rn_bd.equals("")) {

                                        SDKSettings.loginData = null;

                                    }

                                }

                                @Override
                                public void onDissmiss() {
                                    openEmailDialogInUIThread((Activity) context);
                                    operateFloatViewInUIThread((Activity) context, SHOW_FLOAT);

                                }


                                @Override
                                public void onRealNameSuccess(String birthday) {


                                    SDKEntry.getSdkInstance().sdkCallback.onLoginSuccess(token);


                                }
                            }, SDKSettings.isForceRealName).show();
                } else {

                    new WvPageListDialog(context, ResourceUtil.getStyleId(context, "hnyy_half_black_dialog"), SDKSettings.loginData.authentication,
                            new WvPageListDialog.OnClosePageListener() {
                                @Override
                                public void onClose() {

                                    SDKEntry.getSdkInstance().sdkCallback.onLoginSuccess(token);


                                }

                                @Override
                                public void onDissmiss() {
                                    openEmailDialogInUIThread((Activity) context);
                                    operateFloatViewInUIThread((Activity) context, SHOW_FLOAT);

                                }


                                @Override
                                public void onRealNameSuccess(String birthday) {
                                    YYLog.i("onRealNameSuccess");

                                }
                            }).show();


                }

            } else {

                openEmailDialogInUIThread((Activity) context);
                operateFloatViewInUIThread((Activity) context, SHOW_FLOAT);
                SDKEntry.getSdkInstance().sdkCallback.onLoginSuccess(token);


            }

        } else {
            openEmailDialogInUIThread((Activity) context);
            operateFloatViewInUIThread((Activity) context, SHOW_FLOAT);
            SDKEntry.getSdkInstance().sdkCallback.onLoginSuccess(token);
        }
    }

    public void yyrhGetRealNameInfo(Activity activity, RealNameMsgCallback msgCallback) {

        if (Utils.getTextIsNull(SDKSettings.loginData.rn_bd)) {
            msgCallback.onLoadRealNameMsg(false, "");
        } else {
            msgCallback.onLoadRealNameMsg(true, SDKSettings.loginData.rn_bd);
        }
    }

    private void operateFloatViewInUIThread(final Activity gameAct, final int status) {
        gameAct.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (status == SHOW_FLOAT) {
                    FloatViewManager.defaultManager(gameAct).showFloat();
                } else if (status == DESTORY_FLOAT) {
                    FloatViewManager.defaultManager(gameAct).destroyFloat();
                }


            }
        });
    }

    private void openEmailDialogInUIThread(final Activity gameAct) {
        if (Utils.judgeStrNull(SDKSettings.loginData.solo_email)) {
            return;
        }
        gameAct.runOnUiThread(new Runnable() {
            @Override
            public void run() {

                new EmailDialog(context, ResourceUtil.getStyleId(context, "hnyy_half_black_dialog"), SDKSettings.loginData.solo_email).show();

            }
        });
    }

    public void onStart(Activity activity) {

    }

    public void onRestart(Activity activity) {

    }

    public void onResume(Activity activity) {

    }


    public void onPause(Activity activity) {

    }

    public void onStop(Activity activity) {

    }

    public void onDestroy(Activity activity) {

    }

}
