package com.casic.dcms.view.toilet;

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

import androidx.annotation.NonNull;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;

import com.amap.api.services.core.LatLonPoint;
import com.casic.dcms.R;
import com.casic.dcms.databinding.ActivityCleanRecordsBinding;
import com.casic.dcms.model.CleanRecordBean;
import com.casic.dcms.utils.DialogHelper;
import com.casic.dcms.utils.LocationHelper;
import com.casic.dcms.utils.StringHelper;
import com.casic.dcms.utils.callback.IAddressListener;
import com.casic.dcms.view.BigImageActivity;
import com.casic.dcms.view.map.WorkerOnMapActivity;
import com.casic.dcms.vm.ToiletViewModel;
import com.casic.dcms.widgets.RangeDateActionSheet;
import com.gyf.immersionbar.ImmersionBar;
import com.pengxh.androidx.lite.adapter.NormalRecyclerAdapter;
import com.pengxh.androidx.lite.adapter.ViewHolder;
import com.pengxh.androidx.lite.base.AndroidxBaseActivity;
import com.pengxh.androidx.lite.hub.ContextHub;
import com.pengxh.androidx.lite.hub.IntHub;
import com.pengxh.androidx.lite.hub.StringHub;
import com.pengxh.androidx.lite.utils.ImmerseStatusBarManager;
import com.pengxh.androidx.lite.utils.WeakReferenceHandler;
import com.pengxh.androidx.lite.vm.LoadState;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.util.ArrayList;
import java.util.List;

public class CleaningRecordsActivity extends AndroidxBaseActivity<ActivityCleanRecordsBinding> {

    private final Context context = CleaningRecordsActivity.this;
    private ToiletViewModel toiletViewModel;
    private List<CleanRecordBean.DataBean.RowsBean> dataBeans = new ArrayList<>();
    private NormalRecyclerAdapter<CleanRecordBean.DataBean.RowsBean> adapter;
    private WeakReferenceHandler weakReferenceHandler;
    private int pageIndex = 1;
    private boolean isRefresh = false;
    private boolean isLoadMore = false;

    @Override
    protected void setupTopBarLayout() {
        ImmerseStatusBarManager.setColor(this, IntHub.convertColor(this, R.color.white));
        ImmersionBar.with(this).statusBarDarkFont(true).init();

        viewBinding.titleBarLayout.titleView.setText("保洁作业记录");
        viewBinding.titleBarLayout.leftBackView.setOnClickListener(v -> finish());
    }

    @Override
    protected void initData() {
        weakReferenceHandler = new WeakReferenceHandler(callback);
        toiletViewModel = new ViewModelProvider(this).get(ToiletViewModel.class);
        toiletViewModel.cleanRecordModel.observe(this, new Observer<CleanRecordBean>() {
            @Override
            public void onChanged(CleanRecordBean resultBean) {
                if (resultBean.getCode() == 200) {
                    List<CleanRecordBean.DataBean.RowsBean> dataRows = resultBean.getData().getRows();
                    if (isRefresh) {
                        adapter.setRefreshData(dataRows);
                        viewBinding.refreshLayout.finishRefresh();
                        isRefresh = false;
                    } else if (isLoadMore) {
                        if (dataRows.size() == 0) {
                            StringHub.show(context, "到底了，别拉了");
                        }
                        adapter.setLoadMoreData(dataRows);
                        viewBinding.refreshLayout.finishLoadMore();
                        isLoadMore = false;
                    } else {
                        dataBeans = dataRows;
                        weakReferenceHandler.sendEmptyMessage(20210601);
                    }
                }
            }
        });
    }

    @Override
    protected void observeRequestState() {
        toiletViewModel.loadState.observe(this, new Observer<LoadState>() {
            @Override
            public void onChanged(LoadState loadState) {
                if (loadState == LoadState.Loading) {
                    DialogHelper.showLoadingDialog(context, "查询记录中，请稍后");
                } else {
                    DialogHelper.dismissLoadingDialog();
                }
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        pageIndex = 1;
        obtainCleanRecordList("", "");
    }

    @Override
    protected void initEvent() {
        viewBinding.calendarView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                new RangeDateActionSheet.Builder().setContext(context).setOnActionSheetListener(new RangeDateActionSheet.OnDateRangeSelectedListener() {
                    @Override
                    public void onDateRangeSelected(String startDate, String endDate) {
                        viewBinding.dateView.setText(startDate + "~" + endDate);
                        obtainCleanRecordList(startDate, endDate);
                    }
                }).build().show();
            }
        });
        viewBinding.refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                isRefresh = true;
                //刷新之后页码重置
                pageIndex = 1;
                obtainCleanRecordList("", "");
            }
        });
        viewBinding.refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                isLoadMore = true;
                pageIndex++;
                obtainCleanRecordList("", "");
            }
        });
    }

    private void obtainCleanRecordList(String start, String end) {
        toiletViewModel.obtainCleanRecordList(StringHelper.getUserBean().getId(), "", start, end, pageIndex);
    }

    private final Handler.Callback callback = msg -> {
        if (msg.what == 20210601) {
            if (dataBeans.size() == 0) {
                viewBinding.emptyView.show(false, "抱歉，没有查到您的保洁工作记录", null, "刷新", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        pageIndex = 1;
                        obtainCleanRecordList("", "");
                    }
                });
            } else {
                viewBinding.emptyView.hide();
                adapter = new NormalRecyclerAdapter<CleanRecordBean.DataBean.RowsBean>(R.layout.item_record_rv_l, dataBeans) {
                    @Override
                    public void convertView(ViewHolder viewHolder, int position, CleanRecordBean.DataBean.RowsBean item) {
                        viewHolder.setText(R.id.toiletNameView, item.getToiletName().equals("") ? "未知" : item.getToiletName());
                        if (item.getPhoto().equals("")) {
                            viewHolder.setVisibility(R.id.descriptionImageView, View.GONE);
                        } else {
                            viewHolder.setVisibility(R.id.descriptionImageView, View.VISIBLE);
                            ArrayList<String> urls = new ArrayList<>();
                            urls.add(StringHelper.appendCompleteURL(item.getPhoto()));
                            viewHolder.setOnClickListener(R.id.descriptionImageView, new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    ContextHub.navigatePageTo(context, BigImageActivity.class, 0, urls);
                                }
                            });
                        }

                        String lng = item.getLng();
                        if (TextUtils.isEmpty(lng)) {
                            return;
                        }
                        String lat = item.getLat();
                        if (TextUtils.isEmpty(lat)) {
                            return;
                        }
                        LatLonPoint latLonPoint = new LatLonPoint(Double.parseDouble(lat), Double.parseDouble(lng));
                        LocationHelper.antiCodingLocation(context, latLonPoint, new IAddressListener() {
                            @Override
                            public void onGetAddress(String address) {
                                viewHolder.setText(R.id.workerPositionView, address);
                            }
                        });
                        viewHolder.setText(R.id.workTimeView, item.getCreateTime());
                    }
                };
                viewBinding.recordRecyclerView.setAdapter(adapter);
                adapter.setOnItemClickedListener(new NormalRecyclerAdapter.OnItemClickedListener<CleanRecordBean.DataBean.RowsBean>() {
                    @Override
                    public void onItemClicked(int position, CleanRecordBean.DataBean.RowsBean rowsBean) {
                        Intent intent = new Intent(context, 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)) {
                            StringHub.show(context, "经度异常");
                            return;
                        }
                        intent.putExtra("lng", Double.parseDouble(dataLng));
                        String dataLat = rowsBean.getLat();
                        if (TextUtils.isEmpty(dataLat)) {
                            StringHub.show(context, "经度异常");
                            return;
                        }
                        intent.putExtra("lat", Double.parseDouble(dataLat));
                        startActivity(intent);
                    }
                });
            }
        }
        return true;
    };
}