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.model.bean.SendSettlement;
import com.gingersoft.gsa.cloud.main.mvp.model.bean.SettlementReportItem;
import com.gingersoft.gsa.cloud.main.mvp.ui.activity.SettlementReportActivity;
import com.gingersoft.gsa.cloud.main.mvp.ui.adapter.SettlementReportItemAdapter;
import com.jess.arms.integration.AppManager;
import com.jess.arms.di.scope.ActivityScope;
import com.jess.arms.mvp.BasePresenter;
import com.jess.arms.http.imageloader.ImageLoader;

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;
import okhttp3.FormBody;
import okhttp3.RequestBody;

import javax.inject.Inject;

import com.gingersoft.gsa.cloud.main.mvp.contract.SettlementReportContract;
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;


/**
 * ================================================
 * 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 reportItemAdapter;
    private List<SettlementReportItem> mList;

    @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 (reportItemAdapter == null) {
            mList = new ArrayList<>();
            reportItemAdapter = new SettlementReportItemAdapter(IActivity, mList);
            mRootView.setSettlementReportItemAdapter(reportItemAdapter);
        }
    }

    public void notifyDataSetChanged(List<SettlementReportItem> settlementReportItems) {
        mList.clear();
        mList.addAll(settlementReportItems);
        reportItemAdapter.notifyDataSetChanged();
    }

    public void sendSettlement() {
        int restaurantId = GsaCloudApplication.getRestaurantId(mApplication);
        RequestBody requestBody = new FormBody.Builder()
//                .add("openTime", "")
                .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().size() == 0) {
                                    mRootView.showMessage("清機成功");
                                } else {
                                    //還有檯未結賬
                                    showSettlementErrorDialog("仍有臺號未結賬，請先結賬;" + "\n" + getTables(dataBean.getTable()));
                                }
                            } else {
                                mRootView.showMessage("清機失敗");
                            }
                        } 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;
    }
}
