package com.cooleshow.teacher.ui.homepage;

import android.text.TextUtils;
import android.view.View;

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

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.utils.TimeUtils;
import com.cooleshow.base.widgets.EmptyViewLayout;
import com.cooleshow.teacher.R;
import com.cooleshow.teacher.adapter.LiveCourseListAdapter;
import com.cooleshow.teacher.adapter.MineLiveCourseListAdapter;
import com.cooleshow.teacher.bean.LiveCourseListBean;
import com.cooleshow.base.ui.fragment.BaseMVPFragment;
import com.cooleshow.teacher.bean.MineLiveCourseListBean;
import com.cooleshow.teacher.bean.TeacherUserInfo;
import com.cooleshow.teacher.constants.TeacherInfoConstants;
import com.cooleshow.teacher.contract.LiveCoursePageContract;
import com.cooleshow.teacher.databinding.FragmentLiveCoursePageLayoutBinding;
import com.cooleshow.teacher.presenter.homePage.LiveCoursePagePresenter;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;

import java.util.Date;

/**
 * Author by pq, Date on 2022/5/9.
 * 我的主页-直播课
 */
public class LiveCoursePageFragment extends BaseMVPFragment<FragmentLiveCoursePageLayoutBinding, LiveCoursePagePresenter> implements LiveCoursePageContract.LiveCoursePageView, View.OnClickListener {
    private int currentPage;
    private MineLiveCourseListAdapter mAdapter;
    private EmptyViewLayout mEmptyView;
    private boolean hasNext = true;
    private String currentFilterDate;

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

    @Override
    protected void initData() {
        Date currentSelectDate = TimeUtils.getNowDate();
        String targetDateTimeStr = TimeUtils.date2String(currentSelectDate, TimeUtils.getSafeDateFormat("yyyy-MM"));
        currentFilterDate = targetDateTimeStr;
        mViewBinding.refreshLayout.setOnRefreshListener(refreshLayout -> {
            currentPage = 1;
            queryCourse();
        });

        mAdapter = new MineLiveCourseListAdapter(R.layout.item_live_course_list_layout);
        mAdapter.getLoadMoreModule().setOnLoadMoreListener(() -> {
            //上拉加载
            if (hasNext) {
                currentPage++;
                queryCourse();
            } else {
                mAdapter.getLoadMoreModule().loadMoreEnd();
            }
        });
        mViewBinding.recyclerView.setLayoutManager(new LinearLayoutManager(requireContext()));
        mViewBinding.recyclerView.setAdapter(mAdapter);
        mAdapter.setOnItemClickListener((adapter, view, position) -> {
            MineLiveCourseListBean.RowsBean item =  mAdapter.getData().get(position);
            ARouter.getInstance()
                    .build(RouterPath.WebCenter.ACTIVITY_HTML)
                    .withString(WebConstants.WEB_URL, WebConstants.TEACHER_LIVE_DETAIL + "?groupId=" + item.courseGroupId)
                    .navigation();
        });

    }

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

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

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ll_create_live:
                ARouter.getInstance()
                        .build(RouterPath.WebCenter.ACTIVITY_HTML)
                        .withString(WebConstants.WEB_URL, WebConstants.TEACHER_LIVE_CREATE)
                        .navigation();
                break;
            case R.id.tv_open:
                if (mViewBinding.tvOpen.getText().toString().equals("去认证")) {
                    ARouter.getInstance().build(RouterPath.WebCenter.ACTIVITY_HTML)
                            .withString(WebConstants.WEB_URL, WebConstants.TEACHER_CERT)
                            .navigation();
                } else if (mViewBinding.tvOpen.getText().toString().equals("立即开通")) {
                    ARouter.getInstance()
                            .build(RouterPath.WebCenter.ACTIVITY_HTML)
                            .withString(WebConstants.WEB_URL, WebConstants.TEACHER_OPEN_LIVE)
                            .navigation();
                }

                break;
        }

    }

    @Override
    public void onResume() {
        super.onResume();
        presenter.getTeacherUserInfo();
    }

    private void queryCourse() {
        //根据默认筛选条件查询
        presenter.queryLiveCourse(currentFilterDate, currentPage);
    }

    @Override
    public void onGetLiveCourseSuccess(int page, MineLiveCourseListBean liveCourseListBean) {
        if (isDetached()) {
            return;
        }
        if (liveCourseListBean != null) {
            if (page == 1) {
                //第一页
                mViewBinding.refreshLayout.finishRefresh();
                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) {
                        mAdapter.getLoadMoreModule().loadMoreComplete();
                        checkHasNext(liveCourseListBean.rows.size());
                        mAdapter.addData(liveCourseListBean.rows);
                    } 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().loadMoreFail();
            }
        }
    }

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

    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 getTeacherInfoSuccess(TeacherUserInfo teacherUserInfo) {
        if (TextUtils.equals(teacherUserInfo.entryStatus, TeacherInfoConstants.ENTRY_STATUS_DOING)) {
            //入驻审核中
            mViewBinding.llContent.setVisibility(View.GONE);
            mViewBinding.clEmptyFlag.setVisibility(View.VISIBLE);
            mViewBinding.tvEmptyHint.setText("达人认证审核中！");
            mViewBinding.tvOpen.setVisibility(View.GONE);
        } else if (TextUtils.equals(teacherUserInfo.entryStatus, TeacherInfoConstants.ENTRY_STATUS_PASS)) {
            //入驻审核通过
            mViewBinding.llContent.setVisibility(View.VISIBLE);
            mViewBinding.clEmptyFlag.setVisibility(View.GONE);
            currentPage = 1;
            queryCourse();
        } else {
            //未通过或者未申请
            mViewBinding.llContent.setVisibility(View.GONE);
            mViewBinding.clEmptyFlag.setVisibility(View.VISIBLE);
            mViewBinding.tvEmptyHint.setText("您还没有完成达人认证\n认证后才可创建直播课哦~");
            mViewBinding.tvOpen.setVisibility(View.VISIBLE);
            mViewBinding.tvOpen.setText("去认证");
        }

    }
}
