package com.casic.dcms.view.toilet;

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

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

import com.amap.api.services.core.LatLonPoint;
import com.casic.dcms.R;
import com.casic.dcms.adapter.NormalRecyclerAdapter;
import com.casic.dcms.databinding.ActivityCleanRecordsBinding;
import com.casic.dcms.model.CleanRecordBean;
import com.casic.dcms.utils.LocationHelper;
import com.casic.dcms.utils.StringHelper;
import com.casic.dcms.utils.ViewGroupKit;
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.pengxh.androidx.lite.adapter.ViewHolder;
import com.pengxh.androidx.lite.base.AndroidxBaseActivity;
import com.pengxh.androidx.lite.kit.ContextKit;
import com.pengxh.androidx.lite.kit.StringKit;
import com.pengxh.androidx.lite.utils.LoadState;
import com.pengxh.androidx.lite.utils.LoadingDialog;
import com.pengxh.androidx.lite.widget.TitleBarView;
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 = this;
    private ToiletViewModel toiletViewModel;
    private NormalRecyclerAdapter<CleanRecordBean.DataBean.RowsBean> adapter;
    private int page = 1;
    private boolean isRefresh = false;
    private boolean isLoadMore = false;

    @Override
    protected void setupTopBarLayout() {
        ViewGroupKit.initImmersionBar(binding.rootView, this, true, R.color.white);
        binding.titleView.setOnClickListener(new TitleBarView.OnClickListener() {
            @Override
            public void onLeftClick() {
                finish();
            }

            @Override
            public void onRightClick() {

            }
        });
    }

    @Override
    protected void initOnCreate(@Nullable Bundle savedInstanceState) {
        toiletViewModel = new ViewModelProvider(this).get(ToiletViewModel.class);
        toiletViewModel.cleanRecordModel.observe(this, new Observer<CleanRecordBean>() {
            @Override
            public void onChanged(CleanRecordBean resultBean) {
                if (resultBean.getCode() == 200) {
                    bindRecyclerView(resultBean);
                }
            }
        });
        getCleanRecordList("", "");
    }

    private void bindRecyclerView(CleanRecordBean resultBean) {
        List<CleanRecordBean.DataBean.RowsBean> dataRows = resultBean.getData().getRows();
        if (isRefresh) {
            binding.refreshLayout.finishRefresh();
            isRefresh = false;
            adapter.refresh(dataRows);
        } else if (isLoadMore) {
            binding.refreshLayout.finishLoadMore();
            isLoadMore = false;
            if (dataRows.size() == 0) {
                StringKit.show(context, "到底了，别拉了");
            }
            adapter.loadMore(dataRows);
        } else {
            if (dataRows.size() == 0) {
                binding.emptyView.show(null, "抱歉，没有查到您的保洁工作记录");
            } else {
                binding.emptyView.hide();
                adapter = new NormalRecyclerAdapter<CleanRecordBean.DataBean.RowsBean>(R.layout.item_record_rv_l, dataRows) {
                    @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) {
                                    ContextKit.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.get().antiCodingLocation(context, latLonPoint, new IAddressListener() {
                            @Override
                            public void onGetAddress(String address) {
                                viewHolder.setText(R.id.workerPositionView, address);
                            }
                        });
                        viewHolder.setText(R.id.workTimeView, item.getCreateTime());
                    }
                };
                binding.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)) {
                            StringKit.show(context, "经度异常");
                            return;
                        }
                        intent.putExtra("lng", Double.parseDouble(dataLng));
                        String dataLat = rowsBean.getLat();
                        if (TextUtils.isEmpty(dataLat)) {
                            StringKit.show(context, "经度异常");
                            return;
                        }
                        intent.putExtra("lat", Double.parseDouble(dataLat));
                        startActivity(intent);
                    }
                });
            }
        }
    }

    @Override
    protected void observeRequestState() {
        toiletViewModel.loadState.observe(this, new Observer<LoadState>() {
            @Override
            public void onChanged(LoadState loadState) {
                if (!isRefresh && !isLoadMore) {
                    if (loadState == LoadState.Loading) {
                        LoadingDialog.show(CleaningRecordsActivity.this, "查询记录中，请稍后");
                    } else {
                        LoadingDialog.dismiss();
                    }
                }
            }
        });
    }

    @Override
    protected void initEvent() {
        binding.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) {
                        binding.dateView.setText(startDate + "~" + endDate);
                        getCleanRecordList(startDate, endDate);
                    }
                }).build().show();
            }
        });
        binding.refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                isRefresh = true;
                //刷新之后页码重置
                page = 1;
                getCleanRecordList("", "");
            }
        });
        binding.refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                isLoadMore = true;
                page++;
                getCleanRecordList("", "");
            }
        });
    }

    private void getCleanRecordList(String start, String end) {
        toiletViewModel.getCleanRecordList(this, StringHelper.getUserBean().getId(), "", start, end, page);
    }
}