package com.sheep.gamegroup.module.login;

import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.util.Log;
import android.view.Menu;

import com.sheep.gamegroup.absBase.BaseUMActivity;
import com.sheep.gamegroup.greendao.DDProviderHelper;
import com.sheep.gamegroup.model.entity.LoginEntity;
import com.sheep.gamegroup.model.util.EntityUtils;
import com.sheep.gamegroup.module.login.controller.LoginController;
import com.sheep.gamegroup.module.login.fragments.EditUserInfoFgt;
import com.sheep.gamegroup.module.login.fragments.FindAccountFgt;
import com.sheep.gamegroup.module.login.fragments.SignInFgt;
import com.sheep.gamegroup.module.login.fragments.SignUpFgt;
import com.sheep.gamegroup.module.login.fragments.ValidCaptchaFgt;
import com.sheep.gamegroup.greendao.download.Account;
import com.sheep.gamegroup.module.login.fragments.WelcomeFgt;
import com.sheep.gamegroup.util.CertificationUtil;
import com.sheep.gamegroup.util.Jump2View;
import com.sheep.gamegroup.util.TestUtil;
import com.sheep.jiuyan.samllsheep.R;
import com.sheep.jiuyan.samllsheep.SheepApp;
import com.sheep.jiuyan.samllsheep.utils.SpUtils;
import com.sheep.jiuyan.samllsheep.utils.TitleBarUtils;
import com.umeng.socialize.UMAuthListener;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.bean.SHARE_MEDIA;

import java.util.List;
import java.util.Map;

public class LoginAct extends BaseUMActivity implements LoginController {

    private boolean isLogined = false;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_login;
    }

    public boolean onCreateOptionsMenu(Menu menu) {
        try {
            getSupportActionBar().getClass()
                    .getDeclaredMethod("setShowHideAnimationEnabled", boolean.class)
                    .invoke(getSupportActionBar(), false);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public void initView() {
        TitleBarUtils.getInstance().setTitleBack(this);
//        if (DDProviderHelper.getInstance().getAccountList().size() == 0) {
            WelcomeFgt welcomeFragment = WelcomeFgt.newInstance(this);
            showFragment("welcome", welcomeFragment);
//        } else {
//            SignInFgt signInFragment = SignInFgt.newInstance(this);
//            showFragment("登录", signInFragment);
//        }
    }

    @Override
    public void onBackPressed() {
        if (getSupportFragmentManager().getBackStackEntryCount() == 1) {
            finish();
            return;
        }
        if (isLogined) {
            return;
        }
        super.onBackPressed();
        if (getSupportFragmentManager().getBackStackEntryCount() == 1) {
            TitleBarUtils.getInstance().setShowOrHide(this, false);
        }
        if(getSupportActionBar()!=null){
            if(getSupportFragmentManager().getBackStackEntryCount() == 1) {
                getSupportActionBar().hide();
            } else {
                getSupportActionBar().show();
            }
        }
        TitleBarUtils.getInstance().setTitle(this, getLastFragment().getTag());
    }

    @Override
    public void whenToLogin(int platform) {
        SignInFgt signInFragment = SignInFgt.newInstance(this, platform);
        showFragment("登录", signInFragment);
    }

    @Override
    public void whenLoginSuccess(int platform, LoginEntity loginResult) {
        if (TextUtils.isEmpty(SheepApp.getInstance().getGameCode())) {
//            Snackbar.make(getWindow().getDecorView(), "登录成功", Snackbar.LENGTH_SHORT).show();
            if (TextUtils.isEmpty(loginResult.getUser().getBirthday())
                    || loginResult.getUser().getBirthday().startsWith("000")) {
                getUserInfo(platform, loginResult);
            } else {
                goMain(loginResult);
            }
        } else {
            CertificationUtil.newInstance().addCurUserToSdkLoginUser();
            CertificationUtil.newInstance().authCertificationCode(this, SpUtils.getToken(SheepApp.getInstance()));
        }
        TestUtil.saveUser(loginResult);
        if (platform == LoginController.PLATFORM_ACCOUNT || platform == LoginController.PLATFORM_PHONE) {
            DDProviderHelper.getInstance().saveAccount(Account.generateByUser(loginResult.getUser()));
        }
    }

    private void getUserInfo(int platform, final LoginEntity entity) {
        if (platform == LoginController.PLATFORM_QQ || platform == LoginController.PLATFORM_WX) {
            UMShareAPI.get(SheepApp.getInstance()).getPlatformInfo(this,
                    platform == LoginController.PLATFORM_QQ ? SHARE_MEDIA.QQ : SHARE_MEDIA.WEIXIN,
                    new UMAuthListener() {
                        @Override
                        public void onStart(SHARE_MEDIA share_media) {

                        }

                        @Override
                        public void onComplete(SHARE_MEDIA share_media, int i, Map<String, String> map) {
                            entity.getUser().setNickname(map.get("screen_name"));
                            entity.getUser().setAvatar(map.get("profile_image_url"));
                            entity.getUser().setGender("男".equals(map.get("gender")) ? 1 : 2);
                            goEditUserInfo(entity);
                        }

                        @Override
                        public void onError(SHARE_MEDIA share_media, int i, Throwable throwable) {
                            goMain(entity);
                        }

                        @Override
                        public void onCancel(SHARE_MEDIA share_media, int i) {

                        }
                    });
        } else {
            goEditUserInfo(entity);
        }
    }

    private void goEditUserInfo(LoginEntity entity) {
        EditUserInfoFgt editUserInfoFgt = EditUserInfoFgt.newInstance(entity, this);
        showFragment("填写基本资料", editUserInfoFgt);
    }

    @Override
    public void whenEditedInfo(LoginEntity entity) {
        if (DDProviderHelper.getInstance().getAccount(entity.getUser().getId()) != null) {
            DDProviderHelper.getInstance().saveAccount(Account.generateByUser(entity.getUser()));
        }
        goMain(entity);
    }

    private void goMain(LoginEntity entity){
        showProgress();
        Jump2View.getInstance().goHomePageView(this, EntityUtils.getUserCode(entity));
        Jump2View.getInstance().checkCommendApp(this, EntityUtils.getUserCode(entity), false);
    }

    @Override
    public void whenToRegister() {
        SignUpFgt signUpFragment = SignUpFgt.newInstance(this);
        showFragment("注册", signUpFragment);
    }

    @Override
    public void whenGoFindAccount() {
        FindAccountFgt findAccountFgt = FindAccountFgt.newInstance(this);
        showFragment("登录遇到问题", findAccountFgt);
    }

    @Override
    public void whenGoValidCaptcha(String phoneNum) {
        ValidCaptchaFgt validCaptchaFgt = ValidCaptchaFgt.newInstance(phoneNum, this);
        showFragment("输入验证码", validCaptchaFgt);
    }

    private void showFragment(String tag, Fragment fragment) {
        if(getSupportActionBar()!=null){
            if(getSupportFragmentManager().getBackStackEntryCount() > 0) {
                getSupportActionBar().show();
            } else {
                getSupportActionBar().hide();
            }
        }
        TitleBarUtils.getInstance().setShowOrHide(this, getSupportFragmentManager().getBackStackEntryCount() > 0).setTitle(this, tag);
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        transaction.replace(R.id.fragment_container, fragment, tag);
        transaction.show(fragment);
        transaction.addToBackStack(null);
        transaction.commitAllowingStateLoss();
    }

    private Fragment getLastFragment() {
        List<Fragment> fragments = getSupportFragmentManager().getFragments();
        if (fragments != null && fragments.size() > 0) {
            for (int i = 1; i <= fragments.size(); i++) {
                Fragment fragment = fragments.get(fragments.size() - i);
                if (fragment != null) {
                    return fragment;
                }
            }
        }
        return null;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent intent) {
        super.onActivityResult(requestCode, resultCode, intent);
        getLastFragment().onActivityResult(requestCode, resultCode, intent);
    }

    private void setFirstStartup() {
        SharedPreferences sp = getSharedPreferences("small_sheep", MODE_PRIVATE);
        sp.edit().putBoolean("first_startup", false);
        sp.edit().commit();
    }

    private boolean isFirstStartup() {
        SharedPreferences sp = getSharedPreferences("small_sheep", MODE_PRIVATE);
        Log.e("FirstStartUp", sp.contains("first_startup") + "   " + sp.getBoolean("first_startup", true));
        return sp.getBoolean("first_startup", true);
    }

}
