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.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
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.common.core.restaurant.RestaurantInfoManager;
import com.gingersoft.gsa.cloud.common.utils.MoneyUtil;
import com.gingersoft.gsa.cloud.common.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.DaggerSalesComponent;
import com.gingersoft.gsa.cloud.main.mvp.contract.SalesContract;
import com.gingersoft.gsa.cloud.main.mvp.model.bean.DailyReportBean;
import com.gingersoft.gsa.cloud.main.mvp.model.bean.DeliveryLineChartBean;
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.main.mvp.ui.view.OperatingReportView;
import com.gingersoft.gsa.cloud.main.mvp.ui.view.StartEndTimePickerView;
import com.gingersoft.gsa.cloud.ui.AAChartCoreLib.AAChartConfiger.AAChartModel;
import com.gingersoft.gsa.cloud.ui.AAChartCoreLib.AAChartConfiger.AAChartView;
import com.gingersoft.gsa.cloud.ui.AAChartCoreLib.AAChartConfiger.AASeriesElement;
import com.gingersoft.gsa.cloud.ui.AAChartCoreLib.AAChartEnum.AAChartLineDashStyleType;
import com.gingersoft.gsa.cloud.ui.AAChartCoreLib.AAChartEnum.AAChartType;
import com.gingersoft.gsa.cloud.ui.AAChartCoreLib.AATools.AAGradientColor;
import com.gingersoft.gsa.cloud.ui.AAChartCoreLib.AATools.AALinearGradientDirection;
import com.gingersoft.gsa.cloud.ui.utils.TimePickerUtils;
import com.gingersoft.gsa.cloud.ui.view.TriangleView;
import com.gingersoft.gsa.cloud.ui.widget.dialog.LoadingDialog;
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.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

import static com.gingersoft.gsa.cloud.common.utils.time.TimeUtils.DEFAULT_DATE_Y;
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;

    @BindView(R2.id.iv_end_time_triangle)
    TriangleView endTimeTriangleView;
    @BindView(R2.id.layout_sales)
    LinearLayout layoutSales;

    @BindView(R2.id.time_select_picker)
    StartEndTimePickerView startEndTimePickerView;


    @BindView(R2.id.pc_report_delivery)
    AAChartView mDeliveryLineChart;
    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) {
        mTvStartTime.setText(TimeUtils.getOldDate(-7));
        mTvEndTime.setText(TimeUtils.getOldDate(0));
        startEndTimePickerView.setOnUpdateTimePicker(onUpdateTimePicker);

        //处理报表滑动过程中和页面滑动出现冲突
        salesChart.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        salesChart.requestDisallowInterceptTouchEvent(true);
                        break;
                    case MotionEvent.ACTION_POINTER_UP:
                        salesChart.requestDisallowInterceptTouchEvent(false);
                        break;
                    case MotionEvent.ACTION_CANCEL:
                        salesChart.requestDisallowInterceptTouchEvent(false);
                        break;
                }
                return false;
            }
        });
    }

    @Override
    public void onLazyInitView(@Nullable Bundle savedInstanceState) {
        super.onLazyInitView(savedInstanceState);
        getSaleReport();

        getDeliveryReport();
    }

    @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() {

    }


    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) {
            if (salesRankingBean != null) {
                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.setNewInstance(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.setNewInstance(rankings);
        }
        loadChart(salesRanking);
    }

    private OperatingReportView netOperatingAmountView;

    @Override
    public void loadDeliveryPersonnelReport(List<DailyReportBean> dailyReportBeans) {
        if (netOperatingAmountView == null) {
            netOperatingAmountView = new OperatingReportView(mContext, false, "外送員分析", dailyReportBeans, 4);
            netOperatingAmountView.init();
            netOperatingAmountView.setOnReLoadListener(() -> getDeliveryReport());
            layoutSales.addView(netOperatingAmountView);
        } else {
            netOperatingAmountView.setNewData(dailyReportBeans);
        }
    }

    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() {

            }
        });
        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, salesChart);
    }

    private void setData(List<SalesFoodsBean.DataBean.SalesRankingBean> info, PieChart chart) {
        //計算總和
        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);
        chart.setUsePercentValues(true);
        data.setValueFormatter(new PercentFormatter(chart));
        data.setValueTextSize(12f);
        data.setValueTextColor(mContext.getResources().getColor(R.color.theme_color));
//        data.setValueTypeface(tf);
        chart.setData(data);
        // undo all highlights
        chart.highlightValues(null);
        chart.invalidate();
    }
    //查詢多少天的數據
    private int manyDay = 7;

    /**
     * 加載營業信息圖表
     */
    @Override
    public void loadDeliveryLineChart(List<DeliveryLineChartBean.DataBean> data) {
        Object[] chartData = new Object[manyDay];

        String[] xData = new String[manyDay];

        Calendar cal = Calendar.getInstance();
        //設置默認時間為當前的起止時間
        try {
            cal.setTime(TimeUtils.DATE_FORMAT_DATE.parse(TimeUtils.getDatebyDate(startEndTimePickerView.getStartTime(), -1)));
        } catch (ParseException e) {
            e.printStackTrace();
        }

        for (int i = 0; i < manyDay; i++) {
            xData[i] = TimeUtils.getBeginDistanceDate(cal, 1, Calendar.DATE, TimeUtils.DEFAULT_DATE_MD);
        }

        //將數據以時間為key，數據為value存入map
        Map<String, DeliveryLineChartBean.DataBean> map = new HashMap<>();
        for (int i = 0; i < data.size(); i++) {
            map.put(data.get(i).getDate(), data.get(i));
        }

        //y軸 數據間隔
        double yAxisTickInterval = 0;
        //第一條線
        for (int i = 0; i < manyDay; i++) {
            //通過今年年份+月份+日期，獲取對應的對象
            DeliveryLineChartBean.DataBean bean = map.get(TimeUtils.getDistanceDate(0, Calendar.YEAR, DEFAULT_DATE_Y) + xData[i]);
            if (bean != null) {
                chartData[i] = bean.getNum();
                yAxisTickInterval = Math.max(yAxisTickInterval, bean.getNum());
            } else {
                chartData[i] = 0;
            }
        }
        //配置線形圖
        AAChartModel aaChartModel = configureColorfulGradientSplineChart(xData, chartData, (int) (yAxisTickInterval / 6));
        //如果這幾天的數據都為0，設置默認最大數為18000，間隔為3000
        if (yAxisTickInterval == 0) {
            aaChartModel.yAxisMax(18000f);
            aaChartModel.yAxisTickInterval(3000);
        } else {
            aaChartModel.yAxisMax(null);
        }
        mDeliveryLineChart.aa_drawChartWithChartModel(aaChartModel);
    }

    /**
     * @param todayData         今天的數據
     * @param yAxisTickInterval y軸間隔
     * @return
     */
    AAChartModel configureColorfulGradientSplineChart(String[] xData, Object[] todayData, int yAxisTickInterval) {
        Object[][] stopsArr = {
                {0.00, "#018EF2"},
        };//颜色字符串设置支持十六进制类型和 rgba 类型
        Map<String, Object> linearGradientColor = AAGradientColor.linearGradient(
                AALinearGradientDirection.ToLeft,
                stopsArr
        );//颜色字符串设置支持十六进制类型和 rgba 类型

        return new AAChartModel()
                .chartType(AAChartType.Spline)
                .title("")
                .subtitle("")
                .yAxisTitle("")
                .axesTextColor("#777777")
                .axesTextSize(9)
                .legendEnabled(false)
                .markerRadius(0f)
                .categories(xData)
                .yAxisLineWidth(0.5f)
                .xAxisLineWidth(0.5f)
                .yAxisAllowDecimals(false)
                .yAxisTickInterval(yAxisTickInterval)
                .gridLineColor("#8CA0B3")
                .yAxisMin(0f)
                .gridLineDashStyle(AAChartLineDashStyleType.ShortDash)
                .dataLabelsFontColor("#777777")
                .yAxisLineColor("#018EF2")
                .series(new AASeriesElement[]{
                                new AASeriesElement()
                                        .name("單數")
                                        .lineWidth(4f)
                                        .color(linearGradientColor)
                                        .data(todayData)
                        }
                );
    }


    @OnClick({R2.id.tv_start_time, R2.id.iv_sale_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));
                }
                getSaleReport();
            }).setOnDismissListener(o -> {
                if (triangleView.isOpen()) {
                    triangleView.toggle();
                } else if (endTimeTriangleView.isOpen()) {
                    endTimeTriangleView.toggle();
                }
            });
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }

    private void getSaleReport() {
        String startTime = TimeUtils.getDatebyDate(mTvStartTime.getText().toString(), -1);
        String endTime = TimeUtils.getDatebyDate(mTvEndTime.getText().toString(), 1);
        mPresenter.getSalesReportInfo(RestaurantInfoManager.newInstance().getRestaurantId() + "", startTime, endTime);
    }

    private void getDeliveryReport(){
        String startTime = TimeUtils.getDatebyDate(startEndTimePickerView.getStartTime(), -1);
        String endTime = TimeUtils.getDatebyDate(startEndTimePickerView.getEndTime(), 1);
        mPresenter.getDeliveryOrderCurveInfo(RestaurantInfoManager.newInstance().getRestaurantId() + "", startTime, endTime);
        mPresenter.getDeliveryPersonnelReport(RestaurantInfoManager.newInstance().getRestaurantId() + "", startTime, endTime);
    }

    private StartEndTimePickerView.onUpdateTimePicker onUpdateTimePicker = (startTime, endTime) -> getDeliveryReport();

}
