package com.cooleshow.teacher.ui.comment;

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

import com.alibaba.android.arouter.facade.annotation.Route;
import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.CustomListener;
import com.bigkoo.pickerview.view.TimePickerView;
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.activity.BaseMVPActivity;
import com.cooleshow.base.utils.TimeUtils;
import com.cooleshow.base.utils.helper.QMUIStatusBarHelper;
import com.cooleshow.base.widgets.EmptyViewLayout;
import com.cooleshow.teacher.R;
import com.cooleshow.teacher.adapter.ReceivedCommentListAdapter;
import com.cooleshow.teacher.bean.ReceivedCommentListBean;
import com.cooleshow.teacher.contract.ReceivedCommentContract;
import com.cooleshow.teacher.databinding.ActivityReceivedCommentLayoutBinding;
import com.cooleshow.teacher.presenter.comment.ReceivedCommentPresenter;
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.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;

/**
 * Author by pq, Date on 2022/5/5.
 */
@Route(path = RouterPath.CommentCenter.TEACHER_RECEIVED_COMMENT)
public class ReceivedCommentActivity extends BaseMVPActivity<ActivityReceivedCommentLayoutBinding, ReceivedCommentPresenter> implements ReceivedCommentContract.ReceivedCommentView, View.OnClickListener {
    private TimePickerView pvTime;
    private Date currentSelectDate;
    private String currentFilterDate;
    private String currentStudentName;
    private int currentPage = 1;
    private ReceivedCommentListAdapter mListAdapter;
    private EmptyViewLayout mEmptyView;
    private TextView mTvEmptyTip;
    private ImageView mEmptyIcon;
    private boolean hasNext = true;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        QMUIStatusBarHelper.setStatusBarLightMode(this);
    }

    @Override
    protected void initView() {

    }

    @Override
    public void initData() {
        super.initData();
        initMidTitleToolBar(viewBinding.toolbarInclude.toolbar, "我收到的评价");
        currentSelectDate = TimeUtils.getNowDate();
        mListAdapter = new ReceivedCommentListAdapter(R.layout.item_received_comment_layout);
        viewBinding.recyclerView.setLayoutManager(new LinearLayoutManager(this));
        viewBinding.recyclerView.setAdapter(mListAdapter);
        initListener();
        reBuildFilter(currentSelectDate, currentStudentName);
    }

    private void initListener() {
        viewBinding.tvDate.setOnClickListener(this);
        viewBinding.tvSearch.setOnClickListener(this);
        viewBinding.refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                currentPage = 1;
                queryComment(true);
            }
        });

        mListAdapter.getLoadMoreModule().setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore() {
                //上拉加载
                if (hasNext) {
                    currentPage++;
                    queryComment(false);
                } else {
                    mListAdapter.getLoadMoreModule().loadMoreEnd();
                }
            }
        });
    }

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


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

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

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

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

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


    /**
     * 显示时间选择器
     */
    private void showTimeSelectPicker() {
        if (pvTime == null) {
            pvTime = new TimePickerBuilder(this, (date, v) -> {//选中事件回调
                reBuildFilter(date, currentStudentName);
            }).setLayoutRes(com.cooleshow.base.R.layout.pickerview_default_layout, new CustomListener() {
                @Override
                public void customLayout(View 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(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            pvTime.returnData();
                            pvTime.dismiss();
                        }
                    });
                    ivCancel.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            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 queryCommentSuccess(int page, ReceivedCommentListBean commentListBean) {
        if (isDestroyed() || isFinishing()) {
            return;
        }
        if (commentListBean != null) {
            if (page == 1) {
                //第一页
                viewBinding.refreshLayout.finishRefresh();
                if (mListAdapter != null) {
                    mListAdapter.getData().clear();
                    mListAdapter.notifyDataSetChanged();
                    if (commentListBean.rows != null && commentListBean.rows.size() > 0) {
                        checkHasNext(commentListBean.rows.size());
                        mListAdapter.setNewInstance(commentListBean.rows);
                    } else {
                        showEmptyView();
                    }
                }
            } else {
                //加载更多
                if (mListAdapter != null) {
                    if (commentListBean.rows != null && commentListBean.rows.size() > 0) {
                        mListAdapter.getLoadMoreModule().loadMoreComplete();
                        checkHasNext(commentListBean.rows.size());
                        mListAdapter.addData(commentListBean.rows);
                    } else {
                        mListAdapter.getLoadMoreModule().loadMoreEnd();
                    }
                }
            }
        }
    }

    /**
     * 显示空视图
     */
    private void showEmptyView() {
        if (mEmptyView == null) {
            mEmptyView = new EmptyViewLayout(this);
        }
        mEmptyView.setContent(com.cooleshow.base.R.drawable.icon_empty_content, "暂无内容~");
        mListAdapter.setEmptyView(mEmptyView);
    }

    /**
     * 查询列表数据失败
     *
     * @param page
     */
    @Override
    public void queryCommentError(int page) {
        if (isFinishing() || isDestroyed()) {
            return;
        }
        if (page == 1) {
            viewBinding.refreshLayout.finishRefresh();
        } else {
            if (mListAdapter != null) {
                currentPage--;
                mListAdapter.getLoadMoreModule().loadMoreFail();
            }
        }
    }

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