package com.kfzs.duanduan.react;

import android.os.Bundle;
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.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.FgtFind;
import com.kfzs.duanduan.fragment.FgtPersonalCenter;
import com.kfzs.duanduan.fragment.FgtSmallSheep;
import com.sheep.gamegroup.util.DrawablesHelper;
import com.sheep.gamegroup.util.LogUtil;
import com.sheep.gamegroup.util.SysAppUtil;
import com.sheep.gamegroup.util.UMConfigUtils;
import com.sheep.gamegroup.view.fragment.FgtMainAudit;
import com.sheep.jiuyan.samllsheep.R;

import java.util.ArrayList;
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 = 200;
    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 ItemPosition itemPosition;
    public TabsHelper() {
    }
    public TabsHelper(ItemPosition itemPosition) {
        this.itemPosition = itemPosition;
    }

    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) {

            KFZSApp.getInstance().quit();
        } else {
            ToastBuilder.make(activity.getApplicationContext(), R.string.toast_double_click_exit_app, ToastBuilder.DEFAULT_TOAST_SINGLE);
            SysAppUtil.isNewSmallSheep(true);//不知什么原因，之前在弹出弹窗广告时的设置为true可能没有效果，这里再保存一次吧
        }
        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 = System.currentTimeMillis();
                    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();
                        int auditPosition = MainTab.FgtMainAudit.ordinal();
                        int fPosition = MainTab.Fgt_Find.ordinal();
                        FgtSmallSheep fgtSmallSheep = (FgtSmallSheep) fragmentList.get(sheepPosition);
                        FgtPersonalCenter personnalCenter = (FgtPersonalCenter) fragmentList.get(personnalPosition);
                        FgtMainAudit auditFgt = (FgtMainAudit) fragmentList.get(auditPosition);
//                        FgtFind findFgt = (FgtFind) fragmentList.get(fPosition);
                        if(position == sheepPosition){
                            fgtSmallSheep.onResume();
                        } else {
                            fgtSmallSheep.onPause();
                        }
                        if(position == personnalPosition){
                            personnalCenter.onResume();
                        }
                        if(position == auditPosition){
                            auditFgt.onResume();
                        }
                        if(position == fPosition){
//                            findFgt.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.FgtSmallSheep.ordinal()) {//赚钱
            itemPosition.positionClick(0);
            UMConfigUtils.Event.TAB_SHEEP.onEvent();
        }else if(position == MainTab.Fgt_Find.ordinal()) {//发现
            itemPosition.positionClick(1);
            UMConfigUtils.Event.TAB_FIND.onEvent();
        }else if(position == MainTab.FgtPersonnalCenter.ordinal()) {//个人中心
            itemPosition.positionClick(2);
            UMConfigUtils.Event.TAB_USER.onEvent();
        }else if (position==MainTab.FgtMainAudit.ordinal()){//审核
            itemPosition.positionClick(3);
        }else if(position==MainTab.FgtMainAskGetMoney.ordinal()){//邀请
            itemPosition.positionClick(4);
        }
    }

    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() {
        LogUtil.logI("fragmentList.size---"+fragmentList.size());
        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);
                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);
        tabs.get(lastPosition).setActivated(true);
        checkViewState(lastPosition);
    }

    private void showFind(boolean isFind) {
        View frame_container = activity.findViewById(R.id.frame_container);
        if(isFind)
            frame_container.bringToFront();
        else
            other_container.bringToFront();
    }

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

        FragmentTransaction transaction = activity.getSupportFragmentManager().beginTransaction();
        Bundle bundle = new Bundle();
        Fragment fragment = activity.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 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();
    }

    /**
     * 设置获取当前是哪个fragment位置的回调
     */
   public interface ItemPosition{
        /**
         * @param position ,fragment的位置
         */
        void positionClick(int position);
    }

}
