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

import android.content.Intent;
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 androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.gingersoft.gsa.cloud.base.application.GsaCloudApplication;
import com.gingersoft.gsa.cloud.base.utils.MoneyUtil;
import com.gingersoft.gsa.cloud.base.utils.other.TextUtil;
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.MainBusinessBean;
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.NewMainActivity;
import com.gingersoft.gsa.cloud.main.mvp.ui.activity.ReportActivity;
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.util.List;
import java.util.Map;

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 {
    private AAChartModel aaChartModel;
    @BindView(R2.id.line_chart_view)
    AAChartView 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) {
//        getInfo();
        time.setText(TimeUtils.getCurrentTimeInString(TimeUtils.dateFormatYMDE));
    }

    private void getInfo() {
        mPresenter.getOrderInfoChart(GsaCloudApplication.getRestaurantId(mContext) + "");
        mPresenter.getRestaurantReport(GsaCloudApplication.getRestaurantId(mContext) + "");//GsaCloudApplication.getRestaurantId(mContext) 獲取餐廳營業信息
    }


    @Override
    public void onResume() {
        super.onResume();
        getInfo();
    }

    /**
     * 通过此方法可以使 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) {
        if (data instanceof Message) {
            switch (((Message) data).what) {
                case 0:
                    //刷新數據
                    getInfo();
                    break;
                default:
                    //do something
                    break;
            }
        }
    }


    @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(List<MainBusinessBean.DataBean> dataBeans) {
        MainBusinessBean.DataBean todayBean = null;
        MainBusinessBean.DataBean yesterdayBean = null;
        for (MainBusinessBean.DataBean dataBean : dataBeans) {
            if (!TextUtil.isEmptyOrNullOrUndefined(dataBean.getDate())) {
                if (dataBean.getDate().equals(TimeUtils.getOldDate(0))) {
                    todayBean = dataBean;
                } else if (dataBean.getDate().equals(TimeUtils.getOldDate(-1))) {
                    yesterdayBean = dataBean;
                }
            }
        }
        if (todayBean != null) {
            tvTurnover.setText(String.valueOf(todayBean.getTotalAmount()));//今日營業額，淨值
            tvProjectAmount.setText(String.valueOf(todayBean.getPrice()));
            tvConsumersNumber.setText(String.valueOf(todayBean.getPerson()));
            tvBillNumber.setText(String.valueOf(todayBean.getNum()));
            if (todayBean.getPerson() != 0) {
                //人均消費
                tvPerCapitaConsumption.setText(String.valueOf(MoneyUtil.totalFoodPrice(todayBean.getPrice() / todayBean.getPerson())));
            } else {
                tvPerCapitaConsumption.setText(String.valueOf(0));
            }
            if (todayBean.getNum() != 0) {
                //每單平均消費
                tvAveragePerOrder.setText(String.valueOf(MoneyUtil.totalFoodPrice(todayBean.getPrice() / todayBean.getNum())));
            } else {
                tvAveragePerOrder.setText(String.valueOf(0));
            }
            //通過今天的日期取得今天的報表信息
            if (yesterdayBean != null) {
                //获得昨日和今日營業額的差，淨值
                double turnover = MoneyUtil.sub(todayBean.getTotalAmount(), yesterdayBean.getTotalAmount());
                ivTurnoverTrend.setVisibility(View.VISIBLE);
                ivTurnoverTrend.setImageResource(getTrendImg(turnover));
                tvTurnoverTrend.setText(String.format(getString(R.string.format_one_point), Math.abs(turnover)));

                //項目總金額
                double sales = MoneyUtil.sub(todayBean.getPrice(), yesterdayBean.getPrice());
                tvProjectAmountTrend.setText(String.format(getString(R.string.format_one_point), Math.abs(sales)));
                ivProjectAmountState.setVisibility(View.VISIBLE);
                ivProjectAmountState.setImageResource(getTrendImg(sales));

                //人數
                int people = MoneyUtil.sub(todayBean.getPerson(), yesterdayBean.getPerson());
                ivPeopleTrend.setImageResource(getTrendImg(people));
                ivPeopleTrend.setVisibility(View.VISIBLE);
                tvPeopleTrend.setText(String.valueOf(Math.abs(people)));

                //賬單數
                int billNum = todayBean.getNum() - yesterdayBean.getNum();
                ivBillTrend.setImageResource(getTrendImg(billNum));
                ivBillTrend.setVisibility(View.VISIBLE);
                tvBillTrend.setText(String.valueOf(Math.abs(billNum)));
            }
        }
    }

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

        Map linearGradientColor2 = AAGradientColor.linearGradient(
                AALinearGradientDirection.ToLeft,
                stopsArr2
        );//颜色字符串设置支持十六进制类型和 rgba 类型
        return new AAChartModel()
                .chartType(AAChartType.Spline)
                .title("")
                .subtitle("")
                .yAxisTitle("")
                .axesTextColor("#777777")
                .axesTextSize(9)
                .legendEnabled(false)
                .categories(new String[]{"00:00", "01:00", "02:00", "03:00", "04:00", "05:00", "06:00", "07:00", "08:00", "09:00", "10:00", "11:00", "12:00", "13:00", "14:00", "15:00", "16:00", "17:00", "18:00", "19:00", "20:00", "21:00", "22:00", "23:00", "24:00"})
                .yAxisLineWidth(0.5f)
                .xAxisLineWidth(0.5f)
                .xAxisTickInterval(4)
                .yAxisAllowDecimals(false)
                .yAxisTickInterval(yAxisTickInterval)
                .markerRadius(0f)
                .yAxisMin(0f)
                .gridLineColor("#FF8CA0B3")
                .gridLineDashStyle(AAChartLineDashStyleType.ShortDash)
                .dataLabelsFontColor("#777777")
                .yAxisLineColor("#018EF2")
                .series(new AASeriesElement[]{
                                new AASeriesElement()
                                        .name("昨日")
                                        .lineWidth(4f)
                                        .color(linearGradientColor2)
                                        .data(yesterdayData),
                                new AASeriesElement()
                                        .name("今日")
                                        .lineWidth(4f)
                                        .color(linearGradientColor)
                                        .data(todayData)
                        }
                );
    }

    @Override
    public void loadChart(List<MainOrderInfoChartBean.DataBean> dataBeans) {
        ((NewMainActivity) getActivity()).onFinishRefresh();//結束刷新

        Object[] todayData = new Object[24];//今天的數據
        Object[] yesterdayData = new Object[24];//昨天的數據
        //存儲今天的線條數據
        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);
                }
            }
        }
        double maxAmount = 0;//最大金額，y軸顯示七個數，最大金額除以7，得到間隔數字
        for (int i = 0; i < 24; i++) {
            //添加今天的數據
            if (dataBeanMap.get(i) != null) {
                todayData[i] = dataBeanMap.get(i).getAmount();
                maxAmount = Math.max(maxAmount, dataBeanMap.get(i).getAmount());
            } else {
                todayData[i] = 0d;
            }
            //添加昨天的數據
            if (yesterdayArrays.get(i) != null) {
                yesterdayData[i] = yesterdayArrays.get(i).getAmount();
                maxAmount = Math.max(maxAmount, yesterdayArrays.get(i).getAmount());
            } else {
                yesterdayData[i] = 0d;
            }
        }

        //初始化曲線圖
        aaChartModel = configureColorfulGradientSplineChart(todayData, yesterdayData, (int) (maxAmount / 6));
        if (maxAmount == 0) {
            aaChartModel.yAxisMax(18000f);
            aaChartModel.yAxisTickInterval(3000);
        } else {
            aaChartModel.yAxisMax(null);
        }
        lineChart.aa_drawChartWithChartModel(aaChartModel);
    }

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

    @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));
        }
    }
}
