package com.cooleshow.teacher.ui.homepage;

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

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

import com.alibaba.android.arouter.launcher.ARouter;
import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.view.TimePickerView;
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.SparringCourseListAdapter;
import com.cooleshow.teacher.bean.SparringCourseListBean;
import com.cooleshow.teacher.bean.TeacherUserInfo;
import com.cooleshow.teacher.constants.CourseConstants;
import com.cooleshow.teacher.constants.TeacherInfoConstants;
import com.cooleshow.teacher.contract.SparringCoursePageContract;
import com.cooleshow.teacher.databinding.FragmentSparringCoursePageLayoutBinding;
import com.cooleshow.teacher.presenter.homePage.SparringCoursePagePresenter;
import com.cooleshow.teacher.ui.course.SparringCourseDetailActivity;
import com.cooleshow.base.ui.fragment.BaseMVPFragment;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;

import java.util.Calendar;
import java.util.Date;

/**
 * Author by pq, Date on 2022/5/9.
 * 个人主页-陪练课
 */
public class SparringCoursePageFragment extends BaseMVPFragment<FragmentSparringCoursePageLayoutBinding, SparringCoursePagePresenter> implements SparringCoursePageContract.SparringCoursePageView, View.OnClickListener {
    private int currentPage;
    private boolean hasNext = true;
    private SparringCourseListAdapter mAdapter;
    private EmptyViewLayout mEmptyView;
    private TimePickerView pvTime;
    private Date currentSelectDate;
    private String currentFilterDate;

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

    @Override
    protected void initData() {
        mViewBinding.refreshLayout.setOnRefreshListener(refreshLayout -> {
            currentPage = 1;
            queryCourse();
        });

        mAdapter = new SparringCourseListAdapter(R.layout.item_sparring_course_list_layout);
        mAdapter.getLoadMoreModule().setOnLoadMoreListener(() -> {
            //上拉加载
            if (hasNext) {
                currentPage++;
                queryCourse();
            } else {
                mAdapter.getLoadMoreModule().loadMoreEnd();
            }
        });
        mAdapter.setOnItemClickListener((adapter, view, position) -> {
            if (position < mAdapter.getData().size()) {
                SparringCourseListBean.RowsBean rowsBean = mAdapter.getData().get(position);
                if (rowsBean != null) {
                    ARouter.getInstance()
                            .build(RouterPath.CourseCenter.SPARRING_COURSE_DETAIL)
                            .withString(CourseConstants.COURSE_ID, rowsBean.courseId)
                            .withString(CourseConstants.COURSE_GROUP_ID, rowsBean.courseGoupId)
                            .withString(CourseConstants.STUDENT_ID, rowsBean.userId)
                            .navigation();
                }
            }
        });
        mViewBinding.recyclerView.setLayoutManager(new LinearLayoutManager(requireContext()));
        mViewBinding.recyclerView.setAdapter(mAdapter);

    }

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

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

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

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ll_practice_set:
                ARouter.getInstance()
                        .build(RouterPath.WebCenter.ACTIVITY_HTML)
                        .withString(WebConstants.WEB_URL, WebConstants.TEACHER_PRACTICE_SETTING)
                        .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;
            case R.id.tv_time:
                //时间筛选
                showTimeSelectPicker();
                break;
        }
    }

    private void showTimeSelectPicker() {
        if (pvTime == null) {
            pvTime = new TimePickerBuilder(requireContext(), (date, v) -> {//选中事件回调
                reBuildFilter(date);
            }).setLayoutRes(com.cooleshow.base.R.layout.pickerview_default_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(v1 -> {
                    pvTime.returnData();
                    pvTime.dismiss();
                });
                ivCancel.setOnClickListener(v12 -> pvTime.dismiss());

            })
                    .setLineSpacingMultiplier(2.5f)
                    .setType(new boolean[]{true, true, false, false, false, false})// 默认全部显示
                    .setTextColorCenter(getResources().getColor(com.cooleshow.base.R.color.color_1a1a1a))//设置选中项的颜色
                    .isDialog(false)//是否显示为对话框样式
                    .setLabel("年", "月", "", "", "", "")
                    .build();
        }
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(currentSelectDate);
        pvTime.setDate(calendar);
        if (!pvTime.isShowing()) {
            pvTime.show();
        }
    }

    private void reBuildFilter(Date date) {
        currentSelectDate = date != null ? date : TimeUtils.getNowDate();
        String targetDateTimeStr = TimeUtils.date2String(currentSelectDate, TimeUtils.getSafeDateFormat("yyyy-MM"));
        if (TextUtils.equals(targetDateTimeStr, currentFilterDate)) {
            //防止重复条件触发
            return;
        }
        currentFilterDate = targetDateTimeStr;
        currentPage = 1;
        mViewBinding.tvTime.setText(currentFilterDate);
        queryCourse();
    }

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

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

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

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

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

    @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;
            mViewBinding.tvTime.setVisibility(View.VISIBLE);
            reBuildFilter(null);
        } else {
            //未通过或者未申请
            mViewBinding.llContent.setVisibility(View.GONE);
            mViewBinding.clEmptyFlag.setVisibility(View.VISIBLE);
            mViewBinding.tvEmptyHint.setText("您还没有完成达人认证\n认证后才可创建直播课哦~");
            mViewBinding.tvOpen.setVisibility(View.VISIBLE);
            mViewBinding.tvOpen.setText("去认证");
        }

    }
}
