package com.casic.dcms.ui;

import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;

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

import com.casic.dcms.adapter.RecordListAdapter;
import com.casic.dcms.base.AndroidxBaseActivity;
import com.casic.dcms.bean.CleanRecordBean;
import com.casic.dcms.databinding.ActivityCleanListBinding;
import com.casic.dcms.mvp.presenter.impl.CleanRecordPresenterImpl;
import com.casic.dcms.mvp.view.ICleanToiletRecordView;
import com.casic.dcms.utils.CalendarUtil;
import com.casic.dcms.utils.OtherUtils;
import com.casic.dcms.utils.StringHelper;
import com.casic.dcms.utils.ToastHelper;
import com.casic.dcms.widgets.datepicker.DatePopupWindow;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

public class CleanResultListActivity extends AndroidxBaseActivity<ActivityCleanListBinding> implements ICleanToiletRecordView {

    private final Context context = CleanResultListActivity.this;
    private CleanRecordPresenterImpl recordPresenter;
    private List<CleanRecordBean.DataBean.RowsBean> dataBeans = new ArrayList<>();
    private RecordListAdapter adapter;
    private WeakReferenceHandler weakReferenceHandler;
    private int pageIndex = 1;
    private boolean isRefresh = false;
    private boolean isLoadMore = false;
    private int startGroup = -1;
    private int endGroup = -1;
    private int startChild = -1;
    private int endChild = -1;

    @Override
    protected void setupTopBarLayout() {
        viewBinding.titleBarLayout.titleView.setText("保洁作业记录");
        viewBinding.titleBarLayout.leftBackView.setOnClickListener(v -> finish());
    }

    @Override
    protected void initData() {
        weakReferenceHandler = new WeakReferenceHandler(this);
        recordPresenter = new CleanRecordPresenterImpl(this);
        recordPresenter.onReadyRetrofitRequest(StringHelper.getUserBean().getId(), "", "", "", pageIndex);
    }

    @Override
    protected void initEvent() {
        viewBinding.calendarView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                new DatePopupWindow.Builder(CleanResultListActivity.this, CalendarUtil.obtainLastTwoMonth(), view)
                        .setInitSelect(startGroup, startChild, endGroup, endChild) //设置上一次选中的区间状态
                        .setInitDay(true) //默认为true，UI内容为共几天、开始、结束；当为false时,UI内容为共几晚、入住、离开
                        .setDateOnClickListener(new DatePopupWindow.DateOnClickListener() {
                            @Override
                            public void getDate(String startDate, String endDate, int startGroupPosition, int startChildPosition, int endGroupPosition, int endChildPosition) {
                                startGroup = startGroupPosition; //开始月份位置
                                startChild = startChildPosition; //开始对应月份中日的位置
                                endGroup = endGroupPosition; //结束月份位置
                                endChild = endChildPosition; //结束对应月份中日的位置
                                viewBinding.dateView.setText(startDate + "~" + endDate);
                                recordPresenter.onReadyRetrofitRequest(StringHelper.getUserBean().getId(),
                                        "", startDate, endDate, pageIndex);
                            }
                        }).builder();
            }
        });
        viewBinding.refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                isRefresh = true;
                //刷新之后页码重置
                pageIndex = 1;
                recordPresenter.onReadyRetrofitRequest(
                        StringHelper.getUserBean().getId(), "",
                        "", "", pageIndex
                );
            }
        });
        viewBinding.refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                isLoadMore = true;
                pageIndex++;
                recordPresenter.onReadyRetrofitRequest(
                        StringHelper.getUserBean().getId(), "",
                        "", "", pageIndex
                );
            }
        });
    }

    @Override
    public void obtainCleanRecordResult(CleanRecordBean resultBean) {
        if (resultBean.getCode() == 200) {
            List<CleanRecordBean.DataBean.RowsBean> dataRows = resultBean.getData().getRows();
            if (isRefresh) {
                dataBeans.clear(); //下拉刷新必须先清空之前的List，不然会出现数据重复的问题
                dataBeans = dataRows;
                viewBinding.refreshLayout.finishRefresh();
                isRefresh = false;
            } else if (isLoadMore) {
                if (dataRows.size() == 0) {
                    ToastHelper.showToast("到底了，别拉了", ToastHelper.INFO);
                }
                dataBeans.addAll(dataRows);
                viewBinding.refreshLayout.finishLoadMore();
                isLoadMore = false;
            } else {
                dataBeans = dataRows;
            }
            //更新RecyclerView
            weakReferenceHandler.sendEmptyMessage(20210601);
        }
    }

    @Override
    public void showProgress() {
        OtherUtils.showLoadingDialog(this, "查询记录中，请稍后");
    }

    @Override
    public void hideProgress() {
        OtherUtils.dismissLoadingDialog();
    }

    private static class WeakReferenceHandler extends Handler {

        private final WeakReference<CleanResultListActivity> reference;

        private WeakReferenceHandler(CleanResultListActivity activity) {
            reference = new WeakReference<>(activity);
        }

        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            CleanResultListActivity resultActivity = reference.get();
            if (msg.what == 20210601) {
                if (resultActivity.isRefresh || resultActivity.isLoadMore) {
                    resultActivity.adapter.notifyDataSetChanged();
                } else {
                    //首次加载数据
                    if (resultActivity.dataBeans.size() == 0) {
                        resultActivity.viewBinding.emptyView.show("抱歉，没有查到您的保洁工作记录", null);
                    } else {
                        resultActivity.viewBinding.emptyView.hide();
                        resultActivity.adapter = new RecordListAdapter(resultActivity, resultActivity.dataBeans);
                        resultActivity.viewBinding.recordRecyclerView.setLayoutManager(new LinearLayoutManager(resultActivity));
                        resultActivity.viewBinding.recordRecyclerView.addItemDecoration(new DividerItemDecoration(resultActivity, DividerItemDecoration.VERTICAL));
                        resultActivity.viewBinding.recordRecyclerView.setAdapter(resultActivity.adapter);
                        resultActivity.adapter.setOnItemClickListener(new RecordListAdapter.OnItemClickListener() {
                            @Override
                            public void onClick(int position) {
                                CleanRecordBean.DataBean.RowsBean rowsBean = resultActivity.dataBeans.get(position);
                                Intent intent = new Intent(resultActivity, WorkerOnMapActivity.class);
                                intent.putExtra("userName", rowsBean.getUserName());
                                intent.putExtra("createTime", rowsBean.getCreateTime());
                                intent.putExtra("toiletName", rowsBean.getToiletName());
                                String dataLng = rowsBean.getLng();
                                if (TextUtils.isEmpty(dataLng)) {
                                    ToastHelper.showToast("经度异常", ToastHelper.ERROR);
                                    return;
                                }
                                intent.putExtra("lng", Double.parseDouble(dataLng));
                                String dataLat = rowsBean.getLat();
                                if (TextUtils.isEmpty(dataLat)) {
                                    ToastHelper.showToast("纬度异常", ToastHelper.ERROR);
                                    return;
                                }
                                intent.putExtra("lat", Double.parseDouble(dataLat));
                                resultActivity.startActivity(intent);
                            }
                        });
                    }
                }
            }
        }
    }

    @Override
    protected void onDestroy() {
        recordPresenter.disposeRetrofitRequest();
        super.onDestroy();
    }
}