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.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.gingersoft.gsa.cloud.base.application.GsaCloudApplication;
import com.gingersoft.gsa.cloud.base.utils.time.TimePickerUtils;
import com.gingersoft.gsa.cloud.base.utils.time.TimeUtils;
import com.gingersoft.gsa.cloud.main.R;
import com.gingersoft.gsa.cloud.main.R2;
import com.gingersoft.gsa.cloud.main.di.component.DaggerPaymentMethodReportComponent;
import com.gingersoft.gsa.cloud.main.mvp.contract.PaymentMethodReportContract;
import com.gingersoft.gsa.cloud.main.mvp.model.bean.PaymentMethodBean;
import com.gingersoft.gsa.cloud.main.mvp.presenter.PaymentMethodReportPresenter;
import com.gingersoft.gsa.cloud.main.mvp.ui.adapter.PaymentMethodAdapter;
import com.gingersoft.gsa.cloud.main.mvp.ui.adapter.PaymentMethodColorAdapter;
import com.gingersoft.gsa.cloud.ui.view.TriangleView;
import com.gingersoft.gsa.cloud.ui.widget.dialog.LoadingDialog;
import com.github.mikephil.charting.animation.Easing;
import com.github.mikephil.charting.charts.PieChart;
import com.github.mikephil.charting.components.Legend;
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.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;


/**
 * ================================================
 * Description:
 * <p>
 * Created by MVPArmsTemplate on 02/23/2020 16:22
 * <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 PaymentMethodReportFragment extends BaseFragment<PaymentMethodReportPresenter> implements PaymentMethodReportContract.View, View.OnClickListener {

    @BindView(R2.id.rv_payment_color)
    RecyclerView rvPaymentColor;
    private PaymentMethodColorAdapter methodColorAdapter;
    @BindView(R2.id.rv_payment_proportion)
    RecyclerView rvPaymentProportion;
    private PaymentMethodAdapter methodAdapter;
    @BindView(R2.id.report_payment_method_chart)
    PieChart chart;
    @BindView(R2.id.tv_start_time)
    TextView mTvStartTime;
    @BindView(R2.id.tv_end_time)
    TextView mTvEndTime;
    @BindView(R2.id.iv_payment_time_triangle)
    TriangleView triangleView;

    @BindView(R2.id.iv_end_time_triangle)
    TriangleView endTimeTriangleView;

    public static PaymentMethodReportFragment newInstance() {
        PaymentMethodReportFragment fragment = new PaymentMethodReportFragment();
        return fragment;
    }

    @Override
    public void setupFragmentComponent(@NonNull AppComponent appComponent) {
        DaggerPaymentMethodReportComponent //如找不到该类,请编译一下项目
                .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_payment_method_report, container, false);
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        mTvStartTime.setText(TimeUtils.getOldDate(-7));
        mTvEndTime.setText(TimeUtils.getOldDate(0));

        getPayMenthInfo();
    }

    private void getPayMenthInfo() {
        String startTime = TimeUtils.getDatebyDate(mTvStartTime.getText().toString(), -1);
        String endTime = TimeUtils.getDatebyDate(mTvEndTime.getText().toString(), 1);
        mPresenter.getPaymentInfo(GsaCloudApplication.getRestaurantId() + "", startTime, endTime);
    }

    /**
     * 通过此方法可以使 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) {
        if (message != null)
            LoadingDialog.showDialogForLoading(mContext, message, true);
        else
            LoadingDialog.showDialogForLoading(mContext);
    }

    @Override
    public void hideLoading() {
        LoadingDialog.cancelDialogForLoading();
    }

    @Override
    public void showMessage(@NonNull String message) {
        ArmsUtils.makeText(mContext, message);
    }

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

    @Override
    public void killMyself() {

    }

    @Override
    public void loadPaymentInfo(List<PaymentMethodBean.DataBean> data) {
        if (methodColorAdapter == null) {
            rvPaymentColor.setLayoutManager(new GridLayoutManager(mContext, 4) {
                @Override
                public boolean canScrollVertically() {
                    return false;
                }
            });
            methodColorAdapter = new PaymentMethodColorAdapter(mContext, data);
            rvPaymentColor.setAdapter(methodColorAdapter);
        } else {
            methodColorAdapter.setNewData(data);
        }
        if (methodAdapter == null) {
            rvPaymentProportion.setLayoutManager(new GridLayoutManager(mContext, 4) {
                @Override
                public boolean canScrollVertically() {
                    return false;
                }
            });
            methodAdapter = new PaymentMethodAdapter(mContext, data);
            rvPaymentProportion.setAdapter(methodAdapter);
        } else {
            methodAdapter.setNewData(data);
        }
        initChart();
        setData(data);
    }

    private void initChart() {
        //不顯示右側底部小字
        chart.setUsePercentValues(true);
        chart.getDescription().setEnabled(false);
//        chart.setExtraOffsets(0, 0, 0, 0);
        //滑動摩擦係數
        chart.setDragDecelerationFrictionCoef(0.95f);
        //是否繪製中心圓
        chart.setDrawHoleEnabled(true);
        chart.setHoleColor(Color.WHITE);

        chart.setTransparentCircleColor(Color.BLACK);
        chart.setTransparentCircleAlpha(110);

        chart.setHoleRadius(28f);
        chart.setTransparentCircleRadius(0f);
        //不繪製中心文字
        chart.setDrawCenterText(false);
        //設置旋轉角度
        chart.setRotationAngle(0);
        //設置可以觸摸旋轉
        chart.setRotationEnabled(true);
//        chart.setHighlightPerTapEnabled(true);
        //設置單位
        // chart.setUnit(" €");
        // chart.setDrawUnitsInChart(true);

        // add a selection listener
//        chart.setOnChartValueSelectedListener(this);

        chart.animateY(1400, Easing.EaseInOutQuad);
        Legend l = chart.getLegend();
//        l.setVerticalAlignment(Legend.LegendVerticalAlignment.TOP);
//        l.setHorizontalAlignment(Legend.LegendHorizontalAlignment.RIGHT);
//        l.setOrientation(Legend.LegendOrientation.VERTICAL);
        l.setDrawInside(false);
        l.setEnabled(false);
        // entry label styling
        chart.setEntryLabelColor(mContext.getResources().getColor(R.color.white));
        chart.setEntryLabelTextSize(12f);
    }

    private void setData(List<PaymentMethodBean.DataBean> dataBeans) {
        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.
        ArrayList<Integer> colors = new ArrayList<>();
        for (int i = 0; i < dataBeans.size(); i++) {
            float percentage = Float.parseFloat(dataBeans.get(i).getPercentage().replace("%", ""));
            if (percentage > 3) {//比例大於3才添加
                entries.add(new PieEntry(percentage, dataBeans.get(i).getPayName()));
                colors.add(mContext.getResources().getColor(PaymentMethodAdapter.colors[i % PaymentMethodAdapter.colors.length]));
            }
        }
        PieDataSet dataSet = new PieDataSet(entries, "Election Results");
        dataSet.setColors(colors);
        dataSet.setDrawIcons(false);

        dataSet.setSliceSpace(1f);
        dataSet.setSelectionShift(10f);

        PieData data = new PieData(dataSet);
        data.setValueFormatter(new PercentFormatter(chart));
        data.setValueTextSize(12f);
        data.setValueTextColor(mContext.getResources().getColor(R.color.white));
        chart.setData(data);

        chart.invalidate();
    }

    @OnClick({R2.id.tv_start_time, R2.id.iv_payment_time_triangle, R2.id.tv_end_time, R2.id.iv_end_time_triangle})
    @Override
    public void onClick(View v) {
        int viewId = v.getId();
        try {
            String time;
            Calendar startTime = Calendar.getInstance();
            startTime.set(Calendar.DAY_OF_YEAR, startTime.getActualMinimum(Calendar.DAY_OF_YEAR));//今年第一天

            Calendar endTime = Calendar.getInstance();
            if (viewId == R.id.tv_start_time || viewId == R.id.iv_start_time_triangle) {
                triangleView.toggle();
                time = mTvStartTime.getText().toString();
                endTime.setTime(TimeUtils.DATE_FORMAT_DATE.parse(mTvEndTime.getText().toString()));
            } else if (viewId == R.id.tv_end_time || viewId == R.id.iv_end_time_triangle) {
                endTimeTriangleView.toggle();
                time = mTvEndTime.getText().toString();
                startTime.setTime(TimeUtils.DATE_FORMAT_DATE.parse(mTvStartTime.getText().toString()));
            } else {
                time = TimeUtils.getCurrentDate(TimeUtils.DATE_FORMAT_DATE);
            }

            Calendar cal = Calendar.getInstance();
            try {
                //設置默認時間為當前的起止時間
                cal.setTime(TimeUtils.DATE_FORMAT_DATE.parse(time));
            } catch (ParseException e) {
                e.printStackTrace();
            }
            //打開時間選擇器
            TimePickerUtils.showReportTimePicker(mContext, startTime, endTime, cal, (date, v1) ->
            {
                if (viewId == R.id.tv_start_time || viewId == R.id.iv_start_time_triangle) {
                    mTvStartTime.setText(TimeUtils.DATE_FORMAT_DATE.format(date));
                } else {
                    mTvEndTime.setText(TimeUtils.DATE_FORMAT_DATE.format(date));
                }
                getPayMenthInfo();
            }).setOnDismissListener(o -> {
                if (triangleView.isOpen()) {
                    triangleView.toggle();
                } else if (endTimeTriangleView.isOpen()) {
                    endTimeTriangleView.toggle();
                }
            });
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }
}
