package com.cooleshow.teacher.ui.income;

import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.webkit.ValueCallback;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.CheckBox;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.CustomListener;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.TimePickerView;
import com.contrarywind.view.WheelView;
import com.cooleshow.base.router.RouterPath;
import com.cooleshow.base.ui.activity.BaseMVPActivity;
import com.cooleshow.base.utils.DateUtil;
import com.cooleshow.teacher.R;
import com.cooleshow.teacher.adapter.EarningDoughnutListAdapter;
import com.cooleshow.teacher.adapter.EarningStackedListAdapter;
import com.cooleshow.teacher.bean.AccountTotalBean;
import com.cooleshow.teacher.bean.EarningDoughnutChartBean;
import com.cooleshow.teacher.bean.EarningStackedLineBean;
import com.cooleshow.teacher.contract.EarningStatisticsContract;
import com.cooleshow.teacher.databinding.ActivityEarningStatisticsBinding;
import com.cooleshow.teacher.presenter.income.EarningStatisticsPresenter;
import com.cooleshow.teacher.widgets.LollipopFixedWebView;
import com.google.gson.Gson;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import io.rong.imkit.utils.StatusBarUtil;

/**
 * 创建日期：2022/6/1 17:58
 *
 * @author Ryan
 * 类说明：
 */
@Route(path = RouterPath.IncomeCenter.TEACHER_MINE_EARNING_STATISTICS)
public class EarningStatisticsActivity extends BaseMVPActivity<ActivityEarningStatisticsBinding, EarningStatisticsPresenter> implements EarningStatisticsContract.EarningStatisticsView, View.OnClickListener {
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        StatusBarUtil.setStatusBarDarkTheme(this, true);
        initViewState(savedInstanceState);
    }

    TextView tvAllEarnings;
    RecyclerView rvStacked;
    CheckBox cbScreen;
    FrameLayout viewParent;
    LinearLayout rlNetErrorRoot;
    FrameLayout doughnutParent;
    RecyclerView rvDoughnut;
    WebView webView;
    private String stackedData;
    private String doughnutData;
    private TimePickerView pvCustomLunar;
    private boolean isCheckMonth;
    private String monthStr;
    private String yearStr = DateUtil.getCurYearStr(null);
    private List<String> color = Arrays.asList("#01C1B5", "#5B8FF9", "#FFD02C", "#F97215", "#F85043");
    private EarningDoughnutListAdapter adapterDoughnut;
    private EarningStackedListAdapter adapterStacked;
    private WebView doughnutWebView;
    static final String YEAR_STR = "yearStr";
    static final String MONTH_STR = "monthStr";
    static final String IS_CHECK_MONTH = "isCheckMonth";

    @Override
    protected void initView() {

        initMidTitleToolBar(viewBinding.toolbarInclude.toolbar, "收入统计");
        tvAllEarnings=viewBinding.tvAllEarnings;
        rvStacked=viewBinding.rvStacked;
        cbScreen=viewBinding.cbScreen;
        viewParent=viewBinding.viewParent;
        rlNetErrorRoot=viewBinding.rlNetErrorRoot;
        doughnutParent=viewBinding.doughnutParent;
        rvDoughnut=viewBinding.rvDoughnut;
    }
    @Override
    public void onClick(View view) {

    }
    @Override
    protected ActivityEarningStatisticsBinding getLayoutView() {
        return ActivityEarningStatisticsBinding.inflate(getLayoutInflater());
    }

    @Override
    protected EarningStatisticsPresenter createPresenter() {
        return new EarningStatisticsPresenter();
    }

    @Override
    public void initData() {
        super.initData();
        getData(yearStr,"YEAR");
    }

    private void getData(String dataTime,String timeType){
        presenter.accountTotal(dataTime,timeType);
    }

    @Override
    public void onSaveInstanceState(Bundle savedInstanceState) {
        savedInstanceState.putString(YEAR_STR, yearStr);
        savedInstanceState.putString(MONTH_STR, monthStr);
        savedInstanceState.putBoolean(IS_CHECK_MONTH, isCheckMonth);
        super.onSaveInstanceState(savedInstanceState);
    }

    private void initViewState(Bundle savedInstanceState) {
        if (savedInstanceState != null) {
            yearStr = savedInstanceState.getString(YEAR_STR);
            monthStr = savedInstanceState.getString(MONTH_STR);
            isCheckMonth = savedInstanceState.getBoolean(IS_CHECK_MONTH);
            if (isCheckMonth) {
                cbScreen.setText(yearStr + "年" + monthStr + "月");
            } else {
                cbScreen.setText(yearStr + "年");
                monthStr = null;
            }
        } else {
            cbScreen.setText(yearStr + "年");
        }
        try {
            if (Build.VERSION.SDK_INT >= 21 && Build.VERSION.SDK_INT < 23) {
                webView = new LollipopFixedWebView(this);
            } else {
                webView = new WebView(this);
            }
        } catch (Exception e) {

        }
        try {
            if (Build.VERSION.SDK_INT >= 21 && Build.VERSION.SDK_INT < 23) {
                doughnutWebView = new LollipopFixedWebView(this);
            } else {
                doughnutWebView = new WebView(this);
            }
        } catch (Exception e) {

        }
        if (null == webView || null == doughnutWebView) {
            return;
        }

        viewParent.addView(webView, new FrameLayout.LayoutParams(
                FrameLayout.LayoutParams.MATCH_PARENT,
                FrameLayout.LayoutParams.MATCH_PARENT));

        doughnutParent.addView(doughnutWebView, new FrameLayout.LayoutParams(
                FrameLayout.LayoutParams.MATCH_PARENT,
                FrameLayout.LayoutParams.MATCH_PARENT));
        initWebView();

        cbScreen.setOnClickListener(v -> {
            initLunarPicker();
        });
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this) {
            @Override
            public boolean canScrollVertically() {
                return false;
            }
        };
        rvDoughnut.setLayoutManager(linearLayoutManager);
        adapterDoughnut = new EarningDoughnutListAdapter(this);
        rvDoughnut.setAdapter(adapterDoughnut);

        GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 4) {
            @Override
            public boolean canScrollVertically() {
                return false;
            }
        };
        rvStacked.setLayoutManager(gridLayoutManager);
        adapterStacked = new EarningStackedListAdapter(this);
        rvStacked.setAdapter(adapterStacked);
    }

    private void initWebView() {

        //声明WebSettings子类
        WebSettings webSettings = webView.getSettings();
        webSettings.setGeolocationDatabasePath(getApplicationContext().getFilesDir().getPath());
        webSettings.setGeolocationEnabled(true);
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
        //如果访问的页面中要与Javascript交互，则webview必须设置支持Javascript
        webSettings.setJavaScriptEnabled(true);

        //设置自适应屏幕，两者合用
        webSettings.setUseWideViewPort(true); //将图片调整到适合webview的大小
        webSettings.setLoadWithOverviewMode(true); // 缩放至屏幕的大小
        //缩放操作
        webSettings.setSupportZoom(false); //支持缩放，默认为true。是下面那个的前提。


        webSettings.setLoadsImagesAutomatically(true); //支持自动加载图片
        webSettings.setDefaultTextEncodingName("UTF-8");//设置编码格式


        webSettings.setTextZoom(100);//设置字体默认的缩放比例，以避免手机系统的字体修改对页面字体及布局造成影响。
        webView.setHorizontalScrollBarEnabled(false);
        webView.setVerticalScrollBarEnabled(false);
        webView.setWebViewClient(new WebViewClient() {
                                     //页面开始载入时调用

                                     @Override
                                     public void onPageStarted(WebView view, String url, Bitmap favicon) {
                                         super.onPageStarted(view, url, favicon);

                                     }

                                     //页面载入结束时调用
                                     @Override
                                     public void onPageFinished(WebView view, String url) {
                                         super.onPageFinished(view, url);
                                         if (!TextUtils.isEmpty(stackedData) && !isLoadFished) {
                                             webView.evaluateJavascript("loadEcharts('" + stackedData + "')", new ValueCallback<String>() {
                                                 @Override
                                                 public void onReceiveValue(String s) {
                                                 }
                                             });
                                         }
                                         isLoadFished = true;
                                     }

                                     //处理报错信息
                                     @Override
                                     public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
                                         super.onReceivedError(view, request, error);
                                     }
                                 }
        );
        webView.loadUrl("file:///android_asset/stacked_line_chart.html");


        //声明WebSettings子类
        WebSettings doughnutWebSettings = doughnutWebView.getSettings();
        doughnutWebSettings.setGeolocationDatabasePath(getApplicationContext().getFilesDir().getPath());
        doughnutWebSettings.setGeolocationEnabled(true);
        doughnutWebSettings.setJavaScriptCanOpenWindowsAutomatically(true);
        //如果访问的页面中要与Javascript交互，则webview必须设置支持Javascript
        doughnutWebSettings.setJavaScriptEnabled(true);
        //设置自适应屏幕，两者合用
        doughnutWebSettings.setUseWideViewPort(true); //将图片调整到适合webview的大小
        doughnutWebSettings.setLoadWithOverviewMode(true); // 缩放至屏幕的大小
        //缩放操作
        doughnutWebSettings.setSupportZoom(false); //支持缩放，默认为true。是下面那个的前提。

        doughnutWebSettings.setLoadsImagesAutomatically(true); //支持自动加载图片
        doughnutWebSettings.setDefaultTextEncodingName("UTF-8");//设置编码格式
        doughnutWebSettings.setTextZoom(100);//设置字体默认的缩放比例，以避免手机系统的字体修改对页面字体及布局造成影响。
        doughnutWebView.setHorizontalScrollBarEnabled(false);
        doughnutWebView.setVerticalScrollBarEnabled(false);
        doughnutWebView.setWebViewClient(new WebViewClient() {
            //页面开始载入时调用

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);

            }

            //页面载入结束时调用
            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                if (!TextUtils.isEmpty(doughnutData) && !isDoughnutLoadFished) {
                    doughnutWebView.evaluateJavascript("loadEcharts('" + doughnutData + "')", new ValueCallback<String>() {
                        @Override
                        public void onReceiveValue(String s) {
                        }
                    });
                }
                isDoughnutLoadFished = true;
            }

            //处理报错信息
            @Override
            public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
                super.onReceivedError(view, request, error);
            }
        });
        doughnutWebView.loadUrl("file:///android_asset/stacked_line_chart.html");
    }
    boolean isLoadFished = false;
    boolean isDoughnutLoadFished = false;

    private WheelView month;

    private void initLunarPicker() {
        Calendar selectedDate = Calendar.getInstance();//系统当前时间
        Calendar startDate = Calendar.getInstance();
        startDate.set(2021, 2, 1);
        Calendar endDate = Calendar.getInstance();
        //时间选择器 ，自定义布局
        pvCustomLunar = new TimePickerBuilder(this, new OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {//选中事件回调
                if (isCheckMonth) {
                    yearStr = DateUtil.getCurYearStr(date);
                    monthStr = DateUtil.getCurMonthStr(date);
                    cbScreen.setText(yearStr + "年" + monthStr + "月");
                    getData(yearStr+"-"+monthStr,"MONTH");
                } else {
                    yearStr = DateUtil.getCurYearStr(date);
                    cbScreen.setText(yearStr + "年");
                    monthStr = null;
                    getData(yearStr,"YEAR");
                }
                cbScreen.setChecked(false);

            }
        })
                .setDate(selectedDate)
                .setRangDate(startDate, endDate)
                .setLayoutRes(R.layout.pickerview_year_month, new CustomListener() {


                    @Override
                    public void customLayout(final View v) {
                        final TextView tvSubmit = (TextView) v.findViewById(R.id.tv_finish);
                        TextView tvCancel = (TextView) v.findViewById(R.id.tv_cancel);
                        RadioGroup radiogroup = v.findViewById(R.id.radiogroup);
                        RadioButton rbMonth = v.findViewById(R.id.rb_month);
                        RadioButton rbYear = v.findViewById(R.id.rb_year);
                        month = (WheelView) v.findViewById(R.id.month);

                        tvSubmit.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                isCheckMonth = rbMonth.isChecked();
                                pvCustomLunar.returnData();
                                pvCustomLunar.dismiss();
                            }
                        });
                        tvCancel.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                pvCustomLunar.dismiss();
                            }
                        });

                        //公农历切换

                        if (isCheckMonth) {
                            rbMonth.setChecked(true);
                        } else {
                            rbYear.setChecked(true);
                        }
                        month.setVisibility(isCheckMonth ? View.VISIBLE :
                                View.GONE);
                        radiogroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
                            @Override
                            public void onCheckedChanged(RadioGroup group, int checkedId) {
                                month.setVisibility(checkedId == R.id.rb_month ? View.VISIBLE :
                                        View.GONE);
                            }
                        });

                    }


                })
                .setContentTextSize(18)
                .isCyclic(false)//是否循环滚动
                .setOutSideCancelable(true)//点击屏幕，点在控件外部范围时，是否取消显示
                .setBgColor(getResources().getColor(R.color.white))//滚轮背景颜色 Night mode
                .setTextColorCenter(getResources().getColor(com.cooleshow.base.R.color.color_1a1a1a))//设置选中项的颜色
                .setType(new boolean[]{true, false, false, false, false, false})
                .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                .setDividerColor(getResources().getColor(com.cooleshow.base.R.color.color_e2e2e2))
                .build();
        pvCustomLunar.show();
        if (month != null) {
            month.setVisibility(isCheckMonth ? View.VISIBLE :
                    View.GONE);
        }

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (null != webView) {
            webView.destroy();
        }
        if (null != doughnutWebView) {
            doughnutWebView.destroy();
        }

    }

    @Override
    public void accountTotalSuccess(AccountTotalBean data) {
        DecimalFormat df = new DecimalFormat("#,##0.00");
        tvAllEarnings.setText(df.format(data.totalInAmount));
        if (data.infoList == null || data.infoList.size() == 0) {
            rlNetErrorRoot.setVisibility(View.VISIBLE);
            viewParent.setVisibility(View.INVISIBLE);
            return;
        } else {
            rlNetErrorRoot.setVisibility(View.GONE);
            viewParent.setVisibility(View.VISIBLE);
        }
        EarningStackedLineBean bean = new EarningStackedLineBean();
        List<String> xAxisData = new ArrayList<>();

        for (AccountTotalBean accountTotalBean : data.infoList) {
            if (!isCheckMonth) {
                Date date = DateUtil.str2Date(accountTotalBean.timeStr,"yyyy-MM");
                xAxisData.add(DateUtil.getCurMonthStr(date) + "月");
            } else {
                Date date = DateUtil.str2Date(accountTotalBean.timeStr,"yyyy-MM-dd");
                xAxisData.add(DateUtil.getCurDayStr(date) + "日");
            }
        }
        EarningStackedLineBean.XAxisBean axisBean = new EarningStackedLineBean.XAxisBean();
        axisBean.setData(xAxisData);
        bean.setxAxis(axisBean);
        List<EarningStackedLineBean.SeriesBean> series = new ArrayList<>();
        List<EarningDoughnutChartBean.SeriesBean.DataBean> doughuntDataList = new ArrayList<>();
        EarningStackedLineBean.SeriesBean seriesPBean = new EarningStackedLineBean.SeriesBean();
        seriesPBean.setName("陪练课");
        seriesPBean.setData(new ArrayList<>());
        EarningStackedLineBean.SeriesBean seriesLBean = new EarningStackedLineBean.SeriesBean();
        seriesLBean.setName("直播课");
        seriesLBean.setData(new ArrayList<>());
        EarningStackedLineBean.SeriesBean seriesVBean = new EarningStackedLineBean.SeriesBean();
        seriesVBean.setName("视频课");
        seriesVBean.setData(new ArrayList<>());
        EarningStackedLineBean.SeriesBean seriesMBean = new EarningStackedLineBean.SeriesBean();
        seriesMBean.setName("乐谱");
        seriesMBean.setData(new ArrayList<>());

        for (AccountTotalBean beanX : data.infoList) {
            seriesPBean.getData().add(beanX.practiceAmount);
            seriesLBean.getData().add(beanX.liveAmount);
            seriesVBean.getData().add(beanX.videoAmount);
            seriesMBean.getData().add(beanX.musicAmount);
        }
        series.add(seriesPBean);
        series.add(seriesLBean);
        series.add(seriesVBean);
        series.add(seriesMBean);
        doughuntDataList.add(new EarningDoughnutChartBean.SeriesBean.DataBean(data.practiceAmount, "陪练课"));
        doughuntDataList.add(new EarningDoughnutChartBean.SeriesBean.DataBean(data.liveAmount, "直播课"));
        doughuntDataList.add(new EarningDoughnutChartBean.SeriesBean.DataBean(data.videoAmount, "视频课"));
        doughuntDataList.add(new EarningDoughnutChartBean.SeriesBean.DataBean(data.musicAmount, "乐谱"));

        bean.setColor(color);
        bean.setSeries(series);
        bean.getDataZoom().get(0).setThrottle(series.size() > 15 ? 50 : 100);
        stackedData = new Gson().toJson(bean);
        adapterStacked.setData(doughuntDataList, data.totalInAmount, color);
        if (isLoadFished) {
            webView.evaluateJavascript("loadEcharts('" + stackedData + "')", new ValueCallback<String>() {
                @Override
                public void onReceiveValue(String s) {
                }
            });
        }

        EarningDoughnutChartBean earningDoughnutChartBean = new EarningDoughnutChartBean();
        earningDoughnutChartBean.setColor(color);
        EarningDoughnutChartBean.SeriesBean doughnutSeriesBean = new EarningDoughnutChartBean.SeriesBean();
        doughnutSeriesBean.setData(doughuntDataList);
        List<EarningDoughnutChartBean.SeriesBean> earningDoughnutSeriesDataList = new ArrayList<EarningDoughnutChartBean.SeriesBean>();
        earningDoughnutSeriesDataList.add(doughnutSeriesBean);
        earningDoughnutChartBean.setSeries(earningDoughnutSeriesDataList);
        doughnutData = new Gson().toJson(earningDoughnutChartBean);

        if (isDoughnutLoadFished) {
            doughnutWebView.evaluateJavascript("loadEcharts('" + doughnutData + "')", new ValueCallback<String>() {
                @Override
                public void onReceiveValue(String s) {
                }
            });
        }
        adapterDoughnut.setData(doughuntDataList, data.totalInAmount, color);

    }
}
