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.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
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.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.DaggerBusinessReportComponent;
import com.gingersoft.gsa.cloud.main.mvp.contract.BusinessReportContract;
import com.gingersoft.gsa.cloud.main.mvp.model.bean.BusinessBean;
import com.gingersoft.gsa.cloud.main.mvp.model.bean.HomeTurnoverBean;
import com.gingersoft.gsa.cloud.main.mvp.presenter.BusinessReportPresenter;
import com.gingersoft.gsa.cloud.main.mvp.ui.adapter.BusinessInfoAdapter;
import com.gingersoft.gsa.cloud.main.mvp.ui.view.CustomMarkView;
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 java.util.Map;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import butterknife.BindView;
import butterknife.OnClick;

import static com.gingersoft.gsa.cloud.base.utils.time.TimeUtils.DEFAULT_DATE_Y;
import static com.jess.arms.utils.Preconditions.checkNotNull;


/**
 * ================================================
 * Description:
 * <p>
 * Created by MVPArmsTemplate on 02/23/2020 16:19
 * <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 BusinessReportFragment extends BaseFragment<BusinessReportPresenter> implements BusinessReportContract.View, View.OnClickListener {

    @BindView(R2.id.report_business_chart)
    LineChart mLineChart;
    @BindView(R2.id.rv_business_details)
    RecyclerView mBusinessDetails;
    @BindView(R2.id.tv_restaurant_name)
    TextView mRestaurantName;
    @BindView(R2.id.tv_start_time)
    TextView mTvStartTime;
    @BindView(R2.id.tv_end_time)
    TextView mTvEndTime;

    private BusinessInfoAdapter businessInfoAdapter;

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

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

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        //獲取一段時間內的營業信息，默認獲取七天的數據
        mPresenter.getRestaurantBusinessInfo("26", TimeUtils.getOldDate(-6), TimeUtils.getOldDate(0));

        mRestaurantName.setText(GsaCloudApplication.getRestaurantName(mContext));
        mTvStartTime.setText(TimeUtils.getOldDate(-6));
        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() {

    }


    /**
     * 加載營業信息圖表
     */
    @Override
    public void loadChart(Map<String, HomeTurnoverBean.DataBean> data) {
        Resources res = getResources();
        FontStyle.setDefaultTextSpSize(mContext, 12);
        List<String> chartYDataList = new ArrayList<>();
        for (int i = 0; i < 7; i++) {
            chartYDataList.add(TimeUtils.getDistanceDate(-6 + i, Calendar.DATE, TimeUtils.DEFAULT_DATE_MD));
        }
        List<LineData> ColumnDatas = new ArrayList<>();
        //第一條線
        ArrayList<Double> tempList1 = new ArrayList<>();
        for (int i = 0; i < chartYDataList.size(); i++) {
            //通過今年年份+月份+日期，獲取對應的對象
            HomeTurnoverBean.DataBean bean = data.get(TimeUtils.getDistanceDate(0, Calendar.YEAR, DEFAULT_DATE_Y) + chartYDataList.get(i));
            if (bean != null && bean.getBusiness_amount() != null) {
                tempList1.add(Double.parseDouble(bean.getBusiness_amount()));
            } else {
                tempList1.add(0d);
            }
        }

        final LineData columnData1 = new LineData("今日", "", getResources().getColor(R.color.theme_color), tempList1);
        columnData1.setLineStyle(new LineStyle(mContext, 5, getResources().getColor(R.color.theme_color)));
        ColumnDatas.add(columnData1);

        ChartData<LineData> chartData2 = new ChartData<>("Line chart", chartYDataList, ColumnDatas);
        //設置曲線圖樣式
        mLineChart.setLineModel(LineChart.CURVE_MODEL);
        //獲取左側垂直軸線
        VerticalAxis verticalAxis = mLineChart.getLeftVerticalAxis();
        //獲取橫向軸線
        HorizontalAxis horizontalAxis = mLineChart.getHorizontalAxis();
        //右側軸線
        VerticalAxis rightAxis = mLineChart.getRightVerticalAxis();
        //設置右側軸線不顯示
        rightAxis.setDisplay(false);
        //设置竖轴方向在左側
        verticalAxis.setAxisDirection(IAxis.AxisDirection.LEFT);
        verticalAxis.setStartZero(true);
        //设置网格
        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);
        mLineChart.setZoom(false);
        //开启十字架
        mLineChart.getProvider().setOpenCross(true);
        //關閉硬件加速
        mLineChart.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
        //开启MarkView
        mLineChart.getProvider().setOpenMark(true);
        //设置MarkView
        mLineChart.getProvider().setMarkView(new CustomMarkView(columnData1));
        //设置显示点
        Point point = new Point();
        point.getPointStyle().setShape(PointStyle.CIRCLE);
        //设置显示点的样式
        mLineChart.getProvider().setPoint(point);
        //设置显示标题
        mLineChart.setShowChartName(false);
        //底部不顯示顏色代表的意思
        mLineChart.getLegend().setDisplay(false);
        mLineChart.getMatrixHelper().setWidthMultiple(0.9f);
        mLineChart.getHorizontalAxis().setRotateAngle(0);//設置底部文字旋轉角度
        mLineChart.setFirstAnim(false);
        mLineChart.setChartData(chartData2);
        mLineChart.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);
//            mLineChart.getProvider().setTip(tip);
//            mLineChart.invalidate();
        });
    }

    @Override
    public void loadAdapter(List<BusinessBean> businessBeans) {
        if (businessInfoAdapter == null) {
            mBusinessDetails.setLayoutManager(new GridLayoutManager(mContext, 3) {
                @Override
                public boolean canScrollVertically() {
                    return false;
                }
            });
            businessInfoAdapter = new BusinessInfoAdapter(businessBeans);
            mBusinessDetails.setAdapter(businessInfoAdapter);
        } else {
            businessInfoAdapter.setNewData(businessBeans);
        }
    }

    @OnClick({R2.id.tv_start_time})
    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.tv_start_time) {
            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.getRestaurantBusinessInfo("26", mTvStartTime.getText().toString(), TimeUtils.getOldDate(0));
            });
        }
    }
}
