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

import android.app.Activity;
import android.app.Application;
import android.text.TextUtils;

import com.gingersoft.gsa.cloud.common.core.restaurant.ResturantInfoManager;
import com.gingersoft.gsa.cloud.common.bean.BaseResult;
import com.gingersoft.gsa.cloud.common.utils.JsonUtils;
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.common.core.settlement.SettlementReport;
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.gingersoft.gsa.cloud.common.ui.bean.view.SectionTextItem3;
import com.gingersoft.gsa.cloud.common.ui.bean.view.SectionTextItem5;
import com.gingersoft.gsa.cloud.common.ui.widget.dialog.CommonTipDialog;
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.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<SectionTextItem3> mSettlementReportItemList = new ArrayList<>();

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

    public SettlementReportItem5Adapter mPrintAdapter;

    @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);
        }
        if (mPrintAdapter == null) {
            mPrintAdapter = new SettlementReportItem5Adapter(IActivity, mSettlementReportItem5List, 24);
        }
    }

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

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

    public void sendSettlement(int type) {
        int restaurantId = ResturantInfoManager.newInstance().getRestaurantId();
        RequestBody requestBody;
        if (type != 0) {
            requestBody = new FormBody.Builder()
                    .add("restaurantId", String.valueOf(restaurantId))
                    .add("type", String.valueOf(type))
                    .build();
        } else {
            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 onComplete() {
                        super.onComplete();
                        IActivity.setType(0);
                    }

                    @Override
                    public void onError(Throwable t) {
                        super.onError(t);
                        IActivity.setType(0);
                    }

                    @Override
                    public void onNext(@NonNull SendSettlement info) {
                        if (info != null && info.isSuccess()) {

                            SendSettlement.DataBean dataBean = info.getData();

                            if (dataBean != null
                                    && !TextUtils.isEmpty(dataBean.getErrCode())
                                    && dataBean.getErrCode().equals("restaurant.operation.0005")) {

                                //跨天清機提示
                                mRootView.showCrossDaysLayout(true);

                                if (dataBean.getDateNum() != null) {
                                    mRootView.setOrderConditionList(info.getData().getDateNum(), dataBean.getType1(), dataBean.getType2(), dataBean.getType3());
                                }
                            } else {
                                if (dataBean != null) {
                                    if (dataBean.getTable() == null || (dataBean.getTable() != null && dataBean.getTable().size() == 0)) {
                                        mRootView.showCrossDaysLayout(false);
                                        mRootView.showMessage("清機成功");
                                        //打印清機報表
                                        mRootView.printRepore();
                                    } else {
                                        //還有檯未結賬
                                        showSettlementErrorDialog("仍有臺號未結賬，請先結賬;" + "\n" + getTables(dataBean.getTable()));
                                    }
                                } else {
                                    mRootView.showCrossDaysLayout(false);
                                    mRootView.showMessage("清機成功");
                                    //打印清機報表
                                    mRootView.printRepore();
                                }
                            }
                        } else if (info.getErrCode().equals("restaurant.operation.0003")) {
                            //一天多次清機提示
                            CommonTipDialog.showDoubtDialog(IActivity, "沒有訂單數據", SettlementReportPresenter.class, SettlementReportPresenter.this,
                                    "", null, null);
                        }
//                        else if (info.getErrCode().equals("restaurant.operation.0004")) {
//                            Class[] parameterTypes = {};
//                            Object[] parameters = {};
//                            CommonTipDialog.showDoubtDialog(IActivity, "仍有外送訂單未結賬,請先結賬!", SettlementReportPresenter.class, SettlementReportPresenter.this,
//                                    "", parameterTypes, parameters);
//                        }
                        else if (info.getErrCode().equals("restaurant.operation.0006")) {
                            //一天多次清機提示
//                            Class[] parameterTypes = {};
//                            Object[] parameters = {};
//                            CommonTipDialog.showDoubtDialog(IActivity, "今天已清機過,是否合併清機", SettlementReportPresenter.class, SettlementReportPresenter.this,
//                                    "sendSettlement", parameterTypes, parameters);
                            showMergeSettlementDialog(IActivity, "今天已清機過,是否合併清機");
                        } else {
                            if (!TextUtils.isEmpty(info.getErrMsg())) {
                                showSettlementErrorDialog(info.getErrMsg() + ",清機失敗");
                            } else {
                                mRootView.showMessage("清機失敗");
                            }
                        }
                    }
                });
    }

    public void getSettlementReport() {
        int restaurantId = ResturantInfoManager.newInstance().getRestaurantId();
        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<BaseResult>(mErrorHandler) {

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


    public void showMergeSettlementDialog(Activity context, String msg) {
        QMUIDialog.MessageDialogBuilder dialogBuilder = new QMUIDialog.MessageDialogBuilder(context);
        dialogBuilder.setTitleIcon(com.gingersoft.gsa.cloud.common.R.drawable.qmui_icon_dialog_doubt);
        dialogBuilder.setMessage(msg);
        dialogBuilder.setCancelable(true);
        dialogBuilder.addAction(com.gingersoft.gsa.cloud.common.R.drawable.shape_red_five_radius_bg, "是", QMUIDialogAction.ACTION_PROP_NEGATIVE, (dialog, index) -> {
            dialog.dismiss();
            sendSettlement(SettlementReportActivity.merge_settlement_type_2);
        });
        dialogBuilder.addAction(com.gingersoft.gsa.cloud.common.R.drawable.shape_3c_cancel_btn_bg, "否", (dialog, index) -> {
            dialog.dismiss();
            sendSettlement(SettlementReportActivity.merge_settlement_type_3);
        });
        dialogBuilder.create(com.gingersoft.gsa.cloud.common.R.style.MyDialogTheme2).show();
    }

    private void showSettlementErrorDialog(String msg) {
        new QMUIDialog.MessageDialogBuilder(IActivity)
                .setTitle("溫馨提示")
                .setTitleIcon(com.gingersoft.gsa.cloud.common.R.drawable.qmui_icon_dialog_doubt)
                .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;
    }
}
