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

import android.content.Intent;
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.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.MainBusinessBean;
import com.gingersoft.gsa.cloud.main.mvp.presenter.BusinessReportPresenter;
import com.gingersoft.gsa.cloud.main.mvp.ui.adapter.BusinessInfoAdapter;
import com.gingersoft.gsa.cloud.ui.AAChartCore.AAChartCoreLib.AAChartConfiger.AAChartModel;
import com.gingersoft.gsa.cloud.ui.AAChartCore.AAChartCoreLib.AAChartConfiger.AAChartView;
import com.gingersoft.gsa.cloud.ui.AAChartCore.AAChartCoreLib.AAChartConfiger.AASeriesElement;
import com.gingersoft.gsa.cloud.ui.AAChartCore.AAChartCoreLib.AAChartEnum.AAChartLineDashStyleType;
import com.gingersoft.gsa.cloud.ui.AAChartCore.AAChartCoreLib.AAChartEnum.AAChartType;
import com.gingersoft.gsa.cloud.ui.AAChartCore.AAChartCoreLib.AATools.AAGradientColor;
import com.gingersoft.gsa.cloud.ui.AAChartCore.AAChartCoreLib.AATools.AALinearGradientDirection;
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.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.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)
    AAChartView 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) {
        //獲取一段時間內的營業信息，默認獲取七天的數據
        String startTime = TimeUtils.getOldDate(-6);

        mPresenter.getRestaurantAmount(GsaCloudApplication.getRestaurantId(mContext) + "", startTime, TimeUtils.getOldDate(1));
        mPresenter.getRestaurantBusinessInfo(GsaCloudApplication.getRestaurantId(mContext) + "", startTime, TimeUtils.getOldDate(1));

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

    }

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

        String[] xData = new String[7];
        for (int i = 0; i < 7; i++) {
            xData[i] = TimeUtils.getDistanceDate(-6 + i, Calendar.DATE, TimeUtils.DEFAULT_DATE_MD);
        }

        Map<String, MainBusinessBean.DataBean> map = new HashMap<>();
        for (int i = 0; i < data.size(); i++) {
            map.put(data.get(i).getStartingTime(), data.get(i));
        }

        double yAxisTickInterval = 0;
        //第一條線
        for (int i = 0; i < 7; i++) {
            //通過今年年份+月份+日期，獲取對應的對象
            MainBusinessBean.DataBean bean = map.get(TimeUtils.getDistanceDate(0, Calendar.YEAR, DEFAULT_DATE_Y) + xData[i]);
            if (bean != null) {
                chartData[i] = bean.getTotalAmount();
                yAxisTickInterval = Math.max(yAxisTickInterval, bean.getTotalAmount());
            } 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);
        }
        mLineChart.aa_drawChartWithChartModel(aaChartModel);
    }

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


    @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.getRestaurantAmount(GsaCloudApplication.getRestaurantId(mContext) + "", mTvStartTime.getText().toString(), TimeUtils.getOldDate(1));
                mPresenter.getRestaurantBusinessInfo(GsaCloudApplication.getRestaurantId(mContext) + "", mTvStartTime.getText().toString(), TimeUtils.getOldDate(1));
            });
        }
    }
}
