package com.cooleshow.teacher.ui.course;

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

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.constanst.Constanst;
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.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.VideoCourseListBean;
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;

/**
 * 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 View mEmptyView;
    private TextView mTvEmptyTip;
    private PopupWindow mPopupWindow;
    private CourseStatusFilterAdapter mCourseStatusFilterAdapter;
    private boolean hasNext = 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);
    }

    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(R.layout.item_video_course_list_layout);
        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();
        reBuildFilter();
    }


    /**
     * 刷新
     */
    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 >= Constanst.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 = getLayoutInflater().inflate(com.cooleshow.base.R.layout.empty_layout, mAdapter.getEmptyLayout(), false);
            mTvEmptyTip = mEmptyView.findViewById(com.cooleshow.base.R.id.tv_empty_tip);
        }
        mTvEmptyTip.setText("暂无数据");
        mAdapter.setEmptyView(mEmptyView);
    }


    private void initPopu(View targetView) {
        if (mPopupWindow == null) {
            View popupContentView = LayoutInflater.from(requireContext()).inflate(com.cooleshow.base.R.layout.list_popu_layout, null);
            RecyclerView recyclerView = popupContentView.findViewById(R.id.recyclerView);
            View bg = popupContentView.findViewById(com.cooleshow.base.R.id.view);
            bg.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (mPopupWindow != null) {
                        mPopupWindow.dismiss();
                    }
                }
            });
            mCourseStatusFilterAdapter = new CourseStatusFilterAdapter(com.cooleshow.base.R.layout.notice_popu_list_item);
            mCourseStatusFilterAdapter.setOnItemClickListener(new OnItemClickListener() {
                @Override
                public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                    Object object = mCourseStatusFilterAdapter.getData().get(position);
                    if (object instanceof CourseFilterStatusBean) {
                        if (mCourseStatusFilterAdapter != null) {
                            mCourseStatusFilterAdapter.setSelect(position);
                        }
                        CourseFilterStatusBean filterStatusBean = (CourseFilterStatusBean) object;
                        mViewBinding.tvSubject.setText(filterStatusBean.showText);
                        reBuildFilter();
                    }
                    mPopupWindow.dismiss();
                }
            });
            recyclerView.setLayoutManager(new LinearLayoutManager(requireContext()));
            recyclerView.setAdapter(mCourseStatusFilterAdapter);
//            mCourseStatusFilterAdapter.setNewInstance(mCourseFilterStatusBeans);
            mPopupWindow = PopupUtil.createNoBackPopupWindow(popupContentView, requireContext(), ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT, true);
        }
        mPopupWindow.showAsDropDown(targetView);
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.tv_course_status) {
            //课程状态筛选
            initPopu(mViewBinding.tvSubject);
            return;
        }
    }
}
