package com.sheep.gamegroup.view.activity;

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.view.View;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.sheep.gamegroup.model.entity.SystemNotification;
import com.sheep.gamegroup.view.adapter.ViewPagerFragmentAdapter;
import com.sheep.gamegroup.event.BigEvent;
import com.sheep.gamegroup.view.fragment.FgtAudit;
import com.sheep.gamegroup.view.fragment.FgtFind;
import com.sheep.gamegroup.util.MainTab;
import com.kfzs.duanduan.utils.StatusBarUtils;
import com.kfzs.duanduan.view.DialogStorageLow;
import com.sheep.gamegroup.absBase.BaseActivity;
import com.sheep.gamegroup.model.entity.Container;
import com.sheep.gamegroup.util.DrawablesHelper;
import com.sheep.gamegroup.util.ListUtil;
import com.sheep.gamegroup.util.UMConfigUtils;
import com.sheep.gamegroup.view.fragment.FgtMainAudit;
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 org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

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

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


/**
 * Created by realicing on 2018/9/6.
 * realicing@sina.com
 */
public class ActMain extends BaseActivity {
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        StatusBarUtils.setTranslucent(this);
        super.onCreate(savedInstanceState);
    }

    @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() {
        ButterKnife.bind(this);
        EventBus.getDefault().register(this);
        initViewPager();
        initFind();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            main_layout.setPadding(0, 0, 0, G.getHasVirtualKey(this) -G.getNoHasVirtualKey(this) );

        }
    }

    @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();
        } else if (position == MainTab.FgtMainAudit.ordinal()) {//审核
        } else if (position == MainTab.FgtMainAskGetMoney.ordinal()) {//邀请
        }
    }

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

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

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

    /**
     * 点返回按钮时的多情况处理
     */
    private void doBackPress() {
        if (System.currentTimeMillis() - mLastBackTime < 1000) {
            SheepApp.getInstance().quit();
        } else {
            G.showToast(R.string.toast_double_click_exit_app);
        }
        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 Action1<Integer>() {
                        @Override
                        public void call(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;
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (container != null && container.getT() != null)
            container.getT().call(1);
    }
    @Override
    public void doNextAction(Object action){
        if(action instanceof SystemNotification){
            int auditPosition = MainTab.FgtMainAudit.ordinal();
            view_pager_container.setCurrentItem(auditPosition, false);
            FgtMainAudit fragment = (FgtMainAudit) fragmentList.get(auditPosition);
            switch (((SystemNotification) action).getType()){//5:任务成功 6:任务失败
                case 5:
                    fragment.setCurrentItem(1, false);//审核成功在位置1
                    break;
                case 6:
                    fragment.setCurrentItem(2, false);//审核失败在位置2
                    break;
            }
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (container != null && container.getT() != null)
            container.getT().call(2);
    }
    /**
     * 主要的事件广播接收更新处理
     *
     * @param event
     */
    @Subscribe
    public void onEventMainThread(BigEvent event) {
        switch (event.getEventTypes()) {
            case STORAGE_LOW:
                DialogStorageLow.showDialog(this);
                break;
        }
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        if (container != null && container.getT() != null)
            container.setT(null);
    }
}
