package com.cooleshow.teacher.ui.comment;

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

import com.alibaba.android.arouter.launcher.ARouter;
import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.CustomListener;
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.constanst.Constants;
import com.cooleshow.base.router.RouterPath;
import com.cooleshow.base.ui.fragment.BaseMVPFragment;
import com.cooleshow.base.utils.TimeUtils;
import com.cooleshow.base.widgets.EmptyViewLayout;
import com.cooleshow.teacher.R;
import com.cooleshow.teacher.adapter.CourseCommentNotReplyAdapter;
import com.cooleshow.teacher.bean.CourseCommentListBean;
import com.cooleshow.teacher.contract.CourseCommentContract;
import com.cooleshow.teacher.databinding.FragmentCourseCommentNoReplyLayoutBinding;
import com.cooleshow.teacher.presenter.comment.CourseCommentPresenter;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;

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

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

/**
 * Author by pq, Date on 2022/5/5.
 * 陪练课评价-已评价学生
 */
public class CourseCommentHasReplyFragment extends BaseMVPFragment<FragmentCourseCommentNoReplyLayoutBinding, CourseCommentPresenter> implements CourseCommentContract.CourseCommentView, View.OnClickListener {
    public int courseCommentNotReply = 1;//已评价学生
    private TimePickerView pvTime;
    private Date currentSelectDate;
    private String currentFilterDate;
    private String currentStudentName;
    private int currentPage = 1;
    private EmptyViewLayout mEmptyView;
    private boolean hasNext = true;
    private CourseCommentNotReplyAdapter mAdapter;

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

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

    @Override
    protected void initView(View rootView) {

    }

    @Override
    protected void initData() {
        currentSelectDate = TimeUtils.getNowDate();
        mAdapter = new CourseCommentNotReplyAdapter(R.layout.item_course_comment_list_layout);
        mViewBinding.recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        mViewBinding.recyclerView.setAdapter(mAdapter);
        initListener();
        reBuildFilter(currentSelectDate, currentStudentName);
    }

    @Override
    public void onResume() {
        super.onResume();
        currentPage = 1;
        queryComment(false);
    }

    private void initListener() {
        mViewBinding.tvDate.setOnClickListener(this);
        mViewBinding.tvSearch.setOnClickListener(this);
        mViewBinding.refreshLayout.setOnRefreshListener(refreshLayout -> {
            currentPage = 1;
            queryComment(true);
        });

        mAdapter.setOnItemClickListener((adapter, view, position) -> {
            if (position < mAdapter.getData().size()) {
                CourseCommentListBean.RowsBean rowsBean = mAdapter.getData().get(position);
                startDetailActivity(rowsBean);
            }
        });

        mAdapter.getLoadMoreModule().setOnLoadMoreListener(() -> {
            //上拉加载
            if (hasNext) {
                currentPage++;
                queryComment(false);
            } else {
                mAdapter.getLoadMoreModule().loadMoreEnd();
            }
        });
    }

    private void startDetailActivity(CourseCommentListBean.RowsBean rowsBean) {
        if (rowsBean == null) {
            return;
        }
        ARouter.getInstance()
                .build(RouterPath.CommentCenter.TEACHER_COURSE_COMMENT_DETAIL)
                .withString(CourseCommentDetailActivity.COURSE_ID, rowsBean.courseId)
                .withString(CourseCommentDetailActivity.COURSE_GROUP_ID, rowsBean.courseGoupId)
                .withString(CourseCommentDetailActivity.STUDENT_ID, rowsBean.userId)
                .navigation();

    }

    /**
     * 构造筛选条件
     *
     * @param date
     * @param targetStr
     */
    private void reBuildFilter(Date date, String targetStr) {
        currentSelectDate = date != null ? date : TimeUtils.getNowDate();
        String targetDateTimeStr = TimeUtils.date2String(currentSelectDate, TimeUtils.getSafeDateFormat("yyyy-MM"));
        if (TextUtils.equals(targetDateTimeStr, currentFilterDate) && TextUtils.equals(targetStr, currentStudentName)) {
            //防止重复条件触发
            return;
        }
        currentStudentName = targetStr;
        currentFilterDate = targetDateTimeStr;
        mViewBinding.tvDate.setText(currentFilterDate);
    }

    private void queryComment(boolean isShowLoading) {
        presenter.queryCourseCommentList(isShowLoading, courseCommentNotReply, currentFilterDate, currentStudentName, currentPage);
    }


    /**
     * 显示时间选择器
     */
    private void showTimeSelectPicker() {
        if (pvTime == null) {
            pvTime = new TimePickerBuilder(requireContext(), (date, v) -> {//选中事件回调
                reBuildFilter(date, currentStudentName);
                currentPage = 1;
                queryComment(true);
            }).setLayoutRes(com.cooleshow.base.R.layout.pickerview_default_layout, v -> {
                //自定义布局中的控件初始化及事件处理
                final TextView tvSubmit =  v.findViewById(com.cooleshow.base.R.id.tv_finish);
                TextView ivCancel =  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();
        }
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.tv_date) {
            //显示时间选择器
            showTimeSelectPicker();
            return;
        }

        if (v.getId() == R.id.tv_search) {
            //搜索
            String targetName = mViewBinding.etTargetName.getText().toString();
            reBuildFilter(currentSelectDate, targetName);
            currentPage = 1;
            queryComment(true);
        }
    }

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

    /**
     * 检查是否还有下一页
     *
     * @param dataSize
     */
    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_content, "暂无内容~");
        mAdapter.setEmptyView(mEmptyView);
    }

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