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.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.ActivityHighEventBinding;
import com.casic.dcms.model.HighEventBean;
import com.casic.dcms.utils.ChartViewHelper;
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.github.mikephil.charting.data.PieEntry;
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.HashSet;
import java.util.List;

/**
 * @author Pengxh
 * @time : 2021/4/16 8:44
 * @email : 290677893@qq.com
 */
public class HighEventActivity extends AndroidxBaseActivity<ActivityHighEventBinding> {

    private static final String TAG = "HighEventListActivity";
    private final Context context = HighEventActivity.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(2));
        binding.titleBarLayout.leftBackView.setOnClickListener(v -> finish());
    }

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

    @Override
    protected void initOnCreate(@Nullable Bundle savedInstanceState) {
        dataAnalysisViewModel = new ViewModelProvider(this).get(DataAnalysisViewModel.class);
        dataAnalysisViewModel.highEventModel.observe(this, new Observer<HighEventBean>() {
            @Override
            public void onChanged(HighEventBean resultBean) {
                if (resultBean.getCode() == 200) {
                    int caseCount = 0;
                    List<HighEventBean.DataModel> dataModels = resultBean.getData();
                    List<PieEntry> pieEntries = new ArrayList<>();
                    List<HighEventBean.DataModel> effectiveModels = new ArrayList<>();

                    for (HighEventBean.DataModel dataModel : dataModels) {
                        if (!dataModel.getCaseMajorType().equals("")) {
                            effectiveModels.add(dataModel);
                        } else {
                            caseCount = Integer.parseInt(dataModel.getCaseNum());
                        }
                    }
                    binding.caseCountView.setText("案卷数：" + caseCount);

                    //获取大类
                    HashSet<String> majorTypeSet = new HashSet<>();
                    for (HighEventBean.DataModel effectiveModel : effectiveModels) {
                        majorTypeSet.add(effectiveModel.getCaseMajorType());
                    }

                    //按大类重组数据
                    List<RegroupHighEventBean> regroupModels = new ArrayList<>();
                    for (String type : majorTypeSet) {
                        regroupModels.add(getEventByType(effectiveModels, type));
                    }

                    //按数量排序
                    Collections.sort(regroupModels, new RegroupHighEventComparator());

                    for (RegroupHighEventBean model : regroupModels) {
                        if (model.getCaseNum() != 0) {
                            pieEntries.add(new PieEntry(model.getCaseNum(), model.getCaseMajorType()));
                        }
                    }

                    //数据绑定饼图
                    ChartViewHelper.setPieChartData(binding.resourcePieChart, pieEntries);

                    //绑定列表
                    NormalRecyclerAdapter<RegroupHighEventBean> recyclerAdapter = new NormalRecyclerAdapter<RegroupHighEventBean>(R.layout.item_case_resource_lv_l, regroupModels) {
                        @Override
                        public void convertView(ViewHolder viewHolder, int position, RegroupHighEventBean item) {
                            //设置随机颜色
                            int[] color = ColorKit.generateColor(context);

                            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.getCaseMajorType())
                                    .setText(R.id.caseNumView, String.valueOf(item.getCaseNum()));
                        }
                    };
                    binding.highEventCaseView.addItemDecoration(new RecyclerViewItemDivider(1, Color.LTGRAY));
                    binding.highEventCaseView.setAdapter(recyclerAdapter);
                }
            }
        });
    }

    private RegroupHighEventBean getEventByType(List<HighEventBean.DataModel> effectiveModels, String type) {
        List<HighEventBean.DataModel> models = new ArrayList<>();
        for (HighEventBean.DataModel model : effectiveModels) {
            if (model.getCaseMajorType().equals(type)) {
                models.add(model);
            }
        }
        RegroupHighEventBean eventBean = new RegroupHighEventBean();
        eventBean.setCaseMajorType(type);
        int caseCount = 0;
        for (HighEventBean.DataModel model : models) {
            caseCount += Integer.parseInt(model.getCaseNum());
        }
        eventBean.setCaseNum(caseCount);
        return eventBean;
    }

    @Override
    protected void onResume() {
        super.onResume();
        //默认加载当前时间往前一个月的
        dataAnalysisViewModel.getHighFrequencyCase(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.getHighFrequencyCase(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.getHighFrequencyCase(context, TimeOrDateUtil.getOneMonthDate(), LongKit.timestampToDate(System.currentTimeMillis()));
                } else if (checkedId == R.id.threeMonthRadioButton) {
                    dataAnalysisViewModel.getHighFrequencyCase(context, TimeOrDateUtil.getThreeMonthDate(), LongKit.timestampToDate(System.currentTimeMillis()));
                } else {
                    dataAnalysisViewModel.getHighFrequencyCase(context, TimeOrDateUtil.getSixMonthDate(), LongKit.timestampToDate(System.currentTimeMillis()));
                }
            }
        });
    }

    //内部类
    private static class RegroupHighEventBean {
        private String caseMajorType;
        private int caseNum;

        public String getCaseMajorType() {
            return caseMajorType;
        }

        public void setCaseMajorType(String caseMajorType) {
            this.caseMajorType = caseMajorType;
        }

        public int getCaseNum() {
            return caseNum;
        }

        public void setCaseNum(int caseNum) {
            this.caseNum = caseNum;
        }
    }

    private static class RegroupHighEventComparator implements Comparator<RegroupHighEventBean> {
        @Override
        public int compare(RegroupHighEventBean o1, RegroupHighEventBean o2) {
            int i = o1.getCaseNum();
            int j = o2.getCaseNum();
            return j - i;
        }
    }
}