package com.kfzs.duanduan.react;

import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.kf.utils.ToastBuilder;
import com.kfzs.duanduan.ActMain;
import com.kfzs.duanduan.KFZSApp;
import com.kfzs.duanduan.adp.ViewPagerFragmentAdapter;
import com.kfzs.duanduan.fragment.FgtPersonalCenter;
import com.kfzs.duanduan.fragment.FgtSmallSheep;
import com.kfzs.libs.utils.DrawablesHelper;
import com.sheep.gamegroup.util.UMConfigUtils;
import com.sheep.jiuyan.samllsheep.R;

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

import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;


/**
 * Created by realicing on 2017/11/24.
 */

public class TabsHelper {

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

    LinearLayout other_container;

    View layout_main_activity_toolbar;
    View layout_bottom;
    LinearLayout tab_container;
    View tab_line;

    private ViewPager view_pager_container;
    private TextView mTxtToolBar;


    private void initViews() {
        activity = KFZSApp.actMain;
        other_container = activity.findViewById(R.id.other_container);
        view_pager_container = activity.findViewById(R.id.view_pager_container);
        layout_main_activity_toolbar = activity.findViewById(R.id.layout_main_activity_toolbar);
        layout_bottom = activity.findViewById(R.id.layout_bottom);
        tab_container = activity.findViewById(R.id.tab_container);
        tab_line = activity.findViewById(R.id.tab_line);
        mTxtToolBar = activity.findViewById(R.id.txt_main_activity_toolbar);
    }

    private List<Fragment> fragmentList = new ArrayList<>();
    private long mLastBackTime = 0;//上次按退出按钮的时间

    /**
     * 点返回按钮时的多情况处理
     */
    private void nativeBack() {
        if (System.currentTimeMillis() - mLastBackTime < 1000) {
            //退出统计
            UMConfigUtils.onProfileSignOff();

            KFZSApp.getInstance().quit();
        } else {
            ToastBuilder.make(activity.getApplicationContext(), R.string.toast_double_click_exit_app, ToastBuilder.DEFAULT_TOAST_SINGLE);
        }
        mLastBackTime = System.currentTimeMillis();
    }


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

    private void initArrays() {
        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 = Calendar.getInstance().getTimeInMillis();
                    if (currentTime - lastClickTime > MIN_CLICK_DELAY_TIME) {
                        lastClickTime = currentTime;

                        checkViewState(position);
                        view_pager_container.setCurrentItem(position, false);
                        int sheepPosition = MainTab.FgtSmallSheep.ordinal();
                        int personnalPosition = MainTab.FgtPersonnalCenter.ordinal();
                        FgtSmallSheep fgtSmallSheep = (FgtSmallSheep) fragmentList.get(sheepPosition);
                        FgtPersonalCenter personnalCenter = (FgtPersonalCenter) fragmentList.get(personnalPosition);
                        if(position == sheepPosition){
                            fgtSmallSheep.onResume();
                        } else {
                            fgtSmallSheep.onPause();
                        }
                        if(position == personnalPosition){
                            personnalCenter.onResume();
                        }
                        checkWhichPage(position);
                    }

                }
            });
            index++;
        }
        //隐藏不显示的控件
        for (int i = index * 2; i < tab_container.getChildCount()-1; i++) {
           tab_container.getChildAt(i).setVisibility(View.GONE);
        }
    }

    /**
     * 统计
     * @param position
     */
    private void checkWhichPage(int position){
        /*if(position == MainTab.FgtMainGame.ordinal()) {
            UMConfigUtils.onEvent(UMConfigUtils.Event.TAB_GAME);
        }else if(position == MainTab.FgtMainCategory.ordinal()) {
            UMConfigUtils.onEvent(UMConfigUtils.Event.TAB_CATEGORY);
        }else */if(position == MainTab.FgtSmallSheep.ordinal()) {
            UMConfigUtils.onEvent(UMConfigUtils.Event.TAB_SHEEP);
//        }else if(position == MainTab.Bp.ordinal()) {
//            UMConfigUtils.onEvent(UMConfigUtils.Event.TAB_JIEZHEWAN);
//        }else if(position == MainTab.CreditCard.ordinal()) {
//            UMConfigUtils.onEvent(UMConfigUtils.Event.TAB_CREDITCARD);
        }
    }

    private void checkViewState(int position) {
        int top;
        int bottom;
       /*if(position == MainTab.FgtMainGame.ordinal()) {
           top = activity.getResources().getDimensionPixelSize(R.dimen.app_nav_toolbar_height);
           bottom = 0;
           layout_main_activity_toolbar.setVisibility(View.VISIBLE);
           if (!isGetAdvertisementDialogData) {
               isGetAdvertisementDialogData = true;
               activity.getAdvertisementDialogData();//获取广告弹窗信息
           }
       }else if(position == MainTab.FgtMainCategory.ordinal()) {
           top = activity.getResources().getDimensionPixelSize(R.dimen.app_nav_toolbar_height);
           bottom = activity.getResources().getDimensionPixelSize(R.dimen.bottom_height);
           layout_main_activity_toolbar.setVisibility(View.VISIBLE);
       } else*/ {
            top = 0;
            bottom = activity.getResources().getDimensionPixelSize(R.dimen.bottom_height);
            layout_main_activity_toolbar.setVisibility(View.GONE);
        }
        RelativeLayout.LayoutParams layout = (RelativeLayout.LayoutParams) other_container
                .getLayoutParams();
        layout.setMargins(0, top, 0, bottom);
        other_container.setLayoutParams(layout);
    }
    private boolean isGetAdvertisementDialogData = false;

    public int getCurrentItem() {
        return view_pager_container.getCurrentItem();
    }

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

    private void initViewPager() {
        ViewPagerFragmentAdapter mViewPagerFragmentAdapter = new ViewPagerFragmentAdapter(activity.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选择状态
                if (lastPosition > -1)
                    tabs.get(lastPosition).setActivated(false);
                tabs.get(position).setActivated(true);
                //更新position
                lastPosition = position;
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        view_pager_container.setAdapter(mViewPagerFragmentAdapter);
        view_pager_container.setCurrentItem(lastPosition, false);
        tabs.get(lastPosition).setActivated(true);
        checkViewState(lastPosition);
    }

    public void init() {
        initViews();
        initArrays();
        initViewPager();
    }

    private long lastbackrn = 0;
    private int presscount = 0;
    private final int period = 400;

    public void onBackPressed() {
        if (System.currentTimeMillis() - lastbackrn < 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();
        }
        lastbackrn = System.currentTimeMillis();
    }

    private void doBackPress() {
        nativeBack();
    }

    public void goToPostion(int postion) {
        tabs.get(postion).performClick();
    }

}
