package cn.yyxx.commsdk.impl.merge.platform.xinrui.impl;

import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.text.TextUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.concurrent.TimeUnit;

import cn.yyxx.commsdk.base.entity.ResultInfo;
import cn.yyxx.commsdk.base.entity.SdkOrderInfo;
import cn.yyxx.commsdk.base.entity.SdkRoleInfo;
import cn.yyxx.commsdk.base.entity.bean.InitBean;
import cn.yyxx.commsdk.base.internal.ICallback;
import cn.yyxx.commsdk.base.internal.IMsaDeviceCallback;
import cn.yyxx.commsdk.base.internal.IRequestCallback;
import cn.yyxx.commsdk.base.internal.feature.IApplication;
import cn.yyxx.commsdk.base.internal.feature.IFeature;
import cn.yyxx.commsdk.base.internal.feature.ILifeCycle;
import cn.yyxx.commsdk.base.internal.feature.IOrder;
import cn.yyxx.commsdk.base.utils.Logger;
import cn.yyxx.commsdk.core.entity.SdkLoginInfo;
import cn.yyxx.commsdk.core.network.SdkRequest;
import cn.yyxx.commsdk.core.utils.ResourceUtil;
import cn.yyxx.commsdk.impl.merge.LoginViewModel;
import cn.yyxx.commsdk.impl.merge.platform.xinrui.XinRuiLoginActivity;
import cn.yyxx.commsdk.impl.merge.platform.xinrui.dialog.CustomExitGameDialog;
import cn.yyxx.commsdk.impl.merge.platform.xinrui.dialog.EmailDialog;
import cn.yyxx.commsdk.impl.merge.platform.xinrui.dialog.HnPayDialog;
import cn.yyxx.commsdk.impl.merge.platform.xinrui.dialog.WvPageListDialog;
import cn.yyxx.commsdk.impl.merge.platform.xinrui.floating.FloatViewManager;
import cn.yyxx.commsdk.impl.merge.platform.msa.MsaDeviceHandler;
import cn.yyxx.support.scheduler.ScheduledWorker;

public class SdkPlatformImpl implements IFeature, ILifeCycle, IApplication, IOrder {
    public static InitBean initConfig = null ;

    private static SdkPlatformImpl manager;


    private  ICallback logoutCallback;




    public static LoginViewModel loginViewModel;

    public static ScheduledWorker sScheduledWorker = null;


    private static Activity activity;

    public SdkPlatformImpl(Context context){

    }


    @Override
    public void attachBaseContext(Application application, Context context) {

    }

    @Override
    public void initApplication(Application application) {

    }

    @Override
    public void initialize(Activity activity, ICallback callback) {
        this.activity = activity;
    }

    @Override
    public void initializeSuccess(Activity activity, int loginStatus) {
        this.activity = activity;
    }

    @Override
    public void setLogoutListener(Activity activity, ICallback callback) {
        logoutCallback = callback;
    }

    @Override
    public void login(final Activity activity, InitBean initBean, final ICallback callback) {
        initConfig  = initBean;
        loginViewModel = new LoginViewModel(callback);
        XinRuiLoginActivity.start(activity,callback);
    }

    @Override
    public void logout() {
        SdkLoginInfo.getInstance().reset();
        hideFloat();
        initConfig.isSwitchAccount = true;

        if (sScheduledWorker != null) {
            sScheduledWorker.cancel();
            SdkRequest.getInstance().uploadUserOnlineAction(activity, "0", SdkLoginInfo.getInstance().rn_si, new IRequestCallback() {
                @Override
                public void onResponse(ResultInfo resultInfo) {
                    if (resultInfo.code == ResultInfo.CODE_SUCCESS){
                        Logger.i("上报角色在线状态成功");
                    }else{
                        Logger.i("上报角色在线状态失败");
                    }
                }
            });
        }
    }



    @Override
    public boolean hasExitView(Activity activity) {
        return true;
    }

    @Override
    public void openExitView(final Activity activity, final ICallback callback) {
        if (hasExitView(activity)){

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

                    callback.onResult(ResultInfo.CODE_SUCCESS,activity.getString(ResourceUtil.getStringId(activity,"xinrui_exit_game")));
                    dialog.dismiss();
                }
            });
            builder.setnegativeButton(new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {

                    callback.onResult(ResultInfo.CODE_FAIL,activity.getString(ResourceUtil.getStringId(activity,"xinrui_continue_game")));

                    dialog.dismiss();
                }
            });

            builder.Create().show();
        }else{
            callback.onResult(ResultInfo.CODE_SUCCESS,activity.getString(ResourceUtil.getStringId(activity,"xinrui_open_cp_exit_view")));
        }
    }

    @Override
    public void uploadRoleInfo(Activity activity, String type, SdkRoleInfo roleInfo) {

    }

    @Override
    public void reportGameEvent(String event, JSONObject message) {

    }

    @Override
    public void initMsaDeviceIds(Context context, IMsaDeviceCallback iMsaDeviceCallback) {
        MsaDeviceHandler.initMsaDeviceIds(context,iMsaDeviceCallback);
    }

    @Override
    public String getChannelOcfg(Activity activity) {
        return null;
    }


    public static SdkPlatformImpl getInstance(Context context){
        if (manager == null) {
            synchronized (SdkPlatformImpl.class) {
                if (manager == null) {
                    manager = new SdkPlatformImpl(context);
                }
            }
        }
        return manager;
    }

    @Override
    public void onStart(Activity activity) {

    }

    @Override
    public void onResume(Activity activity) {

    }

    @Override
    public void onRestart(Activity activity) {

    }

    @Override
    public void onPause(Activity activity) {

    }

    @Override
    public void onStop(Activity activity) {

    }

    @Override
    public void onActivityResult(Activity activity, int requestCode, int resultCode, Intent data) {

    }

    @Override
    public void onNewIntent(Activity activity, Intent intent) {

    }

    @Override
    public void onConfigurationChanged(Activity activity, Configuration newconfig) {

    }

    @Override
    public void onWindowFocusChanged(Activity activity, boolean hasFocus) {

    }

    @Override
    public void onDestroy(Activity activity) {
        releaseFloat();
        if (sScheduledWorker != null) {
            sScheduledWorker.cancel();
        }
    }

    @Override
    public void onCreate(Activity activity, Bundle savedInstanceState) {

    }


    public void showFloat(){
        if (!initConfig.isOpenFloatView){
            return ;
        }
        activity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                FloatViewManager.getInstance(activity).showFloat();
            }
        });

    }
    public void hideFloat(){

        activity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                FloatViewManager.getInstance(activity).hideFloat();
            }
        });
    }
    public void releaseFloat(){

        activity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                FloatViewManager.getInstance(activity).releaseFloat();
            }
        });

    }

    public void loginSuccess(){
        operateRealNameDialog(activity);
    }

    @Override
    public void startPay(Activity activity, SdkOrderInfo sdkOrderInfo, final ICallback callback) {

        if (!TextUtils.isEmpty(sdkOrderInfo.getPay_web_url())){

            new HnPayDialog(activity, ResourceUtil.getStyleId(activity, "xinrui_base_dialog"), sdkOrderInfo, new ICallback() {
                @Override
                public void onResult(int code, String result) {
                    if (code  == ResultInfo.CODE_SUCCESS){
                        try {
                            JSONObject json = new JSONObject(result);
                            int order_status = json.optInt("order_status",0);
                            if (order_status == ResultInfo.CODE_SUCCESS){
                                callback.onResult(ResultInfo.CODE_SUCCESS,"支付成功");
                            }else{

                                callback.onResult(ResultInfo.CODE_FAIL,"支付取消");

                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }else{

                        callback.onResult(ResultInfo.CODE_ERROR,"订单查询失败");

                    }
                }
            }).show();

        }

    }

    void operateRealNameDialog(Activity activity){
        if (initConfig.isOpenRealName && !SdkLoginInfo.getInstance().isVefityRealName){

                new WvPageListDialog(activity, ResourceUtil.getStyleId(activity, "xinrui_half_black_dialog"), SdkLoginInfo.getInstance().authentication,
                        new WvPageListDialog.OnClosePageListener() {
                            @Override
                            public void onClose() {

                            }

                            @Override
                            public void onDissmiss() {

                                startLoginOperation();
                            }


                            @Override
                            public void onRealNameSuccess() {


                            }
                        }, initConfig.isForceRealName).show();


        }else{

            startLoginOperation();
        }
    }

    void startLoginOperation(){
        showFloat();
        loginViewModel.mImplCallback.onResult(ResultInfo.CODE_SUCCESS,SdkLoginInfo.getInstance().token);
        startRoleOnlineWorker();
        openEmailDialog();
    }
    void openEmailDialog(){
        if (TextUtils.isEmpty(SdkLoginInfo.getInstance().solo_email)) {
            return;
        }
        activity.runOnUiThread(new Runnable() {
            @Override
            public void run() {

                new EmailDialog(activity, ResourceUtil.getStyleId(activity, "xinrui_half_black_dialog"), SdkLoginInfo.getInstance().solo_email).show();

            }
        });
    }

    private void startRoleOnlineWorker(){
        if (TextUtils.isEmpty(SdkLoginInfo.getInstance().rn_si)){
            Logger.i(" rn_si is null");
            return;
        }
        if (sScheduledWorker == null) {
            sScheduledWorker = new ScheduledWorker(1);
        }
        sScheduledWorker.cancel();
        int time = initConfig.rn_bh;
        Logger.i(" ------ 开始防沉迷计时任务  : " + time);
        sScheduledWorker.invokeAtFixedRate(new Runnable() {
            @Override
            public void run() {

                Logger.i(" ------ 用户角色心跳 ------");

                SdkRequest.getInstance().uploadUserOnlineAction(activity, "2", SdkLoginInfo.getInstance().rn_si, new IRequestCallback() {
                    @Override
                    public void onResponse(ResultInfo resultInfo) {
                        if (resultInfo.code == ResultInfo.CODE_SUCCESS){
                            Logger.i("上报角色在线状态成功");
                        }else{
                            Logger.i("上报角色在线状态失败");
                        }
                    }
                });

            }
        }, time, time, TimeUnit.SECONDS);
    }


    @Override
    public String getChannelOrderExt() {
        return "";
    }
}
