package com.sheep.gamegroup.view.activity;

import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.kfzs.duanduan.utils.StatusBarUtils;
import com.kfzs.duanduan.view.DialogStorageLow;
import com.sheep.gamegroup.absBase.AbsObserver;
import com.sheep.gamegroup.event.BigEvent;
import com.sheep.gamegroup.greendao.download.DownLoadInfo;
import com.sheep.gamegroup.helper.DownloadHelper;
import com.sheep.gamegroup.model.entity.Container;
import com.sheep.gamegroup.util.ActionUtil;
import com.sheep.gamegroup.util.ChannelContent;
import com.sheep.gamegroup.util.CommonUtil;
import com.sheep.gamegroup.util.DataUtil;
import com.sheep.gamegroup.util.DownloadUtil;
import com.sheep.gamegroup.util.DrawablesHelper;
import com.sheep.gamegroup.util.Jump2View;
import com.sheep.gamegroup.util.ListUtil;
import com.sheep.gamegroup.util.MainTab;
import com.sheep.gamegroup.util.SysAppUtil;
import com.sheep.gamegroup.util.TestUtil;
import com.sheep.gamegroup.util.UMConfigUtils;
import com.sheep.gamegroup.view.adapter.ViewPagerFragmentAdapter;
import com.sheep.gamegroup.view.dialog.DialogGameOrTaskOrGift;
import com.sheep.gamegroup.view.fragment.FgtFind;
import com.sheep.gamegroup.view.fragment.FgtSmallSheep;
import com.sheep.jiuyan.samllsheep.R;
import com.sheep.jiuyan.samllsheep.SheepApp;
import com.sheep.jiuyan.samllsheep.utils.G;
import com.sheep.jiuyan.samllsheep.utils.PackageUtil;
import com.sheep.jiuyan.samllsheep.utils.SpUtils;
import com.youmi.android.offer.BaseActYmPermissionCheck;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import rx.functions.Action1;

import static android.content.Intent.ACTION_PACKAGE_ADDED;
import static android.content.Intent.ACTION_PACKAGE_REMOVED;
import static com.sheep.gamegroup.view.adapter.TryMakeMoneyAdp.PUBLIC_TAG_PREFIX_TEXTVIEW_LIST;


/**
 * Created by realicing on 2018/9/6.
 * realicing@sina.com
 */
public class ActMain extends BaseActYmPermissionCheck {
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        StatusBarUtils.setTranslucent(this);
        super.onCreate(savedInstanceState);
        //第一次进入主页检查是否是会长推广的游戏，并显示弹出框
        if (DataUtil.getAsBoolean(FIRST_SHOW_MAIN, true)) {
            DataUtil.putAsBoolean(FIRST_SHOW_MAIN, false);
            String game_id = ChannelContent.getInstance().getGameId();
            if (game_id != null) {
                ActionUtil.getInstance().addNextAction(MiddleSchemeAct.SHOW_DIALOG_GAME_OR_GIFT_TASK, game_id);
            }
        }  //获取顶层视图
        decorView = getWindow().getDecorView();
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        setSystemUiVisibility();
    }

    private void setSystemUiVisibility() {
        //判断当前版本在4.0以上并且存在虚拟按键，否则不做操作
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT && G.checkDeviceHasNavigationBar(this)) {
            //一定要判断是否存在按键，否则在没有按键的手机调用会影响别的功能。如之前没有考虑到，导致图传全屏变成小屏显示。
            int flag =
//                    View.SYSTEM_UI_FLAG_LAYOUT_STABLE |
                    View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR |
                            View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION |
                            View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN |
                            View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | // hide
//                    View.SYSTEM_UI_FLAG_FULLSCREEN | // hide status bar
                            View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY;
            // 获取属性
            decorView.setSystemUiVisibility(flag);
        }
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        return false;
    }

    private View decorView;

    public static final String FIRST_SHOW_MAIN = "first_show_main";//是否是第一次显示主页

    @BindView(R.id.view_pager_container)
    ViewPager view_pager_container;
    @BindView(R.id.frame_container)
    FrameLayout frame_container;
    @BindView(R.id.tab_container)
    LinearLayout tab_container;
    @BindView(R.id.main_layout)
    RelativeLayout main_layout;

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

    @Override
    public void initView() {
        EventBus.getDefault().register(this);
        initViewPager();
        initFind();
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && G.checkDeviceHasNavigationBar(this)) {
//            main_layout.setPadding(0, 0, 0, G.getHasVirtualKey(this) - G.getNoHasVirtualKey(this));
//        }

        CommonUtil.getInstance().initMiDong(this, DataUtil.getInstance().getUserId());
    }

    @Override
    public void initListener() {

    }

    @Override
    public void initData() {

    }

    private List<Fragment> fragmentList = new ArrayList<>();

    private int lastPosition = MainTab.FgtSmallSheep.ordinal();//默认选中小绵羊

    //多次点击预防
    public static final int MIN_CLICK_DELAY_TIME = 200;
    private long lastClickTime = 0;

    private void initViewPager() {

        MainTab[] mainTabs = MainTab.values();
        int index = 0;
        for (MainTab mainTab : mainTabs) {
            fragmentList.add(mainTab.getFragment());

            View view = tab_container.getChildAt(index * 2 + 1);
            if (view instanceof TextView) {
                ((TextView) view).setText(mainTab.getStringId());
                new DrawablesHelper((TextView) view).direction(DrawablesHelper.TOP).drawable(mainTab.getDrawableId()).commit();
            }
            tabs.add(view);
            final int position = index;
            view.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    long currentTime = System.currentTimeMillis();
                    if (currentTime - lastClickTime > MIN_CLICK_DELAY_TIME) {
                        lastClickTime = currentTime;
                        view_pager_container.setCurrentItem(position, false);
                        checkWhichPage(position);
                    }


                }
            });
            index++;
        }
        //隐藏不显示的控件
        for (int i = index * 2; i < tab_container.getChildCount() - 1; i++) {
            tab_container.getChildAt(i).setVisibility(View.GONE);
        }
        ViewPagerFragmentAdapter mViewPagerFragmentAdapter = new ViewPagerFragmentAdapter(getSupportFragmentManager(), fragmentList);
        view_pager_container.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {

            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                //设置tab选择状态
                View lastTab = ListUtil.getItem(tabs, lastPosition);
                View curTab = ListUtil.getItem(tabs, position);
                if (lastTab != null)
                    lastTab.setActivated(false);
                if (curTab != null)
                    curTab.setActivated(true);
                if (lastPosition == MainTab.FgtSmallSheep.ordinal() && position != MainTab.FgtSmallSheep.ordinal()) {
                    ((FgtSmallSheep) MainTab.FgtSmallSheep.getFragment()).onPause();
                }
                showFind(position == MainTab.Fgt_Find.ordinal());
                //更新position
                lastPosition = position;
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        view_pager_container.setAdapter(mViewPagerFragmentAdapter);
        view_pager_container.setCurrentItem(lastPosition, false);
        //添加viewpager 缓存个数，解决邀请赚钱好友切换问题
        view_pager_container.setOffscreenPageLimit(mViewPagerFragmentAdapter.getCount());
        tabs.get(lastPosition).setActivated(true);
    }

    /**
     * 统计
     *
     * @param position
     */
    private void checkWhichPage(int position) {
        if (position == MainTab.FgtSmallSheep.ordinal()) {//赚钱
            UMConfigUtils.Event.TAB_SHEEP.onEvent();
        } else if (position == MainTab.Fgt_Find.ordinal()) {//发现
            UMConfigUtils.Event.TAB_FIND.onEvent();
        } else if (position == MainTab.FgtPersonnalCenter.ordinal()) {//个人中心
            UMConfigUtils.Event.TAB_USER.onEvent();
        }
    }

    private void showFind(boolean isFind) {
        if (isFind) {
            fgtFind.setUserVisibleHint(true);
            frame_container.bringToFront();
        } else {
            fgtFind.setUserVisibleHint(false);
            view_pager_container.bringToFront();
        }
    }

    private Fragment fgtFind;

    public void initFind() {
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        Fragment fragment = getSupportFragmentManager().findFragmentByTag("tag");
        if (fragment == null) {
            fragment = new FgtFind();
            transaction.add(R.id.frame_container, fragment, "tag");
            transaction.commitAllowingStateLoss();
        } else {
            transaction.replace(R.id.frame_container, fragment);
            transaction.commitAllowingStateLoss();
        }
        fgtFind = fragment;
    }

    private long mLastBackTime = 0;//上次按退出按钮的时间

    /**
     * 点返回按钮时的多情况处理
     */
    private void doBackPress() {
        if (System.currentTimeMillis() - mLastBackTime < 1000) {
            SheepApp.getInstance().quit();
        } else {
            try {
                G.showToast(R.string.toast_double_click_exit_app);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        mLastBackTime = System.currentTimeMillis();
    }

    private long lastBackTime = 0;
    private int pressCount = 0;
    private static final int PERIOD = 400;

    @Override
    public void onBackPressed() {
        if (System.currentTimeMillis() - lastBackTime < PERIOD) {
            pressCount = pressCount + 1;
            Observable.just(1).delay(PERIOD * pressCount, TimeUnit.MILLISECONDS)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new AbsObserver<Integer>() {
                        @Override
                        public void onNext(Integer integer) {
                            doBackPress();
                        }
                    });
        } else {
            pressCount = 0;
            doBackPress();
        }
        lastBackTime = System.currentTimeMillis();
    }


    private List<View> tabs = new ArrayList<>();

    private Container<Action1<Integer>> container = new Container<>();

    public Container<Action1<Integer>> getContainer() {
        return container;
    }

    private int onResumeCount = 0;//调用onResume次数

    @Override
    protected void onResume() {
        super.onResume();
        if (container != null && container.getT() != null)
            container.getT().call(1);
        if (checkNextAction(MiddleSchemeAct.SHOW_DIALOG_GAME_OR_GIFT_TASK)) {
            if (onResumeCount == 0) {
                DataUtil.putAsBoolean("tryShowHalfScreenAd", true);
            }
        } else {
            if (onResumeCount == 0 && !TestUtil.isDev()) {
                SysAppUtil.showVersionInfo(this, SpUtils.getIgnoreMd5(), new Action1<Integer>() {
                    @Override
                    public void call(Integer integer) {
                        Jump2View.getInstance().tryShowHalfScreenAd(ActMain.this, getContainer());
                    }
                });
            }
        }
        onResumeCount++;
    }

    @Override
    public void doNextAction(Object action) {
        if (action instanceof String) {
            String game_id = action.toString();
            if (TextUtils.isEmpty(game_id)) {
                if (TestUtil.isTest())
                    G.showToast("game_id为空");
            } else {
                new DialogGameOrTaskOrGift(this, game_id).showDialog();
            }
        } else if (action instanceof MainTab) {
            view_pager_container.setCurrentItem(((MainTab) action).ordinal(), false);
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (container != null && container.getT() != null)
            container.getT().call(2);
    }

    //包含更新进度的view的view(会长推广弹出框中有下载进度用到)
    private View progressView;
    private DownloadHelper downloadHelper;
    private String packageName;
    private String url;

    public void setPackageName(String packageName) {
        this.packageName = packageName;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public void setProgressView(View progressView) {
        this.progressView = progressView;
    }

    public void setDownloadHelper(DownloadHelper downloadHelper) {
        this.downloadHelper = downloadHelper;
    }

    /**
     * 主要的事件广播接收更新处理
     *
     * @param event
     */
    @Subscribe
    public void onEventMainThread(BigEvent event) {
        switch (event.getEventTypes()) {
            case STORAGE_LOW:
                DialogStorageLow.showDialog(null);
                break;
        }
        if (progressView != null && event.getData() instanceof DownLoadInfo) {
            DownLoadInfo task = (DownLoadInfo) event.getData();
            String url = task.getMDownloadUrl();
            TextView tvProgress = progressView.findViewWithTag(PUBLIC_TAG_PREFIX_TEXTVIEW_LIST + url);
            if (tvProgress != null) {
                switch (event.getEventTypes()) {
                    case DOWNLOAD_RUNNING:
                        try {
                            int p = task.getMPercent();    //任务进度百分比
                            tvProgress.setText(String.format(Locale.CHINA, "%d%%", Math.abs(p)));

                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        break;
                    case DOWNLOAD_STOP:
                        tvProgress.setText("继续下载");
                        break;
                    case DOWNLOAD_COMPLETE:
                        tvProgress.setText("安装游戏");
                        if (downloadHelper != null)
                            downloadHelper.updateState(DownloadUtil.STATUS_FINISH);
                        break;
                    case DOWNLOAD_CANCEL:
                        tvProgress.setText("下载取消");
                        break;
                    case DOWNLOAD_FAIL:
                        tvProgress.setText("下载失败");
                        break;
                }
            }
        }
    }

    @Subscribe
    public void onEventMainThread(Intent intent) {
        if (intent != null && intent.getAction() != null && intent.getDataString() != null && intent.getDataString().contains("package:")) {
            String packageName = intent.getDataString().replace("package:", "");
            if (progressView != null) {
                TextView tvProgress = progressView.findViewWithTag(PUBLIC_TAG_PREFIX_TEXTVIEW_LIST + url);
                if (tvProgress != null && downloadHelper != null && TextUtils.equals(packageName, this.packageName)) {
                    switch (intent.getAction()) {
                        case ACTION_PACKAGE_ADDED:
                            tvProgress.setText(CommonUtil.GAME_OPEN);
                            downloadHelper.updateState(DownloadUtil.STATUS_INSTALLED);
                            break;
                        case ACTION_PACKAGE_REMOVED:
                            String path = PackageUtil.isExistsFile(packageName, url);
                            if (TextUtils.isEmpty(path)) {
                                downloadHelper.updateState(DownloadUtil.STATUS_INIT);
                                tvProgress.setText(CommonUtil.START_DOWNLOAD);
                            } else {
                                downloadHelper.updateState(DownloadUtil.STATUS_FINISH);
                                tvProgress.setText(CommonUtil.START_INSTALL);
                            }
                            break;
                    }
                }
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        CommonUtil.getInstance().onDestroy();
        if (container != null && container.getT() != null)
            container.setT(null);

    }
}
