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

import android.app.Application;

import com.gingersoft.gsa.cloud.base.application.GsaCloudApplication;
import com.gingersoft.gsa.cloud.main.R;
import com.gingersoft.gsa.cloud.main.mvp.contract.SettlementReportContract;
import com.gingersoft.gsa.cloud.main.mvp.model.bean.SendSettlement;
import com.gingersoft.gsa.cloud.main.mvp.model.bean.SettlementReport;
import com.gingersoft.gsa.cloud.main.mvp.model.bean.SettlementReportItem;
import com.gingersoft.gsa.cloud.main.mvp.model.bean.SettlementReportItem5;
import com.gingersoft.gsa.cloud.main.mvp.ui.activity.SettlementReportActivity;
import com.gingersoft.gsa.cloud.main.mvp.ui.adapter.SettlementReportItem5Adapter;
import com.gingersoft.gsa.cloud.main.mvp.ui.adapter.SettlementReportItemAdapter;
import com.jess.arms.di.scope.ActivityScope;
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 com.qmuiteam.qmui.widget.dialog.QMUIDialog;
import com.qmuiteam.qmui.widget.dialog.QMUIDialogAction;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import me.jessyan.rxerrorhandler.core.RxErrorHandler;
import me.jessyan.rxerrorhandler.handler.ErrorHandleSubscriber;
import okhttp3.FormBody;
import okhttp3.RequestBody;


/**
 * ================================================
 * Description:
 * <p>
 * Created by MVPArmsTemplate on 03/04/2020 21:36
 * <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>
 * ================================================
 */
@ActivityScope
public class SettlementReportPresenter extends BasePresenter<SettlementReportContract.Model, SettlementReportContract.View> {
    @Inject
    RxErrorHandler mErrorHandler;
    @Inject
    Application mApplication;
    @Inject
    ImageLoader mImageLoader;
    @Inject
    AppManager mAppManager;

    private SettlementReportActivity IActivity;
    private SettlementReportItemAdapter mSettlementReportItemAdapter;
    private List<SettlementReportItem> mSettlementReportItemList= new ArrayList<>();

    private SettlementReportItem5Adapter mSettlementReportItem5Adapter;
    private List<SettlementReportItem5> mSettlementReportItem5List= new ArrayList<>();

    @Inject
    public SettlementReportPresenter(SettlementReportContract.Model model, SettlementReportContract.View rootView) {
        super(model, rootView);
        this.IActivity = (SettlementReportActivity) rootView;
    }

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

    public void initAdapter() {
        if (mSettlementReportItemAdapter == null) {
            mSettlementReportItemAdapter = new SettlementReportItemAdapter(IActivity, mSettlementReportItemList);
            mRootView.setSettlementReportItemAdapter(mSettlementReportItemAdapter);
        }
        if (mSettlementReportItem5Adapter == null) {
            mSettlementReportItem5Adapter = new SettlementReportItem5Adapter(IActivity, mSettlementReportItem5List);
            mRootView.setSettlementReportItem5Adapter(mSettlementReportItem5Adapter);
        }
    }

    public void notifyReportItemAdapter(List<SettlementReportItem> settlementReportItems) {
        mSettlementReportItemList.clear();
        mSettlementReportItemList.addAll(settlementReportItems);
        mSettlementReportItemAdapter.notifyDataSetChanged();
    }

    public void notifyReportItem5Adapter(List<SettlementReportItem5> settlementReportItems) {
        mSettlementReportItem5List.clear();
        mSettlementReportItem5List.addAll(settlementReportItems);
        mSettlementReportItem5Adapter.notifyDataSetChanged();
    }

    public void sendSettlement() {
        int restaurantId = GsaCloudApplication.getRestaurantId(mApplication);
        RequestBody requestBody = new FormBody.Builder()
                .add("restaurantId", String.valueOf(restaurantId))
                .build();
        mModel.sendSettlement(requestBody)
                .subscribeOn(Schedulers.io())
                .doOnSubscribe(disposable -> mRootView.showLoading(null))
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .doAfterTerminate(() -> mRootView.hideLoading())
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .subscribe(new ErrorHandleSubscriber<SendSettlement>(mErrorHandler) {

                    @Override
                    public void onNext(@NonNull SendSettlement info) {
                        if (info != null && info.isSuccess()) {
                            SendSettlement.DataBean dataBean = info.getData();
                            if (dataBean != null) {
                                if (dataBean.getTable() == null || (dataBean.getTable() != null && dataBean.getTable().size() == 0)) {
                                    mRootView.showMessage("清機成功");
                                    //打印清機報表
                                    mRootView.printRepore();
                                } else {
                                    //還有檯未結賬
                                    showSettlementErrorDialog("仍有臺號未結賬，請先結賬;" + "\n" + getTables(dataBean.getTable()));
                                }
                            } else {
                                mRootView.showMessage("清機成功");
                                //打印清機報表
                                mRootView.printRepore();
                            }
                        } else {
                            mRootView.showMessage("清機失敗");
                        }
                    }
                });
    }

    public void getSettlementReport() {
        int restaurantId = GsaCloudApplication.getRestaurantId(mApplication);
        mModel.getSettlementReport(restaurantId)
                .subscribeOn(Schedulers.io())
                .doOnSubscribe(disposable -> mRootView.showLoading(null))
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .doAfterTerminate(() -> mRootView.hideLoading())
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .subscribe(new ErrorHandleSubscriber<SettlementReport>(mErrorHandler) {
                    //{"success":false,"errCode":"data_002","errMsg":"沒有查詢到數據","sysTime":1583573772290}
                    @Override
                    public void onSubscribe(Disposable d) {
                        super.onSubscribe(d);
                    }

                    @Override
                    public void onNext(@NonNull SettlementReport info) {
                        if (info != null && info.isSuccess()) {
                            if (info.getData() != null) {
                                mRootView.returnSettlementData(info.getData());
                            }
                        } else {
//                            mRootView.showMessage("獲取報表失敗");
                        }
                    }
                });
    }

    private void showSettlementErrorDialog(String msg) {
        new QMUIDialog.MessageDialogBuilder(IActivity)
                .setTitle("溫馨提示")
                .setMessage(msg)
                .addAction("確認", new QMUIDialogAction.ActionListener() {
                    @Override
                    public void onClick(QMUIDialog dialog, int index) {
                        dialog.dismiss();
                    }
                })
                .create(R.style.MyDialogTheme2).show();
    }


    /**
     * 拼接未結賬臺號
     *
     * @param tables
     * @return
     */
    private String getTables(List<String> tables) {
        StringBuilder builder = new StringBuilder();
        builder.append("table: ");
        for (String table : tables) {
            builder.append(table);
            builder.append(",");
        }
        String str = builder.toString();
        if (str.endsWith(",")) {
            str = str.substring(0, str.length() - 1);
        }
        return str;
    }
}
