package com.zztrapp.zztrapp.ui;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

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

import com.allenliu.versionchecklib.core.http.HttpHeaders;
import com.allenliu.versionchecklib.v2.AllenVersionChecker;
import com.allenliu.versionchecklib.v2.builder.DownloadBuilder;
import com.allenliu.versionchecklib.v2.builder.UIData;
import com.allenliu.versionchecklib.v2.callback.RequestVersionListener;
import com.google.gson.Gson;
import com.gyf.immersionbar.BarHide;
import com.tencent.smtt.export.external.TbsCoreSettings;
import com.tencent.smtt.sdk.QbSdk;
import com.zztrapp.zztrapp.R;
import com.zztrapp.zztrapp.base.BaseActivity;
import com.zztrapp.zztrapp.bean.UpGradePackageBean;
import com.zztrapp.zztrapp.databinding.ActivityMainBinding;
import com.zztrapp.zztrapp.http.HttpApi;
import com.zztrapp.zztrapp.http.RxApiManager;
import com.zztrapp.zztrapp.utilcode.klogs.KLog;
import com.zztrapp.zztrapp.utilcode.mUtil.FragmentFactory;
import com.zztrapp.zztrapp.utilcode.util.AdaptScreenUtils;
import com.zztrapp.zztrapp.utilcode.util.AppUtils;
import com.zztrapp.zztrapp.utilcode.util.SPUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

public class MainActivity extends BaseActivity {
    private ActivityMainBinding binding;
    public static Activity mainActivity;
    private static final int QUANTITY = 4;
    private List<Fragment> fragments;
    private int currentIndex = 0;

    @Override
    public View getLayoutId() {
        return binding.getRoot();
    }

    @Override
    protected void initBinding() {
        binding = ActivityMainBinding.inflate(getLayoutInflater());
    }

    @Override
    protected void init() {
        mImmersionBar.reset();
        mImmersionBar.fullScreen(true)
                .hideBar(BarHide.FLAG_HIDE_NAVIGATION_BAR)
                .flymeOSStatusBarFontColor(R.color.white).init();  //修改flyme OS状态栏字体颜色;
//        mImmersionBar.statusBarColor(R.color.white).statusBarDarkFont(true).fitsSystemWindows(false)
//                .flymeOSStatusBarFontColor(R.color.black).init();  //修改flyme OS状态栏字体颜色;

        mainActivity = this;
        FragmentManager manager = getSupportFragmentManager();
        manager.popBackStack();
        radioGroupManage();


        Drawable drawable_index = getResources().getDrawable(R.drawable.selector_navigation_index);
        //当这个图片被绘制时，给他绑定一个矩形 ltrb规定这个矩形
        drawable_index.setBounds(0, 0, AdaptScreenUtils.pt2Px(20), AdaptScreenUtils.pt2Px(20));
        //设置图片在文字的哪个方向
        binding.rbIndexNavigationIndex.setCompoundDrawables(null, drawable_index, null, null);
        Drawable drawable_map = getResources().getDrawable(R.drawable.selector_navigation_map);
        drawable_map.setBounds(0, 0, AdaptScreenUtils.pt2Px(20), AdaptScreenUtils.pt2Px(20));
        binding.rbMapNavigationIndex.setCompoundDrawables(null, drawable_map, null, null);
        Drawable drawable_currency = getResources().getDrawable(R.drawable.selector_navigation_currency);
        drawable_currency.setBounds(0, 0, AdaptScreenUtils.pt2Px(20), AdaptScreenUtils.pt2Px(20));
        binding.rbCurrencyNavigationIndex.setCompoundDrawables(null, drawable_currency, null, null);
        Drawable drawable_mine = getResources().getDrawable(R.drawable.selector_navigation_mine);
        drawable_mine.setBounds(0, 0, AdaptScreenUtils.pt2Px(20), AdaptScreenUtils.pt2Px(20));
        binding.rbMineNavigationIndex.setCompoundDrawables(null, drawable_mine, null, null);

        loadVersionCheck();

        //设置开启优化方案
        // 在调用TBS初始化、创建WebView之前进行如下配置
        HashMap map = new HashMap();
        map.put(TbsCoreSettings.TBS_SETTINGS_USE_SPEEDY_CLASSLOADER, true);
        map.put(TbsCoreSettings.TBS_SETTINGS_USE_DEXLOADER_SERVICE, true);
        QbSdk.initTbsSettings(map);
        QbSdk.setDownloadWithoutWifi(true);
        QbSdk.initX5Environment(this, new QbSdk.PreInitCallback() {
            @Override
            public void onCoreInitFinished() {
                // 内核初始化完成，可能为系统内核，也可能为系统内核
                KLog.e(" 内核初始化完成，可能为系统内核，也可能为系统内核");
            }

            /**
             * 预初始化结束
             * 由于X5内核体积较大，需要依赖网络动态下发，所以当内核不存在的时候，默认会回调false，此时将会使用系统内核代替
             * @param isX5 是否使用X5内核
             */
            @Override
            public void onViewInitFinished(boolean isX5) {
                KLog.e("isX5"+isX5);
            }
        });
    }

    @Override
    protected void initOnClick() {

    }


    //导航切换
    private void radioGroupManage() {
        fragments = new ArrayList<>();
        final RadioButton[] buttons = new RadioButton[QUANTITY];
        assert binding.rgNavigationMain != null;
        for (int i = 0; i < binding.rgNavigationMain.getChildCount(); i++) {
            //获取第i个位置上的子控件
            buttons[i] = (RadioButton) binding.rgNavigationMain.getChildAt(i);
            //往集合中添加Fragment对象
            fragments.add(FragmentFactory.createFragment(i));
        }
        //默认加载第一个Fragment对象
        getSupportFragmentManager().beginTransaction().add(binding.flMain.getId(), fragments.get(0)).commit();

        //处理单机事件
        binding.rgNavigationMain.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                for (int i = 0; i < binding.rgNavigationMain.getChildCount(); i++) {
                    if (buttons[i].getId() == checkedId) {
//                        switch (i) {
//                            case 0:
//                                mImmersionBar.reset();
//                                mImmersionBar.statusBarColor(R.color.white).statusBarDarkFont(true)
//                                        .fitsSystemWindows(false).flymeOSStatusBarFontColor(R.color.black).init();  //修改flyme OS状态栏字体颜色;
//                                break;
//                            case 2:
//                            case 1:
//                                mImmersionBar.reset();
//                                mImmersionBar.statusBarColor(R.color.color2C86FF).statusBarDarkFont(false)
//                                        .fitsSystemWindows(true).flymeOSStatusBarFontColor(R.color.white).init();  //修改flyme OS状态栏字体颜色;
//                                break;
//                            case 3:
//                                mImmersionBar.reset();
//                                mImmersionBar.statusBarColor(R.color.color2C86FF).statusBarDarkFont(false)
//                                        .fitsSystemWindows(true).flymeOSStatusBarFontColor(R.color.white).init();  //修改flyme OS状态栏字体颜色;
//                                break;
////                            case 2:
////                                mImmersionBar.reset();
////                                mImmersionBar.fullScreen(true)
////                                        .flymeOSStatusBarFontColor(R.color.white).init();  //修改flyme OS状态栏字体颜色;
////                                break;
//                        }
                        switchFragment(i);
                    }
                }
            }
        });
    }


    /**
     * 切换Fragment的方法
     *
     * @param targetIndex
     */
    private void switchFragment(int targetIndex) {
        //目标的Fragment
        Fragment targetFragment = fragments.get(targetIndex);
        //当前的Fragment
        Fragment currentFragment = fragments.get(currentIndex);
        FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
        if (targetFragment.isAdded()) {
            //目标Fragment已经被添加了...则隐藏当前正在展示的Fragment,显示目标Fragment
            fragmentTransaction.hide(currentFragment).show(targetFragment);
        } else {
            //没有被添加...则隐藏当前的Fragment,添加目标Fragment
            fragmentTransaction.hide(currentFragment).add(binding.flMain.getId(), targetFragment);
        }
        fragmentTransaction.commit();
        //改变当前索引值
        currentIndex = targetIndex;
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        mainActivity = null;
        binding = null;
        //合适的地方关闭
        AllenVersionChecker.getInstance().cancelAllMission();
        RxApiManager.get().cancelAll();
    }

    //检测版本升级
    public void loadVersionCheck() {
        HttpHeaders httpHeaders = new HttpHeaders();
        String authorization = SPUtils.getInstance().getString("authorization", "");
        httpHeaders.put("X-Access-Token", authorization);
        DownloadBuilder downloadBuilder = AllenVersionChecker
                .getInstance()
                .requestVersion()
                .setHttpHeaders(httpHeaders)
                .setRequestUrl(HttpApi.BASE_URL + HttpApi.GET_APP_VERSION)
                .request(new RequestVersionListener() {
                    @Nullable
                    @Override
                    public UIData onRequestVersionSuccess(DownloadBuilder downloadBuilder, String result) {
                        KLog.e("更新app");
                        if (!TextUtils.isEmpty(result)) {
                            KLog.e("更新app:" + result);
                            Gson gson = new Gson();
                            UpGradePackageBean upGradePackageBean = gson.fromJson(result, UpGradePackageBean.class);
                            if (upGradePackageBean.getCode() == 200 && null != upGradePackageBean.getResult() && upGradePackageBean.getResult().getVersionCode() > AppUtils.getAppVersionCode()) {
                                if (upGradePackageBean.getResult().getUpType() == 2) {//升级类型（1普通升级，2强制升级）
                                    //动态在此设置是否强制更新等
                                    downloadBuilder.setForceUpdateListener(() -> {
                                        forceUpdate();
                                    });
                                }
                                //设置当前服务器最新的版本号，供库判断是否使用缓存
//                                downloadBuilder.setNewestVersionCode(upGradePackageBean.getData().getVersionCode());
                                UIData uiData = UIData.create();
                                uiData.setTitle(upGradePackageBean.getResult().getVersionName());
                                uiData.setDownloadUrl(upGradePackageBean.getResult().getDownloadUrl());
//                                uiData.setDownloadUrl("https://shiatang.oss-cn-shanghai.aliyuncs.com/upload/2017-12-08/app-release.apk");
                                uiData.setContent(upGradePackageBean.getResult().getContent());
                                return uiData;
                            }
                        }
                        return null;
                    }

                    @Override
                    public void onRequestVersionFailure(String message) {

                    }
                });
        //下载忽略本地缓存
        downloadBuilder.setForceRedownload(true);
        downloadBuilder.executeMission(this);
    }

    /**
     * 强制更新操作
     * 通常关闭整个activity所有界面，这里方便测试直接关闭当前activity
     */
    private void forceUpdate() {
        finish();
    }

    @SuppressLint("MissingSuperCall")
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        //将这一行注释掉，阻止activity保存fragment的状态,解决Fragment穿透重叠现象
        //super.onSaveInstanceState(outState);
    }

    private static Boolean isExit = false;

    @Override
    public void onBackPressed() {
        Timer tExit = null;

        if (isExit == false) {
            isExit = true; // 准备退出
            Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
            tExit = new Timer();
            tExit.schedule(new TimerTask() {
                @Override
                public void run() {
                    isExit = false; // 取消退出
                }
            }, 2000); // 如果2秒钟内没有按下返回键，则启动定时器取消掉刚才执行的任务

        } else {
            mainActivity=null;
            finish();
            System.exit(0);
        }
    }

}