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

import android.app.Application;

import com.gingersoft.gsa.cloud.base.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.BusinessDetailsBean;
import com.gingersoft.gsa.cloud.main.mvp.model.bean.MainBusinessBean;
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.math.BigDecimal;
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("營業信息獲取失敗");
                        }
                    }
                });
    }

    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), 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)));//平均每人
        } else {
            //為空，全部顯示0
            for (String itemName : itemNames) {
                businessBeans.add(new BusinessBean(itemName, String.valueOf(0)));
            }
        }
        mRootView.loadAdapter(businessBeans);
    }
}
