package com.casic.dcms.view.statistics;

import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.RadioGroup;

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

import com.casic.dcms.R;
import com.casic.dcms.adapter.NormalRecyclerAdapter;
import com.casic.dcms.databinding.ActivityGridAnalysisBinding;
import com.casic.dcms.model.GridAnalysisBean;
import com.casic.dcms.utils.ColorKit;
import com.casic.dcms.utils.LocaleConstant;
import com.casic.dcms.utils.TimeOrDateUtil;
import com.casic.dcms.utils.ViewGroupKit;
import com.casic.dcms.vm.DataAnalysisViewModel;
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.divider.RecyclerViewItemDivider;
import com.pengxh.androidx.lite.kit.LongKit;
import com.pengxh.androidx.lite.utils.LoadState;
import com.pengxh.androidx.lite.utils.LoadingDialog;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class GridAnalysisActivity extends AndroidxBaseActivity<ActivityGridAnalysisBinding> {

    private static final String TAG = "GridAnalysisActivity";
    private final Context context = GridAnalysisActivity.this;
    private DataAnalysisViewModel dataAnalysisViewModel;

    @Override
    protected void setupTopBarLayout() {
        ViewGroupKit.initImmersionBar(binding.rootView, this, true, R.color.white);

        binding.titleBarLayout.titleView.setText(LocaleConstant.ANALYSIS_ITEMS.get(4));
        binding.titleBarLayout.leftBackView.setOnClickListener(v -> finish());
    }

    @Override
    protected void initOnCreate(@Nullable Bundle savedInstanceState) {
        dataAnalysisViewModel = new ViewModelProvider(this).get(DataAnalysisViewModel.class);
        dataAnalysisViewModel.gridAnalysisData.observe(this, new Observer<GridAnalysisBean>() {
            @Override
            public void onChanged(GridAnalysisBean gridAnalysisBean) {
                if (gridAnalysisBean.getCode() == 200) {
                    List<GridAnalysisBean.DataModel> dataModels = gridAnalysisBean.getData();
                    int caseCount = 0;
                    List<GridAnalysisBean.DataModel> effectiveModels = new ArrayList<>();
                    for (GridAnalysisBean.DataModel dataModel : dataModels) {
                        caseCount += Integer.parseInt(dataModel.getRegisteredNum());
                        if (!dataModel.getRegisteredNum().equals("0")) {
                            effectiveModels.add(dataModel);
                        }
                    }
                    binding.caseCountView.setText("立案数：" + caseCount);

                    //按数量排序
                    Collections.sort(effectiveModels, new GridAnalysisComparator());

                    int finalCaseCount = caseCount;
                    NormalRecyclerAdapter<GridAnalysisBean.DataModel> recyclerAdapter = new NormalRecyclerAdapter<GridAnalysisBean.DataModel>(R.layout.item_grid_alanysis_rv_l, effectiveModels) {
                        @Override
                        public void convertView(ViewHolder viewHolder, int position, GridAnalysisBean.DataModel item) {
                            //设置随机颜色
                            int[] color = ColorKit.generateColor(context);

                            int rate = (int) ((Float.parseFloat(item.getRegisteredNum()) / finalCaseCount) * 100);

                            viewHolder.setText(R.id.numberTagView, String.valueOf(position + 1))
                                    .setBackgroundColor(R.id.numberTagView, color[0])
                                    .setTextColor(R.id.numberTagView, color[1])
                                    .setText(R.id.caseSourceView, item.getGridName())
                                    .setText(R.id.caseRateView, rate + "%");

                            ProgressBar progressBar = viewHolder.getView(R.id.frequencyProgressBar);
                            progressBar.setProgress(rate);
                        }
                    };
                    binding.gridAnalysisView.addItemDecoration(new RecyclerViewItemDivider(1, Color.LTGRAY));
                    binding.gridAnalysisView.setAdapter(recyclerAdapter);

                    //表格
                    NormalRecyclerAdapter<GridAnalysisBean.DataModel> gridAdapter = new NormalRecyclerAdapter<GridAnalysisBean.DataModel>(R.layout.item_grid_rv_l, effectiveModels) {
                        @Override
                        public void convertView(ViewHolder viewHolder, int position, GridAnalysisBean.DataModel item) {
                            viewHolder.setText(R.id.gridNameView, item.getGridName())
                                    .setText(R.id.registeredNumView, item.getRegisteredNum())
                                    .setText(R.id.distributeNumView, item.getDistributeNum())
                                    .setText(R.id.processNumView, item.getProcessNum())
                                    .setText(R.id.closedNumView, item.getClosedNum());
                        }
                    };
                    binding.caseRecyclerView.addItemDecoration(new RecyclerViewItemDivider(1, Color.LTGRAY));
                    binding.caseRecyclerView.setAdapter(gridAdapter);
                }
            }
        });
    }

    @Override
    protected void observeRequestState() {
        dataAnalysisViewModel.loadState.observe(this, new Observer<LoadState>() {
            @Override
            public void onChanged(LoadState loadState) {
                if (loadState == LoadState.Loading) {
                    LoadingDialog.show(GridAnalysisActivity.this, "数据加载中，请稍后");
                } else {
                    LoadingDialog.dismiss();
                }
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        //默认加载当前时间往前一个月的
        dataAnalysisViewModel.getGridAnalysis(this, TimeOrDateUtil.getOneMonthDate(), LongKit.timestampToDate(System.currentTimeMillis()));
    }

    @Override
    protected void initEvent() {
        binding.selectCalendarButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new RangeDateActionSheet.Builder().setContext(context).setOnActionSheetListener(new RangeDateActionSheet.OnDateRangeSelectedListener() {
                    @Override
                    public void onDateRangeSelected(String startDate, String endDate) {
                        dataAnalysisViewModel.getGridAnalysis(context, startDate, endDate);
                    }
                }).build().show();
            }
        });

        binding.radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if (checkedId == R.id.oneMonthRadioButton) {
                    dataAnalysisViewModel.getGridAnalysis(context, TimeOrDateUtil.getOneMonthDate(), LongKit.timestampToDate(System.currentTimeMillis()));
                } else if (checkedId == R.id.threeMonthRadioButton) {
                    dataAnalysisViewModel.getGridAnalysis(context, TimeOrDateUtil.getThreeMonthDate(), LongKit.timestampToDate(System.currentTimeMillis()));
                } else {
                    dataAnalysisViewModel.getGridAnalysis(context, TimeOrDateUtil.getSixMonthDate(), LongKit.timestampToDate(System.currentTimeMillis()));
                }
            }
        });
    }

    private static class GridAnalysisComparator implements Comparator<GridAnalysisBean.DataModel> {

        @Override
        public int compare(GridAnalysisBean.DataModel o1, GridAnalysisBean.DataModel o2) {
            int i = Integer.parseInt(o1.getRegisteredNum());
            int j = Integer.parseInt(o2.getRegisteredNum());
            return j - i;
        }
    }
}
