package com.cooleshow.teacher.ui.course;

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

import com.alibaba.android.arouter.launcher.ARouter;
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.PopupUtil;
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.teacher.R;
import com.cooleshow.teacher.adapter.CourseStatusFilterAdapter;
import com.cooleshow.teacher.adapter.VideoCourseListAdapter;
import com.cooleshow.teacher.bean.CourseFilterStatusBean;
import com.cooleshow.teacher.bean.QuerySubjectBean;
import com.cooleshow.teacher.bean.VideoCourseListBean;
import com.cooleshow.teacher.constants.CourseConstants;
import com.cooleshow.teacher.contract.VideoCourseContract;
import com.cooleshow.teacher.databinding.FragmentVideoCourseLayoutBinding;
import com.cooleshow.teacher.presenter.course.VideoCoursePresenter;
import com.cooleshow.teacher.widgets.VideoCourseListItemDecoration;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;

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

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 List<QuerySubjectBean> subjectBeanList = new ArrayList<>();
    private boolean hasNext = true;
    private boolean isFirstLoad = true;

    @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 refreshData() {
        super.refreshData();
        reBuildFilter();
        isFirstLoad = false;
    }

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

    private void buildDefaultCourseStatusFilterList() {
//        mCourseFilterStatusBeans = new ArrayList<>();
//        mCourseFilterStatusBeans.add(new CourseFilterStatusBean(CourseFilterConstants.COURSE_FILTER_ALL, "全部"));
//        mCourseFilterStatusBeans.add(new CourseFilterStatusBean(CourseFilterConstants.COURSE_FILTER_HAS_NOT_STARTED, "未开始"));
//        mCourseFilterStatusBeans.add(new CourseFilterStatusBean(CourseFilterConstants.COURSE_FILTER_IN_PROGRESS, "进行中"));
//        mCourseFilterStatusBeans.add(new CourseFilterStatusBean(CourseFilterConstants.COURSE_FILTER_COMPLETED, "已结束"));
    }

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


    @Override
    protected void initData() {
        mViewBinding.refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                refresh();
            }
        });

        mAdapter = new VideoCourseListAdapter();
        mAdapter.getLoadMoreModule().setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore() {
                //上拉加载
                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);
        buildDefaultCourseStatusFilterList();
        mAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                VideoCourseListBean.RowsBean item = (VideoCourseListBean.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, currentSubjectId, currentPage);
    }

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


    @Override
    public void onGetVideoCourseSuccess(int page, VideoCourseListBean 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();
            }
        }
    }

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

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

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