package com.xxfc.discovery;

import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.PopupWindow;

import com.alibaba.android.arouter.launcher.ARouter;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.frame.base.bus.Observer;
import com.frame.base.bus.RxBus;
import com.frame.base.url.Constance;
import com.ruiwenliu.wrapper.adapter.TabAdapter;
import com.ruiwenliu.wrapper.base.BaseBean;
import com.ruiwenliu.wrapper.base.BaseFragment;
import com.ruiwenliu.wrapper.util.ViewHolder;
import com.ruiwenliu.wrapper.weight.horizontal.GallerySnapHelper;
import com.ruiwenliu.wrapper.weight.horizontal.SpaceItemDecoration;
import com.xxfc.discovery.adapter.DiscoveryMenuAdapter;
import com.xxfc.discovery.event.DiscoveryAddEvent;
import com.xxfc.discovery.fragment.PatFragment;
import com.xxfc.discovery.fragment.QuestionAndAnswerFragment;
import com.xxfc.discovery.fragment.RecommendFragment;
import com.xxfc.discovery.fragment.ShortVideoFragment;
import com.xxfc.discovery.popupwindow.AddDiscoveryContentPw;
import com.xxfc.discovery.presenter.DiscoveryPresenter;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import butterknife.Unbinder;
import io.reactivex.schedulers.Schedulers;

/**
 * 发现模块
 */
public class DiscoveryFragment extends BaseFragment<DiscoveryPresenter> {

    @BindView(R2.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R2.id.order_viewPager)
    ViewPager mViewPager;
    Unbinder unbinder;
    @BindView(R2.id.iv_discovery_content_add)
    ImageView ivDiscoveryContentAdd;

    private DiscoveryMenuAdapter menuAdapter;
    private TabAdapter mAdapter;
    public final static int TYPE_RECOMMEND = 0;//推荐
    public final static int TYPE_PAT = 1;//拍拍
    public final static int TYPE_SHORT_VIDEO = 2;//短视频
    public final static int TYPE_QUESTION_AND_ANSWER = 3;//问题
    private int menuPosition;

    private AddDiscoveryContentPw mPop;
    private boolean isShow = true;


    public static DiscoveryFragment getInstance(int type) {
        Bundle bundl = new Bundle();
        bundl.putInt("type", type);
        DiscoveryFragment fragment = new DiscoveryFragment();
        fragment.setArguments(bundl);
        return fragment;
    }

    @Override
    public int getViewLayout() {
        return R.layout.fragment_discovery;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        initRecyclerView();
        initViewpager();
        initRxbus();
    }

    private void initRxbus() {
        RxBus.tObservable(DiscoveryAddEvent.class)
                .observeOn(Schedulers.newThread())
                .subscribe(new Observer<DiscoveryAddEvent>(disposable) {
                    @Override
                    public void onNext(DiscoveryAddEvent event) {
                        if (1 == event.getType()) {

                        } else if (2 == event.getType()) {

                        } else if (3 == event.getType()) {
//                            menuAdapter.setSelectItem(3);
//                            mViewPager.setCurrentItem(3);
                        }
                    }
                });
    }

    @Override
    protected void loadData(Bundle savedInstanceState) {

    }


    @Override
    public void onShowResult(int requestType, BaseBean result) {

    }

    /**
     * 初始化RecyclerView
     */
    private void initRecyclerView() {
        recyclerView.setLayoutManager(new GridLayoutManager(_mActivity, 4));
        menuAdapter = new DiscoveryMenuAdapter();
        recyclerView.setAdapter(menuAdapter);
        recyclerView.addItemDecoration(new SpaceItemDecoration(5));
        GallerySnapHelper snapHelper = new GallerySnapHelper();
        snapHelper.attachToRecyclerView(recyclerView);
        List<String> list = new ArrayList<>();
        list.add(_mActivity.getString(R.string.discovery_recommend));
        list.add(_mActivity.getString(R.string.discovery_pat));
        list.add(_mActivity.getString(R.string.discovery_short_video));
        list.add(_mActivity.getString(R.string.discovery_question_and_answer));
        menuAdapter.setNewData(list);
        menuAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                menuAdapter.setSelectItem(position);
                mViewPager.setCurrentItem(position);
            }
        });
    }


    /**
     * 初始化Viewpager
     */
    private void initViewpager() {
        mAdapter = new TabAdapter(getChildFragmentManager(), getListFragment());
        mViewPager.setAdapter(mAdapter);
        mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                menuAdapter.setSelectItem(position);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        mViewPager.setOffscreenPageLimit(mAdapter.getCount());
        menuAdapter.setSelectItem(menuPosition);
        mViewPager.setCurrentItem(menuPosition);
    }


    private List<BaseFragment> getListFragment() {
        List<BaseFragment> list = new ArrayList<>();
        list.add(RecommendFragment.getInstance(TYPE_RECOMMEND));
        list.add(PatFragment.getInstance(TYPE_PAT));
        list.add(ShortVideoFragment.getInstance(TYPE_SHORT_VIDEO));
        list.add(QuestionAndAnswerFragment.getInstance(TYPE_QUESTION_AND_ANSWER));
        return list;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        mAdapter.getCurrentFragment().onActivityResult(requestCode, resultCode, data);
    }

    public SwitchListener switchListener = new SwitchListener() {
        @Override
        public void switchTab(int position) {
            if (menuAdapter != null && mViewPager != null) {
                menuAdapter.setSelectItem(position);
                mViewPager.setCurrentItem(position);
            }
        }
    };


    @OnClick({R2.id.iv_discovery_content_add})
    public void onViewClicked(View view) {
        int id = view.getId();
        if (id == R.id.iv_discovery_content_add) {
            //添加
            showPopupWindow(ivDiscoveryContentAdd);
        }
    }

    /******
     * 切换事件
     */
    public interface SwitchListener {
        void switchTab(int position);
    }

    /**
     * 展示menu属性 窗体
     */
    private void showPopupWindow(final View view) {
        mPop = new AddDiscoveryContentPw(_mActivity) {
            @Override
            public void helper(ViewHolder helper) {
                super.helper(helper);
                helper.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        int id = v.getId();
                        if (id == R.id.tv_pat) {
                            //拍拍
                            ARouter.getInstance()
                                    .build(Constance.ACTIVITY_URL_POSTPAT)
                                    .navigation();
                            dismiss();

                        } else if (id == R.id.tv_short_video) {
                            //短视频
                            ARouter.getInstance()
                                    .build(Constance.ACTIVITY_URL_SENDVIDEO)
                                    .navigation();
                            dismiss();
                        } else if (id == R.id.tv_ask_questions) {
                            //去提问
                            ARouter.getInstance()
                                    .build(Constance.ACTIVITY_URL_PUBLISHINGPROBLEM)
                                    .navigation();
                            dismiss();
                        }
                    }
                }, R.id.tv_pat, R.id.tv_short_video, R.id.tv_ask_questions);
            }
        };
        mPop.setTouchable(true); // 设置popupwindow可点击
        mPop.setBackgroundDrawable(new BitmapDrawable());
        mPop.setOutsideTouchable(true);
        mPop.update();

        if (isShow) {
            mPop.showPopupWindow(view);
        } else {
            mPop.dismiss();
        }
        isShow = !isShow;


        mPop.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                isShow = true;
            }
        });
    }
}
