package com.gingersoft.gsa.cloud.main.mvp.presenter;

import android.app.Application;

import com.gingersoft.gsa.cloud.common.utils.MoneyUtil;
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.DailyReportBean;
import com.gingersoft.gsa.cloud.main.mvp.model.bean.DaySalesReportBean;
import com.gingersoft.gsa.cloud.main.mvp.model.bean.DiscountDetailsReportBean;
import com.gingersoft.gsa.cloud.main.mvp.model.bean.MainBusinessBean;
import com.gingersoft.gsa.cloud.main.mvp.model.bean.OrderAnalysisBean;
import com.gingersoft.gsa.cloud.main.mvp.model.bean.OrderDetailsReport;
import com.jess.arms.di.scope.FragmentScope;
import com.jess.arms.http.imageloader.ImageLoader;
import com.jess.arms.integration.AppManager;
import com.jess.arms.mvp.BasePresenter;
import com.jess.arms.utils.RxLifecycleUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.schedulers.Schedulers;
import me.jessyan.rxerrorhandler.core.RxErrorHandler;
import me.jessyan.rxerrorhandler.handler.ErrorHandleSubscriber;


/**
 * ================================================
 * 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>
 * ================================================
 */
@FragmentScope
public class BusinessReportPresenter extends BasePresenter<BusinessReportContract.Model, BusinessReportContract.View> {
    @Inject
    RxErrorHandler mErrorHandler;
    @Inject
    Application mApplication;
    @Inject
    ImageLoader mImageLoader;
    @Inject
    AppManager mAppManager;

    @Inject
    public BusinessReportPresenter(BusinessReportContract.Model model, BusinessReportContract.View rootView) {
        super(model, rootView);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        this.mErrorHandler = null;
        this.mAppManager = null;
        this.mImageLoader = null;
        this.mApplication = null;
    }

    public void getRestaurantAmount(String restaurantId, String startTime, String endTime) {
        Map<String, String> map = new HashMap<>();
        map.put("restaurantId", restaurantId);
        map.put("startTime", startTime);
        map.put("endTime", endTime);
        mModel.getRestaurantBusinessAmount(map)
                .subscribeOn(Schedulers.io())
                .doOnSubscribe(disposable -> mRootView.showLoading("加載營業報表..."))
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .doAfterTerminate(() -> mRootView.hideLoading())
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .subscribe(new ErrorHandleSubscriber<MainBusinessBean>(mErrorHandler) {

                    @Override
                    public void onNext(@NonNull MainBusinessBean info) {
                        if (info != null && info.isSuccess()) {
                            if (info.getData() != null) {
                                mRootView.loadChart(info.getData());
                            }
                        } else {
                            mRootView.showMessage("營業信息獲取失敗");
                        }
                    }
                });
    }


    public void getRestaurantBusinessInfo(String restaurantId, String startTime, String endTime) {
//        Map<String, String> map = new HashMap<>();
//        map.put("restaurantId", restaurantId);
//        map.put("startTime", startTime);
//        map.put("endTime", endTime);
//        mModel.getRestaurantBusinessDetails(map)
//                .subscribeOn(Schedulers.io())
//                .doOnSubscribe(disposable -> mRootView.showLoading(""))
//                .subscribeOn(AndroidSchedulers.mainThread())
//                .observeOn(AndroidSchedulers.mainThread())
//                .doAfterTerminate(() -> mRootView.hideLoading())
//                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
//                .subscribe(new ErrorHandleSubscriber<BusinessDetailsBean>(mErrorHandler) {
//
//                    @Override
//                    public void onNext(@NonNull BusinessDetailsBean info) {
//                        if (info != null && info.isSuccess()) {
//                            loadAdapterInfo(info.getData());
//                        } else {
//                            mRootView.showMessage("營業信息獲取失敗");
//                        }
//                    }
//                });
    }

    public void getDaySalesReport(String restaurantId, String startTime, String endTime) {
        Map<String, String> map = new HashMap<>();
        map.put("restaurantId", restaurantId);
        map.put("startDate", startTime);
        map.put("endDate", endTime);
        mModel.getDaySalesReport(map)
                .subscribeOn(Schedulers.io())
                .doOnSubscribe(disposable -> mRootView.showLoading("加載每日營業詳情..."))
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .doAfterTerminate(() -> mRootView.hideLoading())
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .subscribe(new ErrorHandleSubscriber<DaySalesReportBean>(mErrorHandler) {
                    @Override
                    public void onNext(@NonNull DaySalesReportBean info) {
                        if (info != null && info.isSuccess()) {
                            loadDaySalesReport(info.getData());
                        } else {
                            loadDaySalesReport(null);
                        }
                    }

                    @Override
                    public void onError(Throwable t) {
                        super.onError(t);
                        loadDaySalesReport(null);
                    }
                });
    }


    public void getOrderAnalysis(String restaurantId, String startTime, String endTime) {
        Map<String, String> map = new HashMap<>();
        map.put("restaurantId", restaurantId);
        map.put("startDate", startTime);
        map.put("endDate", endTime);
        mModel.getOrderAnalysis(map)
                .subscribeOn(Schedulers.io())
                .doOnSubscribe(disposable -> mRootView.showLoading("加載營業金額詳情..."))
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .doAfterTerminate(() -> mRootView.hideLoading())
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .subscribe(new ErrorHandleSubscriber<OrderAnalysisBean>(mErrorHandler) {
                    @Override
                    public void onNext(@NonNull OrderAnalysisBean info) {
                        if (info != null && info.isSuccess() && info.getData() != null) {
                            if (info.getData().getList() != null) {
                                List<DailyReportBean> dailyReportBeans = new ArrayList<>();
                                dailyReportBeans.add(new DailyReportBean("支付統計", "賬單數量", "佔比(%)", "金額"));
                                for (OrderAnalysisBean.DataBean.ListBean listBean : info.getData().getList()) {
                                    dailyReportBeans.add(new DailyReportBean(listBean.getPayName(), listBean.getBillNum() + "", listBean.getPercentage() + "", MoneyUtil.get_ItemDecimals_money(listBean.getPayAmount()) + ""));
                                }
                                dailyReportBeans.add(new DailyReportBean("合計", info.getData().getBillNumSum() + "", "100", MoneyUtil.get_ItemDecimals_money(info.getData().getAmountSum()) + ""));
                                mRootView.loadOrderAnalysis(dailyReportBeans);
                            } else {
                                mRootView.loadOrderAnalysis(new ArrayList<>());
                            }
                        } else {
                            mRootView.loadOrderAnalysis(null);
                        }
                    }

                    @Override
                    public void onError(Throwable t) {
                        super.onError(t);
                        mRootView.loadOrderAnalysis(null);
                    }
                });
    }

    public void getOrderDetailsReport(String restaurantId, String startTime, String endTime) {
        Map<String, String> map = new HashMap<>();
        map.put("restaurantId", restaurantId);
        map.put("startDate", startTime);
        map.put("endDate", endTime);
        mModel.getOrderDetailsReport(map)
                .subscribeOn(Schedulers.io())
                .doOnSubscribe(disposable -> mRootView.showLoading("加載訂單詳情..."))
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .doAfterTerminate(() -> mRootView.hideLoading())
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .subscribe(new ErrorHandleSubscriber<OrderDetailsReport>(mErrorHandler) {
                    @Override
                    public void onNext(@NonNull OrderDetailsReport info) {
                        if (info != null && info.isSuccess() && info.getData() != null) {
                            if (info.getData().getList() != null) {
                                List<DailyReportBean> dailyReportBeans = new ArrayList<>();
                                dailyReportBeans.add(new DailyReportBean("訂單類型", "訂單數量", "佔比(%)", "金額"));
                                for (OrderDetailsReport.DataBean.ListBean listBean : info.getData().getList()) {
                                    dailyReportBeans.add(new DailyReportBean(listBean.getOrderType(), listBean.getBillNum() + "", listBean.getPercentage() + "", MoneyUtil.get_ItemDecimals_money(listBean.getPayAmount()) + ""));
                                }

                                dailyReportBeans.add(new DailyReportBean("合計", info.getData().getBillNumSum() + "", "100", MoneyUtil.get_ItemDecimals_money(info.getData().getAmountSum()) + ""));
                                mRootView.loadOrderDetailsReport(dailyReportBeans);
                            } else {
                                mRootView.loadOrderDetailsReport(new ArrayList<>());
                            }
                        } else {
                            mRootView.loadOrderDetailsReport(null);
                        }
                    }

                    @Override
                    public void onError(Throwable t) {
                        super.onError(t);
                        mRootView.loadOrderDetailsReport(null);
                    }
                });
    }

    public void getDiscountDetails(String restaurantId, String startTime, String endTime) {
        Map<String, String> map = new HashMap<>();
        map.put("restaurantId", restaurantId);
        map.put("startDate", startTime);
        map.put("endDate", endTime);
        mModel.getDiscountDetails(map)
                .subscribeOn(Schedulers.io())
                .doOnSubscribe(disposable -> mRootView.showLoading("加載折扣詳情..."))
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .doAfterTerminate(() -> mRootView.hideLoading())
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .subscribe(new ErrorHandleSubscriber<DiscountDetailsReportBean>(mErrorHandler) {
                    @Override
                    public void onNext(@NonNull DiscountDetailsReportBean info) {
                        if (info != null && info.isSuccess() && info.getData() != null) {
                            if (info.getData().getList() != null) {
                                List<DailyReportBean> dailyReportBeans = new ArrayList<>();
                                dailyReportBeans.add(new DailyReportBean("折扣名稱", "訂單數量", "金額"));
                                for (DiscountDetailsReportBean.DataBean.ListBean listBean : info.getData().getList()) {
                                    dailyReportBeans.add(new DailyReportBean(listBean.getCouponName(), listBean.getBillNum() + "", listBean.getAmount() + ""));
                                }
                                dailyReportBeans.add(new DailyReportBean("合計", info.getData().getBillNumSum() + "", info.getData().getAmountSum() + ""));
                                mRootView.loadDiscountDetailsReport(dailyReportBeans);
                            } else {
                                mRootView.loadDiscountDetailsReport(new ArrayList<>());
                            }
                        } else {
                            mRootView.loadDiscountDetailsReport(null);
                        }
                    }

                    @Override
                    public void onError(Throwable t) {
                        super.onError(t);
                        mRootView.loadDiscountDetailsReport(null);
                    }
                });
    }


    private void loadDaySalesReport(DaySalesReportBean.DataBean dataBean) {
        String[] itemNames = new String[]{"項目銷售總金額", "折扣", "服務費", "賬單小數", "簽單", "貼士", "餐盒費", "送貨費", "營業金額淨值"};
        List<BusinessBean> businessBeans = new ArrayList<>();
        if (dataBean != null) {
            businessBeans.add(new BusinessBean(itemNames[0], String.valueOf(MoneyUtil.get_ItemDecimals_money(dataBean.getFoodAmount()))));
            businessBeans.add(new BusinessBean(itemNames[1], String.valueOf(MoneyUtil.get_ItemDecimals_money(dataBean.getDisAmount()))));
            businessBeans.add(new BusinessBean(itemNames[2], String.valueOf(MoneyUtil.get_ItemDecimals_money(dataBean.getSeramount()))));
            businessBeans.add(new BusinessBean(itemNames[3], String.valueOf(MoneyUtil.get_ItemDecimals_money(dataBean.getRoundAmount()))));
            businessBeans.add(new BusinessBean(itemNames[4], String.valueOf(MoneyUtil.get_ItemDecimals_money(dataBean.getSaleAmount()))));
            businessBeans.add(new BusinessBean(itemNames[5], String.valueOf(MoneyUtil.get_ItemDecimals_money(dataBean.getTisAmount()))));
            businessBeans.add(new BusinessBean(itemNames[6], String.valueOf(MoneyUtil.get_ItemDecimals_money(dataBean.getBoxAmount()))));
            businessBeans.add(new BusinessBean(itemNames[7], String.valueOf(MoneyUtil.get_ItemDecimals_money(dataBean.getDelAmount()))));
            double netProfit = MoneyUtil.sub(dataBean.getFoodAmount(), dataBean.getDisAmount(), dataBean.getSeramount(), dataBean.getRoundAmount(), dataBean.getSaleAmount(), dataBean.getTisAmount(), dataBean.getBoxAmount(), dataBean.getDelAmount());
            businessBeans.add(new BusinessBean(itemNames[8], String.valueOf(MoneyUtil.get_ItemDecimals_money(netProfit))));
        } else {
            //為空，全部顯示0
            for (String itemName : itemNames) {
                businessBeans.add(new BusinessBean(itemName, String.valueOf(0)));
            }
        }
        mRootView.loadDaySalesReport(businessBeans);
        mRootView.loadBillReport(dataBean);
    }


//    private String[] itemNames = new String[]{"項目銷售總金額($)", "折扣($)", "服務費($)", "賬單小數($)", "簽單($)", "營業金額淨值($)", "貼士($)", "堂食總金額數($)", "外賣總金額數($)", "單數", "平均每單消費金額($)", "人數", "平均每人消費金額($)", "送貨費($)", "餐盒費($)"};
//
//    private void loadAdapterInfo(BusinessDetailsBean.DataBean dataBean) {
//        //底部信息默認顯示今天的數據
//        List<BusinessBean> businessBeans = new ArrayList<>();
//        if (dataBean != null) {
//            businessBeans.add(new BusinessBean(itemNames[0], String.valueOf(dataBean.getPrices())));
//            businessBeans.add(new BusinessBean(itemNames[1], String.valueOf(dataBean.getDisamount())));
//            businessBeans.add(new BusinessBean(itemNames[2], String.valueOf(dataBean.getScamount())));
//            businessBeans.add(new BusinessBean(itemNames[3], String.valueOf(dataBean.getRounding())));
//            businessBeans.add(new BusinessBean(itemNames[4], String.valueOf(dataBean.getPayamount())));
//            //折扣+賬單小數+簽單
//            double expenditure = MoneyUtil.sum(MoneyUtil.sum(dataBean.getDisamount(), dataBean.getRounding()), dataBean.getPayamount());
//            //服務費和貼士
//            double extraIncome = MoneyUtil.sum(dataBean.getScamount(), dataBean.getTipsPrice());
//            //"營業金額淨值"為項目銷售總金額-折扣+服務費-賬單小數-簽單
//            businessBeans.add(new BusinessBean(itemNames[5], String.valueOf(MoneyUtil.sub(MoneyUtil.sum(dataBean.getPrices(), extraIncome), Math.abs(expenditure)))));
//            businessBeans.add(new BusinessBean(itemNames[6], String.valueOf(dataBean.getTipsPrice())));
//            businessBeans.add(new BusinessBean(itemNames[7], String.valueOf(dataBean.getTotalMeals())));
//            businessBeans.add(new BusinessBean(itemNames[8], String.valueOf(dataBean.getTakeawayTotal())));
//            businessBeans.add(new BusinessBean(itemNames[9], String.valueOf(dataBean.getNum())));//單數
//            BigDecimal averageBill = new BigDecimal(0);
//            if (dataBean.getNum() != 0) {
//                averageBill = MoneyUtil.divide(dataBean.getPrices(), dataBean.getNum());
//            }
//            businessBeans.add(new BusinessBean(itemNames[10], String.valueOf(averageBill)));//"平均每單"
//            businessBeans.add(new BusinessBean(itemNames[11], String.valueOf(dataBean.getPerson())));//人數
//            BigDecimal averageConsumption = new BigDecimal(0);
//            if (dataBean.getPerson() != 0) {
//                averageConsumption = MoneyUtil.divide(dataBean.getPrices(), dataBean.getPerson());
//            }
//            businessBeans.add(new BusinessBean(itemNames[12], String.valueOf(averageConsumption)));//平均每人
//
//            businessBeans.add(new BusinessBean(itemNames[13], String.valueOf(dataBean.getDeliveryCharge())));
//            businessBeans.add(new BusinessBean(itemNames[14], String.valueOf(dataBean.getTotalLunchbox())));
//        } else {
//            //為空，全部顯示0
//            for (String itemName : itemNames) {
//                businessBeans.add(new BusinessBean(itemName, String.valueOf(0)));
//            }
//        }
//        mRootView.loadDaySalesReport(businessBeans);
//    }
}
