package com.zxhl.xymhhf.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.CashCheckFragment;
import com.zxbw.modulemain.fragment.HomeFragment;
import com.zxbw.modulemain.fragment.ShoppingMallFragment;
import com.zxbw.modulemain.fragment.UserCenterFragment;
import com.zxbw.modulemain.view.NavigationBottomView;
import com.zxhl.cms.utils.ClipboardManagerUtil;
import com.zxhl.xymhhf.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.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 XymhMainActivity 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();
        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 {

            }
        });
        initFragment();
        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) {
            UserInfo userInfoData = SettingPreference.getUserInfoData();
            if (userInfoData != null&&userInfoData.member!=null) {
                Constant.Switch.isOpenVip = userInfoData.member;
                if (!userInfoData.member) {
                    SettingPreference.setFirstLoginApp();
                    JumpUtils.OpenMember();
                }
            }
        }
    }

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

    private void initFragment() {
        fragments.add(new HomeFragment());
        fragments.add(new ShoppingMallFragment());
        fragments.add(new CashCheckFragment());
        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_shop) {
            switchFragment(1);
            EventUtils.INSTANCE.onEvent("tab_imp", "shop");
        } else if (vId == com.zxbw.modulemain.R.id.id_view_navigation_bottom_cash) {
            switchFragment(2);
            EventUtils.INSTANCE.onEvent("tab_imp", "cash_check");
        } if (vId == com.zxbw.modulemain.R.id.id_view_navigation_bottom_user) {
            switchFragment(3);
            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", "双击退出");
            exitActivity();
           // closeApp();
        }
    }

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

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


    @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) {
                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);
    }

}
