package com.gingersoft.gsa.cloud.main.mvp.ui.fragment;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.gingersoft.gsa.cloud.base.application.GsaCloudApplication;
import com.gingersoft.gsa.cloud.base.utils.MoneyUtil;
import com.gingersoft.gsa.cloud.base.utils.time.TimePickerUtils;
import com.gingersoft.gsa.cloud.base.utils.time.TimeUtils;
import com.gingersoft.gsa.cloud.base.utils.toast.ToastUtils;
import com.gingersoft.gsa.cloud.main.R;
import com.gingersoft.gsa.cloud.main.R2;
import com.gingersoft.gsa.cloud.main.di.component.DaggerSalesComponent;
import com.gingersoft.gsa.cloud.main.mvp.contract.SalesContract;
import com.gingersoft.gsa.cloud.main.mvp.model.bean.SalesFoodsBean;
import com.gingersoft.gsa.cloud.main.mvp.presenter.SalesPresenter;
import com.gingersoft.gsa.cloud.main.mvp.ui.adapter.FoodRankingAdapter;
import com.gingersoft.gsa.cloud.main.mvp.ui.adapter.SortNumberingAdapter;
import com.gingersoft.gsa.cloud.ui.view.TriangleView;
import com.github.mikephil.charting.charts.PieChart;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.PieData;
import com.github.mikephil.charting.data.PieDataSet;
import com.github.mikephil.charting.data.PieEntry;
import com.github.mikephil.charting.formatter.PercentFormatter;
import com.github.mikephil.charting.highlight.Highlight;
import com.github.mikephil.charting.listener.OnChartValueSelectedListener;
import com.github.mikephil.charting.utils.ColorTemplate;
import com.jess.arms.base.BaseFragment;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

import static com.jess.arms.utils.Preconditions.checkNotNull;
import static java.math.BigDecimal.ROUND_HALF_UP;


/**
 * ================================================
 * Description:
 * <p>
 * Created by MVPArmsTemplate on 02/23/2020 16:21
 * <a href="mailto:jess.yan.effort@gmail.com">Contact me</a>
 * <a href="https://github.com/JessYanCoding">Follow me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms">Star me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms/wiki">See me</a>
 * <a href="https://github.com/JessYanCoding/MVPArmsTemplate">模版请保持更新</a>
 * ================================================
 * 銷售分析報表
 */
public class SalesFragment extends BaseFragment<SalesPresenter> implements SalesContract.View, View.OnClickListener {
    @BindView(R2.id.report_sales_chart)
    PieChart salesChart;
    @BindView(R2.id.rv_sort_numbering)
    RecyclerView rvSortNumbering;
    private SortNumberingAdapter mSortNumberingAdapter;
    @BindView(R2.id.rv_restaurant)
    RecyclerView rvFoodRanking;
    private FoodRankingAdapter foodRankingAdapter;
    @BindView(R2.id.tv_start_time)
    TextView mTvStartTime;
    @BindView(R2.id.tv_end_time)
    TextView mTvEndTime;
    @BindView(R2.id.iv_sale_time_triangle)
    TriangleView triangleView;
    public static SalesFragment newInstance() {
        SalesFragment fragment = new SalesFragment();
        return fragment;
    }

    @Override
    public void setupFragmentComponent(@NonNull AppComponent appComponent) {
        DaggerSalesComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .view(this)
                .build()
                .inject(this);
    }

    @Override
    public View initView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_sales, container, false);
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        String startTime = TimeUtils.getOldDate(-2);
        mPresenter.getSalesReportInfo(GsaCloudApplication.getRestaurantId(mContext) + "", startTime);
        mTvStartTime.setText(startTime);
        mTvEndTime.setText(TimeUtils.getOldDate(0));
    }

    /**
     * 通过此方法可以使 Fragment 能够与外界做一些交互和通信, 比如说外部的 Activity 想让自己持有的某个 Fragment 对象执行一些方法,
     * 建议在有多个需要与外界交互的方法时, 统一传 {@link Message}, 通过 what 字段来区分不同的方法, 在 {@link #setData(Object)}
     * 方法中就可以 {@code switch} 做不同的操作, 这样就可以用统一的入口方法做多个不同的操作, 可以起到分发的作用
     * <p>
     * 调用此方法时请注意调用时 Fragment 的生命周期, 如果调用 {@link #setData(Object)} 方法时 {@link Fragment#onCreate(Bundle)} 还没执行
     * 但在 {@link #setData(Object)} 里却调用了 Presenter 的方法, 是会报空的, 因为 Dagger 注入是在 {@link Fragment#onCreate(Bundle)} 方法中执行的
     * 然后才创建的 Presenter, 如果要做一些初始化操作,可以不必让外部调用 {@link #setData(Object)}, 在 {@link #initData(Bundle)} 中初始化就可以了
     * <p>
     * Example usage:
     * <pre>
     * public void setData(@Nullable Object data) {
     *     if (data != null && data instanceof Message) {
     *         switch (((Message) data).what) {
     *             case 0:
     *                 loadData(((Message) data).arg1);
     *                 break;
     *             case 1:
     *                 refreshUI();
     *                 break;
     *             default:
     *                 //do something
     *                 break;
     *         }
     *     }
     * }
     *
     * // call setData(Object):
     * Message data = new Message();
     * data.what = 0;
     * data.arg1 = 1;
     * fragment.setData(data);
     * </pre>
     *
     * @param data 当不需要参数时 {@code data} 可以为 {@code null}
     */
    @Override
    public void setData(@Nullable Object data) {

    }

    @Override
    public void showLoading(String message) {

    }

    @Override
    public void hideLoading() {

    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
//        ArmsUtils.snackbarText(message);
        ToastUtils.show(mContext, message);
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {

    }


    private double totalAmount = 0;//所有菜品加起來的銷售額
    private int totalNum = 0;//所有菜品加起來的銷售數量

    @Override
    public void loadInfo(List<SalesFoodsBean.DataBean.SalesRankingBean> salesRanking) {
        totalAmount = 0;
        totalNum = 0;
        for (SalesFoodsBean.DataBean.SalesRankingBean salesRankingBean : salesRanking) {
            totalAmount = MoneyUtil.sum(totalAmount, salesRankingBean.getAmount());
            totalNum = totalNum + salesRankingBean.getNumber();
        }

        List<SalesFoodsBean.DataBean.SalesRankingBean> rankings = new ArrayList<>(salesRanking);
        rankings.add(0, new SalesFoodsBean.DataBean.SalesRankingBean());
        if (mSortNumberingAdapter == null) {
            //序號adapter
            rvSortNumbering.setLayoutManager(new LinearLayoutManager(mContext) {
                @Override
                public boolean canScrollVertically() {
                    return false;
                }
            });
            mSortNumberingAdapter = new SortNumberingAdapter(mContext, rankings);
            rvSortNumbering.setAdapter(mSortNumberingAdapter);
        } else {
            mSortNumberingAdapter.setNewData(rankings);
        }

        if (foodRankingAdapter == null) {
            LinearLayoutManager lm = new LinearLayoutManager(mContext) {
                @Override
                public boolean canScrollVertically() {
                    return false;
                }
            };
            lm.setOrientation(RecyclerView.VERTICAL);
            rvFoodRanking.setLayoutManager(lm);
            foodRankingAdapter = new FoodRankingAdapter(mContext, rankings, totalAmount, totalNum);
            rvFoodRanking.setAdapter(foodRankingAdapter);
        } else {
            foodRankingAdapter.setNewData(rankings);
        }
        loadChart(salesRanking);
    }

    private void loadChart(List<SalesFoodsBean.DataBean.SalesRankingBean> info) {
        //是否以百分比顯示值
        salesChart.setUsePercentValues(false);
        //不顯示右側底部小字
        salesChart.getDescription().setEnabled(false);
        //控制轉動速度0為立即停止
        salesChart.setDragDecelerationFrictionCoef(0.95f);
//        salesChart.setCenterText(generateCenterSpannableText());
        //相當於左右間距
        salesChart.setExtraOffsets(0, 15f, 0, 15f);
        //是否繪製中心圓
        salesChart.setDrawHoleEnabled(true);
        salesChart.setHoleColor(Color.WHITE);

        salesChart.setTransparentCircleColor(Color.WHITE);
//        salesChart.setTransparentCircleAlpha(100);
        //中心圓的大小，相當於百分比
        salesChart.setHoleRadius(24f);
        //中心圓外部的半透明部分，百分比，需要比HoleRadius大
        salesChart.setTransparentCircleRadius(0f);
        //是否繪製文字
        salesChart.setDrawCenterText(true);

        salesChart.setRotationAngle(0);
        // enable rotation of the salesChart by touch
        //啟用觸摸，旋轉
        salesChart.setRotationEnabled(true);
        //将此设置为false可以防止点击手势突出显示值。仍然可以通过拖动或以编程方式突出显示值
        salesChart.setHighlightPerTapEnabled(true);
        // salesChart.setUnit(" €");
        // salesChart.setDrawUnitsInChart(true);
        // add a selection listener
        salesChart.setOnChartValueSelectedListener(new OnChartValueSelectedListener() {
            @Override
            public void onValueSelected(Entry e, Highlight h) {

            }

            @Override
            public void onNothingSelected() {

            }
        });
//        seekBarX.setProgress(4);
//        seekBarY.setProgress(100);

//        salesChart.animateY(1400, Easing.EaseInOutQuad);
        // salesChart.spin(2000, 0, 360);

        Legend l = salesChart.getLegend();
        l.setVerticalAlignment(Legend.LegendVerticalAlignment.TOP);
        l.setHorizontalAlignment(Legend.LegendHorizontalAlignment.RIGHT);
        l.setOrientation(Legend.LegendOrientation.VERTICAL);
        l.setDrawInside(false);
        l.setEnabled(false);
        salesChart.setEntryLabelColor(mContext.getResources().getColor(R.color.theme_color));
        setData(info);
    }

    private void setData(List<SalesFoodsBean.DataBean.SalesRankingBean> info) {
        //計算總和
        ArrayList<PieEntry> entries = new ArrayList<>();
        // NOTE: The order of the entries when being added to the entries array determines their position around the center of
        // the chart.
        if (info != null) {
            for (int i = 0; i < info.size(); i++) {
                if (info.get(i) != null) {
                    //金額佔比
                    float money = MoneyUtil.divide(info.get(i).getAmount(), totalAmount, 2, ROUND_HALF_UP);
                    if (money > 0.03) {
                        entries.add(new PieEntry(money, info.get(i).getProductName()));
                    }
                }
            }
        }
        PieDataSet dataSet = new PieDataSet(entries, "Election Results");
        dataSet.setSliceSpace(1f);//設置餅狀圖空隙
        dataSet.setSelectionShift(5f);//放大時突出多少
        // add a lot of colors
        ArrayList<Integer> colors = new ArrayList<>();

        for (int c : ColorTemplate.VORDIPLOM_COLORS)
            colors.add(c);

        for (int c : ColorTemplate.JOYFUL_COLORS)
            colors.add(c);

        for (int c : ColorTemplate.COLORFUL_COLORS)
            colors.add(c);

        for (int c : ColorTemplate.LIBERTY_COLORS)
            colors.add(c);

        for (int c : ColorTemplate.PASTEL_COLORS)
            colors.add(c);

        colors.add(ColorTemplate.getHoloBlue());

        dataSet.setColors(colors);
        //dataSet.setSelectionShift(0f);

        //設置周圍的值在餅狀圖外
        dataSet.setValueLinePart1OffsetPercentage(100f);
        //
        dataSet.setValueLinePart1Length(1f);
        dataSet.setValueLinePart2Length(0.2f);

        dataSet.setXValuePosition(PieDataSet.ValuePosition.OUTSIDE_SLICE);
        dataSet.setYValuePosition(PieDataSet.ValuePosition.OUTSIDE_SLICE);
        dataSet.setValueLineColor(mContext.getResources().getColor(R.color.theme_color));

        PieData data = new PieData(dataSet);
        salesChart.setUsePercentValues(true);
        data.setValueFormatter(new PercentFormatter(salesChart));
        data.setValueTextSize(12f);
        data.setValueTextColor(mContext.getResources().getColor(R.color.theme_color));
//        data.setValueTypeface(tf);
        salesChart.setData(data);
        // undo all highlights
        salesChart.highlightValues(null);
        salesChart.invalidate();
    }

    @OnClick({R2.id.tv_start_time, R2.id.iv_sale_time_triangle})
    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.tv_start_time || v.getId() == R.id.iv_sale_time_triangle) {
            triangleView.toggle();
            //打開時間選擇器
            Calendar cal = Calendar.getInstance();
            try {
                //設置默認時間為當前的起止時間
                cal.setTime(TimeUtils.DATE_FORMAT_DATE.parse(mTvStartTime.getText().toString()));
            } catch (ParseException e) {
                e.printStackTrace();
            }
            TimePickerUtils.showReportTimePicker(mContext, cal, (date, v1) -> {
                mTvStartTime.setText(TimeUtils.DATE_FORMAT_DATE.format(date));
                mPresenter.getSalesReportInfo(GsaCloudApplication.getRestaurantId(mContext) + "", mTvStartTime.getText().toString());
            }).setOnDismissListener(o -> triangleView.toggle());
        }
    }


}
