package com.zxbw.xxsq.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;

import com.umeng.analytics.MobclickAgent;
import com.umeng.socialize.UMShareAPI;
import com.zxbw.modulemain.fragment.HomeFragment;
import com.zxbw.modulemain.fragment.UserCenterFragment;
import com.zxbw.modulemain.view.NavigationBottomView;
import com.zxbw.xxsq.R;
import com.zxhl.cms.AppContext;
import com.zxhl.cms.common.Constant;
import com.zxhl.cms.common.base.BaseActivity;
import com.zxhl.cms.net.ApiClient;
import com.zxhl.cms.net.RxSchedulers;
import com.zxhl.cms.net.SettingPreference;
import com.zxhl.cms.net.callback.BaseObserver;
import com.zxhl.cms.net.model.uc.UserInfo;
import com.zxhl.cms.utils.AdDataSupport;
import com.zxhl.cms.utils.EventUtils;
import com.zxhl.cms.utils.JumpUtils;
import com.zxhl.cms.utils.RxBus;
import com.zxhl.cms.utils.UserDataUtils;
import com.zxhl.cms.utils.Utils;
import com.zxhl.cms.widget.LoadingDialog;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;

/**
 * Copyright @ 2018 Bitgoose All rights reserved.
 *
 * @class name: MainActivity
 * @class describe:
 * @author: fuxin
 * @date: 2019/3/15 下午2:19
 */
public class MainActivity extends BaseActivity implements NavigationBottomView.NavifationCallback/*, IDialogCloseCallback, MemberContract.View*/ {

    private List<Fragment> fragments = new ArrayList<>();
    private NavigationBottomView navigationView;
    private LoadingDialog mLoading;
    private Observable<String> mRestartLoginObservable;
    private Observable<Integer> mSwitchMainObservable;

    @Override
    public int layoutID() {
        return R.layout.activity_main;
    }

    @Override
    public void before() {
        super.before();

        setStatusBarBackground(AppContext.get().getResources().getColor(R.color.transparent));

    }

    @SuppressLint("CheckResult")
    @Override
    public void init() {
        mLoading = LoadingDialog.getLoadingDialog(
                this,
                getString(com.zxhl.cms.R.string.wait_ing),
                false,
                false
        );
        navigationView = findViewById(R.id.id_activity_main_fragment_navigation);
        initListener();
        AdDataSupport.INSTANCE.init(this);
        initFragment();
        mRestartLoginObservable = RxBus.get().register(Constant.REFRESH_LOGIN_STATS, String.class);
        mRestartLoginObservable.observeOn(AndroidSchedulers.mainThread()).subscribe(new Consumer<String>() {
            @Override
            public void accept(String s) throws Exception {
                JumpUtils.loginJump();
            }
        }, new Consumer<Throwable>() {
            @Override
            public void accept(Throwable throwable) throws Exception {

            }
        });

        mSwitchMainObservable = RxBus.get().register(Constant.SWITCH_PAGE, Integer.class);
        mSwitchMainObservable.observeOn(AndroidSchedulers.mainThread()).subscribe(new Consumer<Integer>() {
            @Override
            public void accept(Integer s) throws Exception {
                switchFragment(s);
            }
        }, new Consumer<Throwable>() {
            @Override
            public void accept(Throwable throwable) throws Exception {

            }
        });

        boolean firstLoginApp = SettingPreference.getFirstLoginApp();
        if (firstLoginApp) {
            SettingPreference.setFirstLoginApp();
            UserInfo userInfoData = SettingPreference.getUserInfoData();
            if (userInfoData != null) {
                Constant.Switch.isOpenVip = userInfoData.member;
                if (!userInfoData.member) {
                    JumpUtils.OpenMember();
                }
            }
        }
    }

    private void initListener() {
        navigationView.setNavifationCallback(this);
    }

    private void initFragment() {
        fragments.add(new HomeFragment());
        fragments.add(new UserCenterFragment());
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        for (Fragment fragment : fragments) {
            transaction.add(R.id.id_activity_main_fragment_layout, fragment);
        }
        hideFragment(transaction);
        transaction.show(fragments.get(0)).commit();
        EventUtils.INSTANCE.onEvent("tab_imp", "home");
    }

    private void switchFragment(int index) {
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        hideFragment(transaction);
        transaction.show(fragments.get(index)).commitAllowingStateLoss();
        getSupportFragmentManager().executePendingTransactions();
    }

    private void switchFragment(Fragment fragment) {
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        hideFragment(transaction);
        transaction.show(fragment).commit();
    }

    private void hideFragment(FragmentTransaction transaction) {
        for (Fragment fragment : fragments) {
            transaction.hide(fragment);
        }
    }

    @Override
    public void onClick(View v) {

    }

    @Override
    public void onNavigationClick(int vId) {
        if (vId == com.zxbw.modulemain.R.id.id_view_navigation_bottom_box) {
            switchFragment(0);
            EventUtils.INSTANCE.onEvent("tab_imp", "home");
        } else if (vId == com.zxbw.modulemain.R.id.id_view_navigation_bottom_user) {
            switchFragment(1);
            EventUtils.INSTANCE.onEvent("tab_imp", "user");
        }
    }

    private boolean mPrepareExit = false;

    @Override
    public void onBackPressed() {
        exitBy2Click();
    }

    private void exitBy2Click() {
        if (!mPrepareExit) {
            mPrepareExit = true;// 准备退出
            Utils.showToast(this, getResources().getString(R.string.nav_back_again_finish));
            navigationView.postDelayed(new Runnable() {
                @Override
                public void run() {
                    mPrepareExit = false;// 取消退出
                }
            }, 1500);
        } else {
            EventUtils.INSTANCE.onEvent("double_exit", "双击退出");
            closeApp();
        }
    }

    private void exitActivity() {
        Utils.onExit(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
        UserInfo userInfoData = SettingPreference.getUserInfoData();
        if (userInfoData != null) {
            Constant.Switch.isOpenVip = userInfoData.member;
        }
    }


    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

    private void deviceLogin() {
        ApiClient.INSTANCE.getUserInfoAPi().deviceLogin().compose(RxSchedulers.observableIO2Main()).subscribe(new BaseObserver<UserInfo>() {
            @Override
            public void onSuccess(UserInfo result) {
                if (result != null) {
                    SettingPreference.saveToken(result.token);
                    UserDataUtils.INSTANCE.updateUserInfo(null);
                }
            }

            @Override
            public void onFailure(Throwable e, String code, String errorMsg) {

            }
        });
    }

    private void closeApp() {
        ApiClient.INSTANCE.getHomeApi().closeApp().compose(RxSchedulers.observableIO2Main()).subscribe(new BaseObserver<Object>() {
            @Override
            public void onSuccess(Object result) {
                Log.e("MXL", "退出app上报");
                exitActivity();
            }

            @Override
            public void onFailure(Throwable e, String code, String errorMsg) {
                exitActivity();
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        RxBus.get().unregister(Constant.REFRESH_LOGIN_STATS, mRestartLoginObservable);
        RxBus.get().unregister(Constant.SWITCH_PAGE, mSwitchMainObservable);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        try {
            UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
        } catch (Exception e) {
        }
    }


    @SuppressLint("MissingSuperCall")
    @Override
    protected void onSaveInstanceState(@NonNull Bundle outState) {
//        super.onSaveInstanceState(outState);
    }

}
