package com.yyrh.core.impl.login;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;

import com.yyrh.core.entity.Session;
import com.yyrh.core.impl.login.fragment.AccountLauncherFragment;
import com.yyrh.core.impl.login.fragment.PhoneRegisterFragment;
import com.yyrh.core.impl.login.fragment.QuickRegisterFragment;
import com.yyrh.core.internal.IImplCallback;
import com.yyrh.ui.dialog.AgreementDialog;
import com.yyrh.ui.dialog.AutoLauncherDialog;
import com.yyrh.utils.SessionUtils;
import com.yyrh.utils.TimeDownUtils;
import com.yyrh.utils.YYLog;

import java.util.LinkedList;

import cn.yyxx.support.AndroidBug5497Workaround;
import cn.yyxx.support.ResUtils;

/**
 * @author #Suyghur.
 * Created on 2021/10/19
 */
public class LoginActivity extends FragmentActivity {

    private static boolean isLandscape = false;
    public static IImplCallback implCallback = null;
    private static boolean autoLogin = true;
    private AccountLauncherFragment accountLauncherFragment;
    private QuickRegisterFragment quickRegisterFragment;
    private PhoneRegisterFragment phoneRegisterFragment;
    private final LinkedList<String> fragmentStack = new LinkedList<>();
    private String currentFragmentTag;
    public LoginViewModel viewModel;
    private Dialog agreementDialog = null;
    private AutoLauncherDialog autoLoginDialog = null;
    private Session session = null;
    private boolean isCancelLogin = false;

    private final Handler handler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(@NonNull Message msg) {
            if (msg.what == 101) {
                YYLog.d("cancel: " + isCancelLogin);
                if (isCancelLogin) {
                    hideAutoLoginDialog();
                    return;
                }
                autoLoginDialog.getButton().setEnabled(false);
                autoLoginDialog.getButton().setBackgroundResource(ResUtils.getResId(LoginActivity.this, "hnyy_btn_light_purple_bg", "drawable"));
                viewModel.accountLauncher(LoginActivity.this, session.userName, session.pwd);
            }
        }
    };


    public static void start(Activity activity, boolean auto, boolean isLand, IImplCallback callback) {
        isLandscape = isLand;
        autoLogin = auto;
        implCallback = callback;
        activity.startActivity(new Intent(activity, LoginActivity.class).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
    }


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.viewModel = new LoginViewModel(new LoginViewModel.ISignInCallback() {
            @Override
            public void onSuccess(String result) {
                hideAutoLoginDialog();
                implCallback.onResult(1, result);
            }

            @Override
            public void onFailed(String result) {
                implCallback.onResult(0, result);
            }
        });
        initView();
    }

    private void initView() {
        if (isLandscape) {
            getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
        }
        setContentView(ResUtils.getResId(this, "hnyy_login_activity", "layout"));

        if (!isLandscape) {
            AndroidBug5497Workaround.assistActivity(this);
        }
        showAutoLoginDialog();
    }

    private void initFragment() {
        switchFragment(LoginFragmentTag.ACCOUNT_LAUNCHER);
    }

    public void switchFragment(String tag) {
        switch (tag) {
            case LoginFragmentTag.ACCOUNT_LAUNCHER:
                if (null == accountLauncherFragment) {
                    accountLauncherFragment = new AccountLauncherFragment();
                }
                switchFragment(accountLauncherFragment, tag);
                break;
            case LoginFragmentTag.QUICK_REGISTER:
                if (null == quickRegisterFragment) {
                    quickRegisterFragment = new QuickRegisterFragment();
                }
                switchFragment(quickRegisterFragment, tag);
                break;
            case LoginFragmentTag.PHONE_REGISTER:
                if (null == phoneRegisterFragment) {
                    phoneRegisterFragment = new PhoneRegisterFragment();
                }
                switchFragment(phoneRegisterFragment, tag);
                break;
        }
    }

    public void switchFragment(Fragment fragment, String tag) {
        if (fragmentStack.contains(tag)) {
            //栈里最后一个与tag相同才执行删除
            if (fragmentStack.size() > 1 && !fragmentStack.getLast().equals(tag)) {
                fragmentStack.removeLast();
            }
        } else {
            fragmentStack.add(tag);
        }

        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        transaction.setCustomAnimations(ResUtils.getResId(this, "hnyy_fragment_push_anim", "anim"),
                ResUtils.getResId(this, "hnyy_fragment_popup_anim", "anim"));
        Fragment tagFragment = getSupportFragmentManager().findFragmentByTag(currentFragmentTag);
        if (tagFragment != null && !tag.equals(currentFragmentTag)) {
            tagFragment.onPause();
            transaction.hide(tagFragment);
        }
        tagFragment = getSupportFragmentManager().findFragmentByTag(tag);
        if (tagFragment == null) {
            transaction.add(ResUtils.getResId(this, "hnyy_login_container", "id"), fragment, tag);
        } else {
            tagFragment.onResume();
            transaction.show(tagFragment);
        }
        currentFragmentTag = tag;
        transaction.commitAllowingStateLoss();
    }

    public void showAgreementDialog(String url) {
        if (agreementDialog != null) {
            if (agreementDialog.isShowing()) {
                agreementDialog.dismiss();
            }
            agreementDialog = null;
        }
        agreementDialog = new AgreementDialog(this, url, false);
        agreementDialog.show();
    }

    private void showAutoLoginDialog() {
        if (autoLoginDialog != null) {
            if (autoLoginDialog.isShowing()) {
                autoLoginDialog.dismiss();
            }
            autoLoginDialog = null;
        }
        this.session = SessionUtils.getInstance().getLocalLastSession();

        if (session == null || !autoLogin) {
            initFragment();
            return;
        }

        autoLoginDialog = new AutoLauncherDialog(this);
        autoLoginDialog.getButton().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 取消自动登录
                isCancelLogin = true;
                hideAutoLoginDialog();
                initFragment();
            }
        });
        autoLoginDialog.show();
        // 延迟2s发起登录
        handler.sendEmptyMessageDelayed(101, 2000);
    }

    private void hideAutoLoginDialog() {
        if (autoLoginDialog != null) {
            autoLoginDialog.dismiss();
//            TimeDownUtils.cancel();
            autoLoginDialog = null;
        }
    }

    private void changeTimeNum() {
        if (!TimeDownUtils.isRunning()) {
            TimeDownUtils.start(2, new TimeDownUtils.TimeCallback() {
                @Override
                public void onTime(int time) {
                    Message msg = Message.obtain();
                    msg.what = 101;
                    msg.obj = time;
                    handler.sendMessage(msg);
                }
            });
        } else {
            TimeDownUtils.resetCallback(new TimeDownUtils.TimeCallback() {
                @Override
                public void onTime(int time) {
                    Message msg = Message.obtain();
                    msg.what = 101;
                    msg.obj = time;
                    handler.sendMessage(msg);
                }
            });
        }
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
            if (isShouldHideInput(v, ev)) {

                InputMethodManager imm = (InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE);
                if (imm != null) {
                    imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                }
            }
            return super.dispatchTouchEvent(ev);
        }
        // 必不可少，否则所有的组件都不会有TouchEvent了
        if (getWindow().superDispatchTouchEvent(ev)) {
            return true;
        }
        return onTouchEvent(ev);
    }

    public boolean isShouldHideInput(View v, MotionEvent event) {
        if ((v instanceof EditText)) {
            int[] leftTop = {0, 0};
            //获取输入框当前的location位置
            v.getLocationInWindow(leftTop);
            int left = leftTop[0];
            int top = leftTop[1];
            int bottom = top + v.getHeight();
            int right = left + v.getWidth();
            // 点击的是输入框区域，保留点击EditText的事件
            return !(event.getX() > left) || !(event.getX() < right) || !(event.getY() > top) || !(event.getY() < bottom);
        }
        return false;
    }

    public void hideBar() {
        // The UI options currently enabled are represented by a bitfield.
        // getSystemUiVisibility() gives us that bitfield.
        int uiOptions = getWindow().getDecorView().getSystemUiVisibility();
        int newUiOptions = uiOptions;
        boolean isImmersiveModeEnabled =
                ((uiOptions | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY) == uiOptions);
        if (!isImmersiveModeEnabled) {
//            Log.i(TAG, "Turning immersive mode mode on. ");
            if (Build.VERSION.SDK_INT >= 14) {
                newUiOptions |= View.SYSTEM_UI_FLAG_HIDE_NAVIGATION;
            }
            if (Build.VERSION.SDK_INT >= 16) {
                newUiOptions |= View.SYSTEM_UI_FLAG_FULLSCREEN;
            }
            if (Build.VERSION.SDK_INT >= 18) {
                newUiOptions |= View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY;
            }
            getWindow().getDecorView().setSystemUiVisibility(newUiOptions);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        hideBar();
    }

    @Override
    public void onBackPressed() {
        if (!fragmentStack.isEmpty() && fragmentStack.size() > 1) {
            switch (fragmentStack.getLast()) {
                case LoginFragmentTag.QUICK_REGISTER:
                    quickRegisterFragment.onBack();
                    break;
                case LoginFragmentTag.PHONE_REGISTER:
                    phoneRegisterFragment.onBack();
                    break;
            }

            fragmentStack.removeLast();
            String tag = fragmentStack.getLast();
            switchFragment(tag);
        } else {
            super.onBackPressed();
        }
    }
}
