package com.cooleshow.student.ui.course;

import android.view.View;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.GridLayoutManager;

import com.alibaba.android.arouter.launcher.ARouter;
import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.CustomListener;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.chad.library.adapter.base.listener.OnLoadMoreListener;
import com.cooleshow.base.common.WebConstants;
import com.cooleshow.base.constanst.Constants;
import com.cooleshow.base.router.RouterPath;
import com.cooleshow.base.ui.fragment.BaseMVPFragment;
import com.cooleshow.base.utils.LogUtils;
import com.cooleshow.base.utils.SizeUtils;
import com.cooleshow.base.widgets.EmptyViewLayout;
import com.cooleshow.base.widgets.poplist.PopMenuBean;
import com.cooleshow.base.widgets.poplist.PopupListWindow;
import com.cooleshow.student.R;
import com.cooleshow.student.adapter.CourseStatusFilterAdapter;
import com.cooleshow.student.adapter.VideoCourseListAdapter;
import com.cooleshow.student.bean.QuerySubjectBean;
import com.cooleshow.student.bean.SelectMyGroupBean;
import com.cooleshow.student.constants.CourseConstants;
import com.cooleshow.student.contract.VideoCourseContract;
import com.cooleshow.student.databinding.FragmentVideoCourseLayoutBinding;
import com.cooleshow.student.presenter.course.VideoCoursePresenter;
import com.cooleshow.student.wxapi.VideoCourseListItemDecoration;
import com.cooleshow.usercenter.helper.UserHelper;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;

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

/**
 * Author by pq, Date on 2022/4/25.
 */
public class VideoCourseFragment extends BaseMVPFragment<FragmentVideoCourseLayoutBinding, VideoCoursePresenter> implements VideoCourseContract.VideoCourseView, View.OnClickListener {
    private int currentSubjectId;
    private int currentPage;
    private VideoCourseListAdapter mAdapter;
    private EmptyViewLayout mEmptyView;
    private boolean hasNext = true;
    private boolean isFirstLoad = true;
    private List<QuerySubjectBean> subjectBeanList = new ArrayList<>();
    private OptionsPickerView pvOptions;

    public static VideoCourseFragment newInstance() {
        VideoCourseFragment fragment = new VideoCourseFragment();
        return fragment;
    }

    @Override
    protected FragmentVideoCourseLayoutBinding getLayoutView() {
        return FragmentVideoCourseLayoutBinding.inflate(getLayoutInflater());
    }

    @Override
    protected VideoCoursePresenter createPresenter() {
        return new VideoCoursePresenter();
    }

    @Override
    protected void initView(View rootView) {
        mViewBinding.tvSubject.setOnClickListener(this);
    }

    @Override
    public void onResume() {
        super.onResume();
        if (isFirstLoad) {
            isFirstLoad = false;
            reBuildFilter();
        }
    }

    @Override
    public void refreshData() {
        super.refreshData();
        reBuildFilter();
        isFirstLoad = false;
    }

    private void reBuildFilter() {
        currentPage = 1;
        queryCourse(true);
    }


    @Override
    protected void initData() {
        mViewBinding.refreshLayout.setOnRefreshListener(refreshLayout -> refresh());

        mAdapter = new VideoCourseListAdapter(R.layout.item_video_course_list_layout);
        mAdapter.getLoadMoreModule().setOnLoadMoreListener(() -> {
            //上拉加载
            if (hasNext) {
                loadMore();
            } else {
                mAdapter.getLoadMoreModule().loadMoreEnd();
            }
        });
        mAdapter.getLoadMoreModule().setAutoLoadMore(true);
        //当自动加载开启，同时数据不满一屏时，是否继续执行自动加载更多(默认为true)
        mAdapter.getLoadMoreModule().setEnableLoadMoreIfNotFullPage(false);

        GridLayoutManager gridLayoutManager = new GridLayoutManager(requireContext(), 2);
        gridLayoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
            @Override
            public int getSpanSize(int position) {
                int itemViewType = mAdapter.getItemViewType(position);
                if (itemViewType == BaseQuickAdapter.LOAD_MORE_VIEW) {
                    return 2;
                }
                return 1;
            }
        });
        VideoCourseListItemDecoration itemDecoration = new VideoCourseListItemDecoration(0, SizeUtils.dp2px(11), 0, SizeUtils.dp2px(11), SizeUtils.dp2px(5.5f));
        mViewBinding.recyclerView.addItemDecoration(itemDecoration);
        mViewBinding.recyclerView.setLayoutManager(gridLayoutManager);
        mViewBinding.recyclerView.setAdapter(mAdapter);
        mAdapter.setOnItemClickListener((adapter, view, position) -> {
            SelectMyGroupBean.RowsBean item = (SelectMyGroupBean.RowsBean) adapter.getItem(position);
            ARouter.getInstance()
                    .build(RouterPath.WebCenter.ACTIVITY_HTML)
                    .withString(WebConstants.WEB_URL, WebConstants.TEACHER_VIDEO_DETAIL + "?groupId=" + item.id)
                    .navigation();
        });
    }


    /**
     * 刷新
     */
    private void refresh() {
        // 这里的作用是防止下拉刷新的时候还可以上拉加载
        mAdapter.getLoadMoreModule().setEnableLoadMore(false);
        // 下拉刷新，需要重置页数
        currentPage = 1;
        queryCourse(true);
    }

    private void loadMore() {
        currentPage++;
        queryCourse(false);
    }

    private void queryCourse(boolean isShowLoading) {
        //根据默认筛选条件查询
        LogUtils.i("pq", "currentSubjectId:" + currentSubjectId);
        LogUtils.i("pq", "currentPage:" + currentPage);
        presenter.queryVideoCourse(isShowLoading, UserHelper.getUserId(), currentSubjectId, currentPage);
    }

    private void checkHasNext(int dataSize) {
        hasNext = dataSize >= Constants.DEFAULT_DATA_SIZE;
    }


    @Override
    public void onGetVideoCourseSuccess(int page, SelectMyGroupBean liveCourseListBean) {
        if (isDetached()) {
            return;
        }
        if (liveCourseListBean != null) {
            mViewBinding.refreshLayout.finishRefresh();
            mAdapter.getLoadMoreModule().setEnableLoadMore(true);
            if (page == 1) {
                //第一页
                if (mAdapter != null) {
                    mAdapter.getData().clear();
                    mAdapter.notifyDataSetChanged();
                    if (liveCourseListBean.rows != null && liveCourseListBean.rows.size() > 0) {
                        checkHasNext(liveCourseListBean.rows.size());
                        mAdapter.setNewInstance(liveCourseListBean.rows);
                    } else {
                        showEmptyView();
                    }
                }
            } else {
                //加载更多
                if (mAdapter != null) {
                    if (liveCourseListBean.rows != null && liveCourseListBean.rows.size() > 0) {
                        checkHasNext(liveCourseListBean.rows.size());
                        mAdapter.addData(liveCourseListBean.rows);
                        mAdapter.getLoadMoreModule().loadMoreComplete();
                    } else {
                        mAdapter.getLoadMoreModule().loadMoreEnd();
                    }
                }
            }
        }
    }

    @Override
    public void onGetCourseError(int page) {
        if (isDetached()) {
            return;
        }
        if (page == 1) {
            mViewBinding.refreshLayout.finishRefresh();
        } else {
            if (mAdapter != null) {
                currentPage--;
                mAdapter.getLoadMoreModule().setEnableLoadMore(true);
                mAdapter.getLoadMoreModule().loadMoreFail();
            }
        }
    }

    public void querySubjectItemSuccess(List<QuerySubjectBean> data) {
        subjectBeanList.clear();
        subjectBeanList.add(new QuerySubjectBean("全部声部", 0));
        subjectBeanList.addAll(data);
    }

    private void showEmptyView() {
        if (mEmptyView == null) {
            mEmptyView = new EmptyViewLayout(getContext());
        }
        mEmptyView.setContent(com.cooleshow.base.R.drawable.icon_empty_course, "暂无课程~");
        mAdapter.setEmptyView(mEmptyView);
    }


    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.tv_subject) {
            if (subjectBeanList.size() == 0) {
                subjectBeanList.add(new QuerySubjectBean("全部声部", 0));
            }
            List<PopMenuBean> popList = new ArrayList<>();
            for (QuerySubjectBean bean : subjectBeanList) {
                PopMenuBean popMenuBean = new PopMenuBean();
                popMenuBean.setActionName(bean.name);
                popList.add(popMenuBean);
            }
            initCoursePop(mViewBinding.tvSubject, popList, position -> {
                QuerySubjectBean bean = subjectBeanList.get(position);
                currentSubjectId = bean.id;
                mViewBinding.tvSubject.setText(bean.name);
                queryCourse(true);
            });
        }
    }

    private void initCoursePop(View targetView, List<PopMenuBean> popList, PopupListWindow.PopupListListener listener) {
        PopupListWindow popWindow = new PopupListWindow(getContext());
        popWindow.showListPop(targetView, popList, position -> listener.onPopupListClick(position));
    }

    private void selectSubject() {
        if (subjectBeanList.size() == 0) {
            subjectBeanList.add(new QuerySubjectBean("全部声部", 0));
        }
        pvOptions = new OptionsPickerBuilder(getContext(), (options1, options2, options3, v) -> {
            currentSubjectId = subjectBeanList.get(options1).id;
            mViewBinding.tvSubject.setText(subjectBeanList.get(options1).name);
            queryCourse(true);
        }).setLayoutRes(R.layout.pickerview_address_layout, v -> {
            //自定义布局中的控件初始化及事件处理
            final TextView tvSubmit = (TextView) v.findViewById(com.cooleshow.base.R.id.tv_finish);
            TextView ivCancel = (TextView) v.findViewById(com.cooleshow.base.R.id.tv_cancel);
            tvSubmit.setOnClickListener(v12 -> {
                pvOptions.returnData();
                pvOptions.dismiss();
            });
            ivCancel.setOnClickListener(v1 -> pvOptions.dismiss());

        }).isDialog(false)
                .build();
        pvOptions.setPicker(subjectBeanList);
        pvOptions.show();
    }
}
