package com.zhangxin.magicbox.activity;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.Signature;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

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

import com.zhangxin.magicbox.R;
import com.umeng.analytics.MobclickAgent;
import com.zxhl.cms.AppContext;
import com.zxhl.cms.ad.upload.model.NewsEntity;
import com.zxhl.cms.common.Constant;
import com.zxhl.cms.common.base.BaseActivity;
import com.zxhl.cms.net.model.box.PopupsEntity;
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.AdCallback;
import com.zxhl.cms.utils.AdDataSupport;
import com.zxhl.cms.utils.EventUtils;
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 com.zxhl.main.page.fragment.HomeFragment;
import com.zxhl.main.page.fragment.ShopFragment;
import com.zxhl.main.page.fragment.WareHouseFragment;
import com.zxhl.main.page.view.DiscountDialog;
import com.zxhl.main.page.view.NavigationBottomView;
import com.zxhl.uc.page.fragment.UserCenterFragment;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.HashMap;
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 MemberPresenter memberPresenter;
    private LoadingDialog mLoading;
    private Dialog mDialog;
    private Context context;
    private Observable<String> mRestartLoginObservable;
    private Observable<Integer> mSwitchMainObservable;
    private String goodsId;
    private TextView mallBottomBtn;

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

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

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

    }

    @Override
    public void init() {
        context = this;
        mLoading = LoadingDialog.getLoadingDialog(
                this,
                getString(com.zxhl.cms.R.string.wait_ing),
                false,
                false
        );
        navigationView = findViewById(R.id.id_activity_main_fragment_navigation);
        mallBottomBtn = findViewById(R.id.id_view_navigation_bottom_shop);
//        memberPresenter = new MemberPresenter(this);
        initListener();
        AdDataSupport.INSTANCE.init(this);
        initFragment();
//        facelogin();
        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 {
                deviceLogin();
            }
        }, 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 {

            }
        });
    }

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

    private void initFragment() {
        fragments.add(new HomeFragment());
        fragments.add(new WareHouseFragment());
        fragments.add(new UserCenterFragment());

        if (Constant.Switch.isOpenShop) {
            fragments.add(new ShopFragment());
            mallBottomBtn.setVisibility(View.VISIBLE);
        }else {
            mallBottomBtn.setVisibility(View.GONE);
        }
        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 == R.id.id_view_navigation_bottom_user) {
            switchFragment(2);
            EventUtils.INSTANCE.onEvent("tab_imp", "user");
        } else if (vId == R.id.id_view_navigation_bottom_box) {
            switchFragment(0);
            EventUtils.INSTANCE.onEvent("tab_imp", "home");
        } else if (vId == R.id.id_view_navigation_bottom_shop) {
            switchFragment(3);
        } else if (vId == R.id.id_view_navigation_bottom_warehouse) {
            switchFragment(1);
        }
    }

    private boolean mPrepareExit = false;

    @Override
    public void onBackPressed() {
//        super.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 {
            showPopus();

        }
    }

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

    private void showPopus() {
        ApiClient.INSTANCE.getHomeApi().getPopups().compose(RxSchedulers.observableIO2Main()).subscribe(new BaseObserver<PopupsEntity>() {
            @Override
            public void onSuccess(PopupsEntity result) {
                if (result != null) {
                    if (result.getPopUps().equals("0")) {
                        exitActivity();
                    } else {
                        DiscountDialog.INSTANCE.showDiscountDialog(mActivity);
                    }
                }
            }

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

            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onResume(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) {

            }
        });
    }

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

    private void requestRewardVidedo(AdCallback<String> adCallback) {
        String slotId = "video";
        ApiClient.INSTANCE.getAdApi().getAds(slotId).compose(RxSchedulers.observableIO2Main())
                .subscribe(new BaseObserver<List<NewsEntity>>() {
                    @Override
                    public void onSuccess(List<NewsEntity> result) {
                        if (result != null && result.size() > 0) {
                            AdDataSupport.INSTANCE.requestByteRewardVideoAd(result.get(0), MainActivity.this, adCallback);

                        } else {
                            adCallback.onResult(-1, "失败");
                        }

                    }

                    @Override
                    public void onFailure(Throwable e, String code, String errorMsg) {
                        adCallback.onResult(-1, "失败");
                    }
                });
    }
//
//    @Override
//    public void onCloseViewTopay(@NotNull String goodsId, @NotNull Dialog dialog) {
//        this.goodsId=goodsId;
//        memberPresenter.requestWechatPayOrder(goodsId);
//        mDialog = dialog;
//    }
//
//    @Override
//    public void updatePriceList(@NotNull List<MemberEntity.ProductDetail> data) {
//
//    }
//
//    @Override
//    public void verifyOrderFail() {
//        showResultLoading(false);
//    }
//
//    @Override
//    public void requestOrderSuc() {
//        mLoading.setLoading("正在支付");
//    }
//
//    @Override
//    public void verifyOrderSuc(@NotNull String orsder) {
//        showResultLoading(true);
//    }

    private void showResultLoading(Boolean isPaySuc) {
        if (isPaySuc) {
            if (TextUtils.equals("11", goodsId)) {
                EventUtils.INSTANCE.onEvent("rebate_dialog_pay_suc", "折扣购买成功");
            } else if (TextUtils.equals("21", goodsId)) {
                EventUtils.INSTANCE.onEvent("coupon_dialog_pay_suc", "优惠券购买成功");
            }
            mLoading.setResult(true, "支付成功", 1000);
            if (mDialog != null) {
                mDialog.dismiss();
            }
        } else {
            mLoading.setResult(false, "支付失败", 1000);
            if (TextUtils.equals("11", goodsId)) {
                EventUtils.INSTANCE.onEvent("rebate_dialog_pay_fail", "折扣购买失败");
            } else if (TextUtils.equals("21", goodsId)) {
                EventUtils.INSTANCE.onEvent("coupon_dialog_pay_fail", "优惠券购买失败");
            }
        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        try {
        } catch (Exception e) {
        }
    }
    //    @Override
//    public void showNextDialog(boolean isneed) {
//        if (isneed) {
//            CouponDialog.INSTANCE.showCouponDialog(this, this);
//        } else {
//
//        }
//    }
//
//    private void openDialog() {
//        if (SettingPreference.getshowDialog()) {
//            DiscountDialog.INSTANCE.showDiscountDialog(this, this);
//        } else {
//            TripsDialog.INSTANCE.showTripDialog(this, true);
//        }
//    }


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


}
