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

import android.content.Intent;
import android.content.res.Resources;
import android.graphics.DashPathEffect;
import android.os.Bundle;
import android.os.Message;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.daivd.chart.component.axis.HorizontalAxis;
import com.daivd.chart.component.axis.VerticalAxis;
import com.daivd.chart.component.base.IAxis;
import com.daivd.chart.core.LineChart;
import com.daivd.chart.data.ChartData;
import com.daivd.chart.data.LineData;
import com.daivd.chart.data.style.FontStyle;
import com.daivd.chart.data.style.LineStyle;
import com.daivd.chart.data.style.PointStyle;
import com.daivd.chart.provider.component.point.Point;
import com.gingersoft.gsa.cloud.base.application.GsaCloudApplication;
import com.gingersoft.gsa.cloud.base.utils.MoneyUtil;
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.DaggerMainTopComponent;
import com.gingersoft.gsa.cloud.main.mvp.contract.MainTopContract;
import com.gingersoft.gsa.cloud.main.mvp.model.bean.HomeTurnoverBean;
import com.gingersoft.gsa.cloud.main.mvp.model.bean.MainOrderInfoChartBean;
import com.gingersoft.gsa.cloud.main.mvp.presenter.MainTopPresenter;
import com.gingersoft.gsa.cloud.main.mvp.ui.activity.ReportActivity;
import com.jess.arms.base.BaseFragment;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.jess.arms.utils.Preconditions.checkNotNull;


/**
 * ================================================
 * Description:
 * <p>
 * Created by MVPArmsTemplate on 02/18/2020 17: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 MainTopFragment extends BaseFragment<MainTopPresenter> implements MainTopContract.View, View.OnClickListener {
    //    line_chart_view
    @BindView(R2.id.line_chart_view)
    LineChart lineChart;
    @BindView(R2.id.tv_today_amount)
    TextView tvTurnover;//今日營業額
    @BindView(R2.id.tv_today_time)
    TextView time;//今日日期
    @BindView(R2.id.tv_compare_today_state)
    ImageView ivTurnoverTrend;//較昨日營業額趨勢
    @BindView(R2.id.tv_compare_today_size)
    TextView tvTurnoverTrend;//今日較昨日營業額差距
    @BindView(R2.id.tv_total_amount_project)
    TextView tvProjectAmount;//項目總金額
    @BindView(R2.id.tv_consumers_number)
    TextView tvConsumersNumber;//消費人數
    @BindView(R2.id.tv_bill_number)
    TextView tvBillNumber;//賬單數
    @BindView(R2.id.iv_project_amount_state)
    ImageView ivProjectAmountState;//今日項目額度較昨日上漲或下跌圖標
    @BindView(R2.id.tv_project_amount_trend)
    TextView tvProjectAmountTrend;//今日項目額度較昨日上漲或下跌數據
    @BindView(R2.id.tv_per_capita_consumption)
    TextView tvPerCapitaConsumption;//人均消費
    @BindView(R2.id.iv_people_trend)
    ImageView ivPeopleTrend;//人數趨勢圖標
    @BindView(R2.id.tv_people_trend)
    TextView tvPeopleTrend;//人數較昨日上漲或下跌數量
    @BindView(R2.id.tv_average_consumption_per_order)
    TextView tvAveragePerOrder;//平均每單消費
    @BindView(R2.id.iv_bill_trend)
    ImageView ivBillTrend;//賬單數量趨勢
    @BindView(R2.id.tv_bill_trend)
    TextView tvBillTrend;//賬單數量較昨日上漲或下跌數量

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

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

    @Override
    public View initView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_main_top, container, false);
        ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        mPresenter.getRestaurantReport(GsaCloudApplication.getRestaurantId(mContext) + "");//GsaCloudApplication.getRestaurantId(mContext) 獲取餐廳營業信息
        mPresenter.getOrderInfoChart();
        time.setText(TimeUtils.getCurrentTimeInString(new SimpleDateFormat("yyyy-MM-dd E")));
    }

    /**
     * 通过此方法可以使 Fragment 能够与外界做一些交互和通信, 比如说外部的 Activity 想让自己持有的某个 Fragment 对象执行一些方法,
     * 建议在有多个需要与外界交互的方法时, 统一传 {@link Message}, 通过 what 字段来区分不同的方法, 在 {@link #setData(Object)}
     * 方法中就可以 {@code switch} 做不同的操作, 这样就可以用统一的入口方法做多个不同的操作, 可以起到分发的作用
     * <p>
     * 调用此方法时请注意调用时 Fragment 的生命周期, 如果调用 {@link #setData(Object)} 方法时 {Fragment#onCreate(Bundle)} 还没执行
     * 但在 {@link #setData(Object)} 里却调用了 Presenter 的方法, 是会报空的, 因为 Dagger 注入是在 {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);
        ToastUtils.show(mContext, message);
    }

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

    @Override
    public void killMyself() {

    }

    @Override
    public void loadBusinessInfo(Map<String, HomeTurnoverBean.DataBean> dataBeanMap) {
        //通過今天的日期取得今天的報表信息
        HomeTurnoverBean.DataBean bean = dataBeanMap.get(TimeUtils.getCurrentTimeInString(TimeUtils.DATE_FORMAT_DATE));//TimeUtils.getCurrentTimeInString(TimeUtils.DATE_FORMAT_DATE)
        HomeTurnoverBean.DataBean yesterdayBean = dataBeanMap.get(TimeUtils.getOldDate(-1));//TimeUtils.getCurrentTimeInString(TimeUtils.DATE_FORMAT_DATE)
        if (bean != null) {
            tvTurnover.setText(bean.getBusiness_amount());
            tvProjectAmount.setText(bean.getSales());
            tvConsumersNumber.setText(bean.getPeople());
            tvBillNumber.setText(bean.getNumber_bill());
            if (Float.parseFloat(bean.getPeople()) != 0) {
                //人均消費
                tvPerCapitaConsumption.setText(Float.parseFloat(bean.getBusiness_amount()) / Float.parseFloat(bean.getPeople()) + "");
            }
            if (Integer.parseInt(bean.getNumber_bill()) != 0) {
                //每單平均消費
                tvAveragePerOrder.setText(Float.parseFloat(bean.getBusiness_amount()) / Integer.parseInt(bean.getNumber_bill()) + "");
            }

            if (yesterdayBean != null) {
                double turnover = MoneyUtil.sub(Double.parseDouble(bean.getBusiness_amount()), Double.parseDouble(yesterdayBean.getBusiness_amount()));
                ivTurnoverTrend.setImageResource(getTrendImg(turnover));
                tvTurnoverTrend.setText(String.format(getString(R.string.format_one_point), turnover));

                double sales = MoneyUtil.sub(Double.parseDouble(bean.getSales()), Double.parseDouble(yesterdayBean.getSales()));
                tvProjectAmountTrend.setText(String.format(getString(R.string.format_one_point), sales));
                ivProjectAmountState.setImageResource(getTrendImg(sales));

                int people = Integer.parseInt(bean.getPeople()) - Integer.parseInt(yesterdayBean.getPeople());
                ivPeopleTrend.setImageResource(getTrendImg(people));
                tvPeopleTrend.setText(people + "");

                int billNum = Integer.parseInt(bean.getNumber_bill()) - Integer.parseInt(yesterdayBean.getNumber_bill());
                ivBillTrend.setImageResource(getTrendImg(billNum));
                tvBillTrend.setText(billNum + "");
            }
        }
    }

    @Override
    public void loadChart(List<MainOrderInfoChartBean.DataBean> dataBeans) {

        Resources res = getResources();
        FontStyle.setDefaultTextSpSize(mContext, 12);


        //存儲今天的線條數據
        SparseArray<MainOrderInfoChartBean.DataBean.ItemsBean> dataBeanMap = new SparseArray<>();
        SparseArray<MainOrderInfoChartBean.DataBean.ItemsBean> yesterdayArrays = new SparseArray<>();
        for (int i = 0; i < dataBeans.size(); i++) {
            if (dataBeans.get(i).getDate().equals(TimeUtils.getCurrentTimeInString(TimeUtils.DATE_FORMAT_DATE))) {
                //獲得今天的線條數據
                for (MainOrderInfoChartBean.DataBean.ItemsBean itemsBean : dataBeans.get(i).getItems()) {
                    dataBeanMap.put(Integer.parseInt(itemsBean.getHours()), itemsBean);
                }
            }
            if (dataBeans.get(i).getDate().equals(TimeUtils.getOldDate(-1))) {
                //獲得前一天的線條數據
                for (MainOrderInfoChartBean.DataBean.ItemsBean itemsBean : dataBeans.get(i).getItems()) {
                    yesterdayArrays.put(Integer.parseInt(itemsBean.getHours()), itemsBean);
                }
            }
        }
        List<LineData> ColumnDatas = new ArrayList<>();
        //第一條線
        ArrayList<Double> tempList1 = new ArrayList<>();
        final LineData columnData1 = new LineData("今日", "", getResources().getColor(R.color.theme_color), tempList1);
        columnData1.setLineStyle(new LineStyle(mContext, 5, getResources().getColor(R.color.theme_color)));

        //第二條線
        ArrayList<Double> humidityList = new ArrayList<>();
        LineData columnData2 = new LineData("昨日", "", getResources().getColor(R.color.today_line), humidityList);
        columnData2.setLineStyle(new LineStyle(mContext, 5, getResources().getColor(R.color.today_line)));

        //X軸數據，固定不變
        List<String> chartYDataList = new ArrayList<>();
        for (int i = 0; i < 24; i++) {
            if (i < 10) {
                chartYDataList.add("0" + i + ":00");
            } else {
                chartYDataList.add(i + ":00");
            }
            //添加今天的數據
            if (dataBeanMap.get(i) != null) {
                tempList1.add(dataBeanMap.get(i).getAmount());
            } else {
                tempList1.add(0d);
            }
            //添加昨天的數據
            if (yesterdayArrays.get(i) != null) {
                humidityList.add(yesterdayArrays.get(i).getAmount());
            } else {
                humidityList.add(0d);
            }
        }
        ColumnDatas.add(columnData2);
        ColumnDatas.add(columnData1);

        ChartData<LineData> chartData2 = new ChartData<>("Line chart", chartYDataList, ColumnDatas);
        //設置曲線圖樣式
        lineChart.setLineModel(LineChart.CURVE_MODEL);
        //獲取左側垂直軸線
        VerticalAxis verticalAxis = lineChart.getLeftVerticalAxis();
        //獲取橫向軸線
        HorizontalAxis horizontalAxis = lineChart.getHorizontalAxis();
        //右側軸線
        VerticalAxis rightAxis = lineChart.getRightVerticalAxis();
        //設置右側軸線不顯示
        rightAxis.setDisplay(false);
        //设置竖轴方向在左側
        verticalAxis.setAxisDirection(IAxis.AxisDirection.LEFT);
        verticalAxis.setStartZero(true);
//        verticalAxis.setMaxValue(18000);
        //设置网格
        verticalAxis.setDrawGrid(true);
        //设置横轴方向
        horizontalAxis.setAxisDirection(IAxis.AxisDirection.BOTTOM);
        //不顯示網格
        horizontalAxis.setDrawGrid(false);
        horizontalAxis.getAxisStyle().setWidth(mContext, 1).setColor(res.getColor(R.color.theme_color));
        //设置线条样式
        verticalAxis.getAxisStyle().setWidth(mContext, 1).setColor(res.getColor(R.color.theme_color));
        //設置網格虛線樣式
        DashPathEffect effects = new DashPathEffect(new float[]{1, 2, 4, 8}, 1);
        verticalAxis.setGridStyle(new LineStyle(0.5f, res.getColor(R.color.report_dotted_line_color)));
        verticalAxis.getGridStyle().setEffect(effects);
        FontStyle scaleStyle = new FontStyle(mContext, 9, res.getColor(R.color.report_left_scale));
        scaleStyle.setScalePadding(30);
        horizontalAxis.setScaleStyle(scaleStyle);
        verticalAxis.setScaleStyle(scaleStyle);
        lineChart.setZoom(false);
        //开启十字架
        lineChart.getProvider().setOpenCross(true);

        //开启MarkView
//        lineChart.getProvider().setOpenMark(true);
        //设置MarkView
//        lineChart.getProvider().setMarkView(new CustomMarkView(mContext));
        //设置显示点
        Point point = new Point();
        point.getPointStyle().setShape(PointStyle.CIRCLE);
        //设置显示点的样式
        lineChart.getProvider().setPoint(point);
        //设置显示标题
        lineChart.setShowChartName(false);
        //底部不顯示顏色代表的意思
        lineChart.getLegend().setDisplay(false);
        lineChart.getMatrixHelper().setWidthMultiple(1f);
        lineChart.getMatrixHelper().setCanZoom(false);
        lineChart.getHorizontalAxis().setRotateAngle(0);//設置底部文字旋轉角度
        lineChart.setFirstAnim(true);
        lineChart.setChartData(chartData2);
        lineChart.setOnClickColumnListener((lineData, pos) -> {
//            Paint paint = new Paint();
//            paint.setAntiAlias(true);
//            paint.setTextSize(DensityUtils.sp2px(mContext, 13));
//            paint.setStyle(Paint.Style.FILL);
//            paint.setColor(Color.WHITE);
//            MultiLineBubbleTip tip = new MultiLineBubbleTip<LineData>(mContext,
//                    R.mipmap.round_rect, R.mipmap.triangle, paint) {
//                @Override
//                public boolean isShowTip(LineData lineData, int position) {
//                    return position == pos;
//                }
//
//                @Override
//                public String[] format(LineData lineData, int position) {
//                    String title = lineData.getName();
//                    String value = lineData.getChartYDataList().get(position) + lineData.getUnit();
//                    return new String[]{title, value};
//                }
//            };
//            tip.setColorFilter(Color.parseColor("#FA8072"));
//            tip.setAlpha(0.8f);
//            lineChart.getProvider().setTip(tip);
//            lineChart.invalidate();
        });

    }

    private int getTrendImg(double amount) {
        if (amount > 0) {
            return R.drawable.ic_rise;
        } else if (amount < 0) {
            return R.drawable.ic_down;
        } else {
            return -1;
        }
    }

    @OnClick({R2.id.tv_more_report})
    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.tv_more_report) {
            //更多報表
            startActivity(new Intent(mContext, ReportActivity.class));
        }
    }
}
