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

import android.app.Application;

import com.gingersoft.gsa.cloud.base.utils.constans.HttpsConstans;
import com.gingersoft.gsa.cloud.base.utils.time.TimeUtils;
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.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.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.retrofiturlmanager.RetrofitUrlManager;
import me.jessyan.rxerrorhandler.core.RxErrorHandler;
import me.jessyan.rxerrorhandler.handler.ErrorHandleSubscriber;
import okhttp3.FormBody;
import okhttp3.RequestBody;


/**
 * ================================================
 * 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 getRestaurantBusinessInfo(String restaurantId, String startTime, String endTime) {
        RequestBody requestBody = new FormBody.Builder()
                .add("restaurantId", restaurantId)
                .add("startTime", startTime)//TimeUtils.getYesterdayTime(TimeUtils.DATE_FORMAT_DATE)
                .add("endTime", endTime)//TimeUtils.getCurrentTimeInString(TimeUtils.DATE_FORMAT_DATE)
                .build();
        mModel.getRestaurantBusinessInfo(requestBody)
                .subscribeOn(Schedulers.io())
                .doOnSubscribe(disposable -> mRootView.showLoading(""))
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .doAfterTerminate(() -> mRootView.hideLoading())
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .subscribe(new ErrorHandleSubscriber<HomeTurnoverBean>(mErrorHandler) {

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

                    @Override
                    public void onComplete() {
                        super.onComplete();
                        RetrofitUrlManager.getInstance().putDomain("common", HttpsConstans.ROOT_SERVER_ADDRESS_FORMAL);
                    }

                    @Override
                    public void onError(Throwable t) {
                        super.onError(t);
                        RetrofitUrlManager.getInstance().putDomain("common", HttpsConstans.ROOT_SERVER_ADDRESS_FORMAL);
                    }
                });
    }

    private String[] itemNames = new String[]{"項目銷售總金額", "折扣", "服務費", "賬單小數", "簽單", "營業金額淨值", "貼士", "堂食總數", "外賣總數", "單數", "平均每單", "人數", "平均每人"};

    private void loadAdapterInfo(Map<String, HomeTurnoverBean.DataBean> data) {
        HomeTurnoverBean.DataBean dataBean = data.get(TimeUtils.getOldDate(0));
        //底部信息默認顯示今天的數據
        List<BusinessBean> businessBeans = new ArrayList<>();
        if (dataBean != null) {
            businessBeans.add(new BusinessBean(itemNames[0], dataBean.getBusiness_amount()));
            businessBeans.add(new BusinessBean(itemNames[1], dataBean.getDiscount()));
            businessBeans.add(new BusinessBean(itemNames[2], dataBean.getServicecharge()));
            businessBeans.add(new BusinessBean(itemNames[3], dataBean.getBill_decimal()));
            businessBeans.add(new BusinessBean(itemNames[4], "簽單"));
            businessBeans.add(new BusinessBean(itemNames[5], "營業金額淨值"));
            businessBeans.add(new BusinessBean(itemNames[6], dataBean.getTipsAmount()));
            businessBeans.add(new BusinessBean(itemNames[7], dataBean.getBillNum_table()));
            businessBeans.add(new BusinessBean(itemNames[8], dataBean.getBillNum_Takeout()));
            businessBeans.add(new BusinessBean(itemNames[9], dataBean.getNumber_bill()));
            float averageBill = Float.parseFloat(dataBean.getBusiness_amount()) / Float.parseFloat(dataBean.getNumber_bill());
            businessBeans.add(new BusinessBean(itemNames[10], averageBill + ""));//"平均每單"
            businessBeans.add(new BusinessBean(itemNames[11], dataBean.getPeople()));//人數
            float averageConsumption = Float.parseFloat(dataBean.getBusiness_amount()) / Float.parseFloat(dataBean.getPeople());
            businessBeans.add(new BusinessBean(itemNames[12], averageConsumption + ""));//平均每人
        } else {
            //為空，全部顯示0
            for (int i = 0; i < itemNames.length; i++) {
                businessBeans.add(new BusinessBean(itemNames[i], "0"));
            }
        }
        mRootView.loadAdapter(businessBeans);
    }
}
