package com.cooleshow.teacher.ui.work;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import io.rong.imkit.utils.helper.OpenChatHelper;

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.OnItemChildClickListener;
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.teacher.R;
import com.cooleshow.teacher.adapter.HomeworkAdapter;
import com.cooleshow.teacher.bean.HomeworkListBean;
import com.cooleshow.teacher.constants.CourseConstants;
import com.cooleshow.teacher.constants.TeacherConfig;
import com.cooleshow.teacher.contract.HomeWorkContract;
import com.cooleshow.teacher.databinding.FragmentHomeworkBinding;
import com.cooleshow.teacher.presenter.homework.HomeWorkPresenter;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * 创建日期：2022/5/23 10:54
 *
 * @author Ryan
 * 类说明：
 */
public class HomeWorkFragment extends BaseMVPFragment<FragmentHomeworkBinding, HomeWorkPresenter> implements HomeWorkContract.HomeWorkView, View.OnClickListener {
    private int currentPage;
    private String decorate = "";
    private HomeworkAdapter homeworkAdapter;
    private boolean hasNext = true;
    private TimePickerView pvTime;
    private Date currentSelectDate;
    private String currentFilterDate;

    public static HomeWorkFragment newInstance(String decorate) {
        Bundle args = new Bundle();
        HomeWorkFragment fragment = new HomeWorkFragment();
        args.putString("decorate", decorate);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_date:
                showTimeSelectPicker();
                break;
        }
    }

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

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

    @Override
    protected void initView(View rootView) {
        decorate = getArguments().getString("decorate");
        mViewBinding.tvDate.setOnClickListener(this);
        RecyclerView rvAddress = mViewBinding.recyclerView;
        LinearLayoutManager manager = new LinearLayoutManager(getContext());
        rvAddress.setLayoutManager(manager);
        homeworkAdapter = new HomeworkAdapter();
        homeworkAdapter.setDecorate(decorate);
        LayoutInflater inflater = LayoutInflater.from(getContext());
        View emptyLayout = inflater.inflate(R.layout.layout_empty_conent, null);
        homeworkAdapter.setEmptyView(emptyLayout);
        rvAddress.setAdapter(homeworkAdapter);
        homeworkAdapter.setOnItemClickListener((adapter, view, position) -> {
            List<HomeworkListBean.RowsBean> data = (List<HomeworkListBean.RowsBean>) adapter.getData();
            HomeworkListBean.RowsBean rowsBean = data.get(position);
            if (rowsBean != null && TextUtils.equals(CourseConstants.PIANO_ROOM_COURSE, rowsBean.type)) {
                //琴房课
                ARouter.getInstance().build(RouterPath.CourseCenter.PIANO_ROOM_COURSE_DETAIL)
                        .withString("course_id", rowsBean.courseId)
                        .navigation();
            } else {
                //陪练课
                ARouter.getInstance().build(RouterPath.WorkCenter.TEACHER_WORK_ASSIGN_HOMEWORK)
                        .withString(TeacherConfig.COURSE_ID, rowsBean.courseId)
                        .withString(TeacherConfig.STUDENT_ID, rowsBean.studentId)
                        .navigation();
            }
        });

        homeworkAdapter.setOnItemChildClickListener(new OnItemChildClickListener() {
            @Override
            public void onItemChildClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                if (position >= homeworkAdapter.getData().size()) {
                    return;
                }
                HomeworkListBean.RowsBean rowsBean = homeworkAdapter.getData().get(position);
                if (TextUtils.equals(rowsBean.type, CourseConstants.OTHER_COURSE)) {
                    //陪练课
                    OpenChatHelper.goChat(getContext(), rowsBean.studentId, rowsBean.studentName);
                } else {
                    //琴房课或者直播课
                    OpenChatHelper.goGroupChat(getContext(), rowsBean.imGroupId, "");
                }
            }
        });
    }

    @Override
    protected void initData() {
        mViewBinding.refreshLayout.setOnRefreshListener(refreshLayout -> {
            currentPage = 1;
            queryCourse(true);
        });
        homeworkAdapter.getLoadMoreModule().setOnLoadMoreListener(() -> {
            //上拉加载
            if (hasNext) {
                currentPage++;
                queryCourse(false);
            } else {
                homeworkAdapter.getLoadMoreModule().loadMoreEnd();
            }
        });
        currentPage = 1;
        reBuildFilter(null);
    }


    @Override
    public void onResume() {
        super.onResume();
        queryCourse(true);
    }

    /**
     * 检查是否还有下一页
     *
     * @param dataSize
     */
    private void checkHasNext(int dataSize) {
        hasNext = dataSize >= Constants.DEFAULT_DATA_SIZE;
    }

    public void queryCourse(boolean isLoading) {
        presenter.queryHomeworkList(isLoading, currentPage, decorate, currentFilterDate);
    }

    @Override
    public void queryHomeworkListSuccess(int page, HomeworkListBean data) {
        if (isDetached()) {
            return;
        }
        if (data != null) {
            if (page == 1) {
                mViewBinding.refreshLayout.finishRefresh();
                homeworkAdapter.getData().clear();
                homeworkAdapter.notifyDataSetChanged();
                if (data.rows != null && data.rows.size() > 0) {
                    checkHasNext(data.rows.size());
                    homeworkAdapter.setNewInstance(data.rows);
                }
            } else {
                if (data.rows != null && data.rows.size() > 0) {
                    homeworkAdapter.getLoadMoreModule().loadMoreComplete();
                    homeworkAdapter.addData(data.rows);
                    checkHasNext(data.rows.size());
                } else {
                    homeworkAdapter.getLoadMoreModule().loadMoreEnd();
                }
            }
        }

    }

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


    private void showTimeSelectPicker() {
        if (pvTime == null) {
            pvTime = new TimePickerBuilder(requireContext(), (date, v) -> {//选中事件回调
                reBuildFilter(date);
                queryCourse(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();
        }
    }

    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.tvDate.setText(currentFilterDate);
    }
}
