package com.xxfc.discovery;

import android.Manifest;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Build;
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.text.TextUtils;
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.util.permission.RxPermission;
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.PostPatEvent;
import com.xxfc.discovery.event.PostVideoEvent;
import com.xxfc.discovery.fragment.PatFragment;
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 com.yuyife.okgo.OkGoUtil;

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

import butterknife.BindView;
import butterknife.OnClick;
import butterknife.Unbinder;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import pub.devrel.easypermissions.AppSettingsDialog;

/**
 * 发现模块
 */
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(PostVideoEvent.class)
                .observeOn(Schedulers.newThread())
                .subscribe(new Observer<PostVideoEvent>(disposable) {
                    @Override
                    public void onNext(PostVideoEvent event) {
                        menuAdapter.setSelectItem(2);
                        mViewPager.setCurrentItem(2);
                    }
                });

        RxBus.tObservable(PostPatEvent.class)
                .observeOn(Schedulers.newThread())
                .subscribe(new Observer<PostPatEvent>(disposable) {
                    @Override
                    public void onNext(PostPatEvent event) {
                        menuAdapter.setSelectItem(1);
                        mViewPager.setCurrentItem(1);
                    }
                });
    }

    @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);
            //判断是否已经登录
//            if (TextUtils.isEmpty(OkGoUtil.getToken())) {
//                ARouter.getInstance().build(Constance.ACTIVITY_URL_LOGINRV).navigation();
//                return;
//            }
//
//            ARouter.getInstance()
//                    .build(Constance.ACTIVITY_URL_POSTPAT)
//                    .navigation();

        }
    }

    /******
     * 切换事件
     */
    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) {
                        //判断是否已经登录
                        if (TextUtils.isEmpty(OkGoUtil.getToken())) {
                            ARouter.getInstance().build(Constance.ACTIVITY_URL_LOGINRV).navigation();
                            return;
                        }

                        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) {
//                            verifyAudioPermissions(_mActivity);
                            processPicker();

                            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;
            }
        });
    }

    /**
     * 打开相机和相册
     *
     * @param
     */
    private void processPicker() {
        /**
         * 6.0以上手机做权限处理
         */
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            new RxPermission(_mActivity).request(
                    Manifest.permission.WRITE_EXTERNAL_STORAGE,
                    Manifest.permission.CAMERA, Manifest.permission.RECORD_AUDIO).subscribe(new Consumer<Boolean>() {
                @Override
                public void accept(Boolean aBoolean) throws Exception {
                    if (aBoolean == true) {
                        //短视频
                        ARouter.getInstance()
                                .build(Constance.ACTIVITY_URL_RECORDXACTIVITY)
                                .navigation();
                    } else {
                        new AppSettingsDialog.Builder(DiscoveryFragment.this).
                                setTitle("需要获取相机权限、存储权限")
                                .setRationale("如果没有此权限，此应用程序可能无法正常工作,是否打开设置修改该应用权限")
                                .build().show();
                    }
                }
            });
        } else {

        }
        //两个日历权限和一个数据读写权限
//        String[] permissions = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA, Manifest.permission.RECORD_AUDIO};
////        PermissionsUtils.showSystemSetting = false;//是否支持显示系统设置权限设置窗口跳转
//        //这里的this不是上下文，是Activity对象！
//        PermissionsUtils.getInstance().chekPermissions(_mActivity, permissions, permissionsResult);
    }
}