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

import android.app.Application;
import android.os.CountDownTimer;
import android.text.TextUtils;

import com.gingersoft.gsa.cloud.common.core.restaurant.RestaurantInfoManager;
import com.gingersoft.gsa.cloud.common.bean.BaseResult;
import com.gingersoft.gsa.cloud.common.core.table.TableArea;
import com.gingersoft.gsa.cloud.common.core.table.TableManagerItem;
import com.gingersoft.gsa.cloud.common.utils.JsonUtils;
import com.gingersoft.gsa.cloud.common.utils.gson.GsonUtils;
import com.gingersoft.gsa.cloud.common.utils.log.LogUtil;
import com.gingersoft.gsa.cloud.common.constans.GoldConstants;
import com.gingersoft.gsa.cloud.manager.mvp.contract.TableManageContract;
import com.gingersoft.gsa.cloud.manager.mvp.model.bean.request.AreaRequest;
import com.gingersoft.gsa.cloud.manager.mvp.model.bean.request.TableRequest;
import com.gingersoft.gsa.cloud.manager.mvp.ui.activity.TableManageActivity;
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.scwang.smartrefresh.layout.api.RefreshLayout;

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


/**
 * ================================================
 * Description:
 * <p>
 * Created by MVPArmsTemplate on 05/13/2020 14:47
 * <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 TableManagePresenter extends BasePresenter<TableManageContract.Model, TableManageContract.View> {
    @Inject
    RxErrorHandler mErrorHandler;
    @Inject
    Application mApplication;
    @Inject
    ImageLoader mImageLoader;
    @Inject
    AppManager mAppManager;

    private GetTableTimer tableTimer;
    private Disposable mGetTablesDataDisposable;

    @Inject
    public TableManagePresenter(TableManageContract.Model model, TableManageContract.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 addArea(AreaRequest.Add request) {
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), GsonUtils.GsonString(request));
        String json = GsonUtils.GsonString(request);
        mModel.addArea(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<BaseResult>(mErrorHandler) {

                    @Override
                    public void onComplete() {
                        super.onComplete();
                        mRootView.hideLoading();
                    }

                    @Override
                    public void onError(Throwable t) {
                        super.onError(t);
                        mRootView.hideLoading();
                    }

                    @Override
                    public void onNext(@NonNull BaseResult info) {
                        if (info != null && info.isSuccess()) {
                            if (info.getData() != null) {
                                List<TableArea> tableAreas = JsonUtils.parseArray(info.getData(), TableArea.class);
                                mRootView.queryAreasSuccess(tableAreas, TableManageActivity.ADD_AREA_SUCCESS);
                            }
                        } else {
                            if (!TextUtils.isEmpty(info.getErrMsg())) {
                                mRootView.showMessage(info.getErrMsg());
                            } else {
                                mRootView.showMessage("添加失敗");
                            }
                        }
                    }
                });
    }

    public void deleteArea(String ids) {
        RequestBody requestBody = new FormBody.Builder()
                .add("id", ids)
                .build();
        mModel.deleteArea(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<BaseResult>(mErrorHandler) {

                    @Override
                    public void onComplete() {
                        super.onComplete();
                        mRootView.hideLoading();
                    }

                    @Override
                    public void onError(Throwable t) {
                        super.onError(t);
                        mRootView.hideLoading();
                    }

                    @Override
                    public void onNext(@NonNull BaseResult info) {
                        if (info != null && info.isSuccess()) {
                            if (info.getData() != null) {
                                List<TableArea> tableAreas = JsonUtils.parseArray(info.getData(), TableArea.class);
                                mRootView.queryAreasSuccess(tableAreas, TableManageActivity.DELETE_AREA_SUCCESS);
                            }
                        } else {
                            if (!TextUtils.isEmpty(info.getErrMsg())) {
                                mRootView.showMessage(info.getErrMsg());
                            } else {
                                mRootView.showMessage("刪除失敗");
                            }
                        }
                    }
                });
    }

    public void updateArea(AreaRequest.Update request) {
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), GsonUtils.GsonString(request));
        String json = GsonUtils.GsonString(request);
        mModel.updateArea(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<BaseResult>(mErrorHandler) {

                    @Override
                    public void onComplete() {
                        super.onComplete();
                        mRootView.hideLoading();
                    }

                    @Override
                    public void onError(Throwable t) {
                        super.onError(t);
                        mRootView.hideLoading();
                    }

                    @Override
                    public void onNext(@NonNull BaseResult info) {
                        if (info != null && info.isSuccess()) {
                            if (info.getData() != null) {
                                List<TableArea> tableAreas = JsonUtils.parseArray(info.getData(), TableArea.class);
                                mRootView.queryAreasSuccess(tableAreas, TableManageActivity.UPDATE_AREA_SUCCESS);
                            }
                        } else {
                            if (!TextUtils.isEmpty(info.getErrMsg())) {
                                mRootView.showMessage(info.getErrMsg());
                            } else {
                                mRootView.showMessage("添加失敗");
                            }
                        }
                    }
                });
    }

    public void queryAreas(RefreshLayout refreshLayout, boolean showLoading) {
        mModel.queryAreas()
                .subscribeOn(Schedulers.io())
                .doOnSubscribe(disposable -> {
                    if (refreshLayout == null && showLoading) {
                        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) {
                                List<TableArea> tableAreas = JsonUtils.parseArray(info.getData(), TableArea.class);
                                if (tableAreas.size() > 0) {
                                    mRootView.queryAreasSuccess(tableAreas, TableManageActivity.QUERY_AREA_SUCCESS);
                                } else {
                                    mRootView.showEmptyView(true, 0, null);
                                }
                            } else {
                                mRootView.showEmptyView(true, 0, null);
                            }
                        } else {
                            mRootView.showEmptyView(false, 0, null);
//                            mRootView.showMessage("查詢失敗");
                        }
                    }

                    @Override
                    public void onComplete() {
                        super.onComplete();
                        resetRefreshLayout();
                    }

                    @Override
                    public void onError(Throwable t) {
                        super.onError(t);
                        mRootView.showEmptyView(false, 0, t);
                        resetRefreshLayout();
                    }

                    private void resetRefreshLayout() {
                        if (refreshLayout != null) {
                            refreshLayout.finishRefresh();
                            refreshLayout.resetNoMoreData();
                        }
                    }
                });
    }


    public void addTable(TableRequest.Add request) {
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), GsonUtils.GsonString(request));
        String json = GsonUtils.GsonString(request);
        mModel.addTable(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<BaseResult>(mErrorHandler) {

                    @Override
                    public void onComplete() {
                        super.onComplete();
                        mRootView.hideLoading();
                    }

                    @Override
                    public void onError(Throwable t) {
                        super.onError(t);
                        mRootView.hideLoading();
                    }

                    @Override
                    public void onNext(@NonNull BaseResult info) {
                        if (info != null && info.isSuccess()) {
                            if (info.getData() != null) {
                                List<TableManagerItem> tableItems = JsonUtils.parseArray(info.getData(), TableManagerItem.class);
                                mRootView.queryTablesSuccess(tableItems, TableManageActivity.ADD_TABLE_SUCCESS);
                            }
                        } else {
                            if (!TextUtils.isEmpty(info.getErrMsg())) {
                                mRootView.showMessage(info.getErrMsg());
                            } else {
                                mRootView.showMessage("添加失敗");
                            }
                        }
                    }
                });
    }

    public void deleteTable(String ids) {
        RequestBody requestBody = new FormBody.Builder()
                .add("id", ids)
                .build();
        mModel.deleteTable(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<BaseResult>(mErrorHandler) {

                    @Override
                    public void onComplete() {
                        super.onComplete();
                        mRootView.hideLoading();
                    }

                    @Override
                    public void onError(Throwable t) {
                        super.onError(t);
                        mRootView.hideLoading();
                    }

                    @Override
                    public void onNext(@NonNull BaseResult info) {
                        if (info != null && info.isSuccess()) {
                            if (info.getData() != null) {
                                List<TableManagerItem> tableItems = JsonUtils.parseArray(info.getData(), TableManagerItem.class);
                                mRootView.queryTablesSuccess(tableItems, TableManageActivity.DELETE_TABLE_SUCCESS);
                            }
                        } else {
                            if (!TextUtils.isEmpty(info.getErrMsg())) {
                                mRootView.showMessage(info.getErrMsg());
                            } else {
                                mRootView.showMessage("刪除失敗");
                            }
                        }
                    }
                });
    }

    public void updateTable(TableRequest.Update request) {
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), GsonUtils.GsonString(request));
        String json = GsonUtils.GsonString(request);
        mModel.updateTable(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<BaseResult>(mErrorHandler) {

                    @Override
                    public void onComplete() {
                        super.onComplete();
                        mRootView.hideLoading();
                    }

                    @Override
                    public void onError(Throwable t) {
                        super.onError(t);
                        mRootView.hideLoading();
                    }

                    @Override
                    public void onNext(@NonNull BaseResult info) {
                        if (info != null && info.isSuccess()) {
                            if (info.getData() != null) {
                                List<TableManagerItem> tableItems = JsonUtils.parseArray(info.getData(), TableManagerItem.class);
                                if (tableItems.size() > 0) {
                                    mRootView.queryTablesSuccess(tableItems, TableManageActivity.UPDATE_TABLE_SUCCESS);
                                } else {
                                }
                            } else {
                            }
                        } else {
                            if (!TextUtils.isEmpty(info.getErrMsg())) {
                                mRootView.showMessage(info.getErrMsg());
                            } else {
                                mRootView.showMessage("更新失敗");
                            }
                        }
                    }
                });
    }

    public void queryTables(RefreshLayout refreshLayout, boolean showLoading) {
        mModel.queryTables()
                .subscribeOn(Schedulers.io())
                .doOnSubscribe(disposable -> {
                    if (refreshLayout == null && showLoading) {
                        mRootView.showLoading(null);
                    }
                })
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .doAfterTerminate(() -> mRootView.hideLoading())
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .subscribe(new ErrorHandleSubscriber<BaseResult>(mErrorHandler) {

                    @Override
                    public void onSubscribe(Disposable d) {
                        super.onSubscribe(d);
                        mGetTablesDataDisposable = d;
                    }

                    @Override
                    public void onNext(@NonNull BaseResult info) {
                        if (info != null && info.isSuccess()) {
                            if (info.getData() != null) {
                                List<TableManagerItem> tableItems = JsonUtils.parseArray(info.getData(), TableManagerItem.class);
                                mRootView.queryTablesSuccess(tableItems, TableManageActivity.QUERY_TABLE_SUCCESS);
                                if (tableItems.size() > 0) {
                                } else {
                                    mRootView.showEmptyView(true, 0, null);
                                }
                            } else {
                                mRootView.showEmptyView(true, 0, null);
                            }
                        } else {
                            mRootView.showEmptyView(false, 0, null);
//                            mRootView.showMessage("查詢失敗");
                        }
                    }

                    @Override
                    public void onComplete() {
                        super.onComplete();
                        resetRefreshLayout();
                    }

                    @Override
                    public void onError(Throwable t) {
                        super.onError(t);
                        mRootView.showEmptyView(false, 0, t);
                        resetRefreshLayout();
                    }

                    private void resetRefreshLayout() {
                        if (refreshLayout != null) {
                            refreshLayout.finishRefresh();
                            refreshLayout.resetNoMoreData();
                        }
                    }
                });
    }

    public void changeAreaSort(String ids) {
        RequestBody requestBody = new FormBody.Builder()
                .add("restaurantId", String.valueOf(RestaurantInfoManager.newInstance().getRestaurantId()))
                .add("ids", ids)
                .build();
        LogUtil.d(TAG, "changeAreaSort   " + " ids:" + ids);
        mModel.changeAreaSort(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<BaseResult>(mErrorHandler) {

                    @Override
                    public void onComplete() {
                        super.onComplete();
                        mRootView.hideLoading();
                    }

                    @Override
                    public void onError(Throwable t) {
                        super.onError(t);
                        mRootView.hideLoading();
                    }

                    @Override
                    public void onNext(@NonNull BaseResult info) {
                        if (info != null && info.isSuccess()) {
                            if (info.getData() != null) {
                                List<TableArea> tableAreas = JsonUtils.parseArray(info.getData(), TableArea.class);
                                if (tableAreas.size() > 0) {
                                    mRootView.queryAreasSuccess(tableAreas, TableManageActivity.CHANGE_AREA_SORT);
                                } else {
                                    mRootView.showEmptyView(true, 0, null);
                                }
                            } else {
                                mRootView.showEmptyView(true, 0, null);
                            }
                        } else {
                            if (!TextUtils.isEmpty(info.getErrMsg())) {
                                mRootView.showMessage(info.getErrMsg());
                            } else {
                                mRootView.showMessage("更新失敗");
                            }
                        }
                    }
                });
    }

    public void changeTableSort(String ids) {
        RequestBody requestBody = new FormBody.Builder()
                .add("restaurantId", String.valueOf(RestaurantInfoManager.newInstance().getRestaurantId()))
                .add("ids", ids)
                .build();
        LogUtil.d(TAG, "changeTableSort   " + " ids:" + ids);
        mModel.changeTableSort(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<BaseResult>(mErrorHandler) {

                    @Override
                    public void onComplete() {
                        super.onComplete();
                        mRootView.hideLoading();
                    }

                    @Override
                    public void onError(Throwable t) {
                        super.onError(t);
                        mRootView.hideLoading();
                    }

                    @Override
                    public void onNext(@NonNull BaseResult info) {
                        if (info != null && info.isSuccess()) {
                            if (info.getData() != null) {
                                List<TableManagerItem> tableItems = JsonUtils.parseArray(info.getData(), TableManagerItem.class);
                                if (tableItems.size() > 0) {
                                    mRootView.queryTablesSuccess(tableItems, TableManageActivity.CHANGE_TABLE_SORT);
                                } else {
                                    mRootView.showEmptyView(true, 0, null);
                                }
                            } else {
                                mRootView.showEmptyView(true, 0, null);
                            }
                        } else {
                            if (!TextUtils.isEmpty(info.getErrMsg())) {
                                mRootView.showMessage(info.getErrMsg());
                            } else {
                                mRootView.showMessage("更新失敗");
                            }
                        }
                    }
                });
    }

    public void updateTableServiceCharge(List<TableRequest.UpdateServiceCharge> request) {
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), GsonUtils.GsonString(request));
        String json = GsonUtils.GsonString(request);
        mModel.updateTableServiceCharge(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<BaseResult>(mErrorHandler) {

                    @Override
                    public void onNext(@NonNull BaseResult info) {
                        if (info != null && info.isSuccess()) {
                            if (info.getData() != null) {
                                List<TableManagerItem> tableItems = JsonUtils.parseArray(info.getData(), TableManagerItem.class);
                                if (tableItems.size() > 0) {
                                    mRootView.queryTablesSuccess(tableItems, TableManageActivity.UPDATE_TABLE_SERVICE_CHARGE);
                                } else {
                                    mRootView.showEmptyView(true, 0, null);
                                }
                            } else {
                                mRootView.showEmptyView(true, 0, null);
                            }
                        } else {
                            if (!TextUtils.isEmpty(info.getErrMsg())) {
                                mRootView.showMessage(info.getErrMsg());
                            } else {
                                mRootView.showMessage("更新失敗");
                            }
                        }
                    }
                });
    }


    public void initGetTableTimer() {
        if (tableTimer == null) {
            tableTimer = new GetTableTimer(GoldConstants.refreshTime * 1000, GoldConstants.refreshTime * 1000);
        }
        TableManageActivity.isRefreshData = true;
        tableTimer.start();
    }

    public void startTableTimer() {
        if (tableTimer != null) {
            tableTimer.start();
        }
    }

    public void cancelTableTimer() {
        if (tableTimer != null) {
            tableTimer.cancel();
        }
    }

    /**
     * 计时器类 定時更新餐台数据
     */
    private class GetTableTimer extends CountDownTimer {

        public GetTableTimer(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);// 参数依次为总时长,和计时的时间间隔
        }

        @Override
        public void onFinish() {// 计时完毕时触发
            if (TableManageActivity.isRefreshData) {
                queryAreas(null, false);
                queryTables(null, false);
            }
            this.start();
        }

        @Override
        public void onTick(long millisUntilFinished) {// 计时过程显示
        }
    }


    public Disposable getGetTablesDataDisposable() {
        return mGetTablesDataDisposable;
    }


}
