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

import android.app.Activity;
import android.app.Application;
import android.content.Intent;

import com.gingersoft.gsa.cloud.base.application.GsaCloudApplication;
import com.gingersoft.gsa.cloud.base.utils.gson.GsonUtils;
import com.gingersoft.gsa.cloud.base.utils.okhttpUtils.OkHttp3Utils;
import com.gingersoft.gsa.cloud.base.utils.other.SPUtils;
import com.gingersoft.gsa.cloud.base.utils.other.TextUtil;
import com.gingersoft.gsa.cloud.bean.PublicBean;
import com.gingersoft.gsa.cloud.constans.AppConstans;
import com.gingersoft.gsa.cloud.constans.PrintConstans;
import com.gingersoft.gsa.cloud.login.mvp.bean.LoginLimitBean;
import com.gingersoft.gsa.cloud.login.mvp.contract.BaseLoginContract;
import com.gingersoft.gsa.cloud.login.mvp.ui.activity.mvp.ui.activity.LoginActivity;
import com.gingersoft.gsa.cloud.ui.bean.mode.BrandsBean;
import com.gingersoft.gsa.cloud.ui.bean.mode.LoginBean;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
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.DeviceUtils;
import com.jess.arms.utils.RxLifecycleUtils;

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;

@ActivityScope
public class BaseLoginPresenter<M extends BaseLoginContract.Model, V extends BaseLoginContract.View> extends BasePresenter<BaseLoginContract.Model, BaseLoginContract.View> {
    @Inject
    RxErrorHandler mErrorHandler;
    @Inject
    Application mApplication;
    @Inject
    ImageLoader mImageLoader;
    @Inject
    AppManager mAppManager;


    private Activity IAcitivity;

    @Inject
    public BaseLoginPresenter(BaseLoginContract.Model model, BaseLoginContract.View rootView) {
        super(model, rootView);
        IAcitivity = (Activity) rootView;
    }

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

    public void login(String account, String pwd) {
        if (account.equals("888888") && pwd.equals("cc81081168")) {
            mRootView.startToSwitchServer();
            return;
        }
        if (!DeviceUtils.netIsConnected(GsaCloudApplication.getAppContext())) {
            //防止沒有網絡 請求登錄接口卡在歡迎頁
            if (IAcitivity instanceof LoginActivity) {
            } else {
                mRootView.launchActivity(new Intent(IAcitivity, LoginActivity.class));
                return;
            }
        }
        RequestBody requestBody = new FormBody.Builder()
                .add("userName", account.trim() + "")
                .add("passWord", pwd.trim() + "")
                .build();
        mModel.login(requestBody)
                .subscribeOn(Schedulers.io())
                .subscribeOn(AndroidSchedulers.mainThread())
                .doOnSubscribe(disposable -> mRootView.showLoading("登錄中..."))
                .observeOn(AndroidSchedulers.mainThread())
                .doAfterTerminate(() -> mRootView.hideLoading())
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .subscribe(new ErrorHandleSubscriber<LoginBean>(mErrorHandler) {

                    @Override
                    public void onNext(@NonNull LoginBean info) {
                        if (info.isSuccess()) {
                            GsaCloudApplication.isLogin = true;
                            SPUtils.put(GsaCloudApplication.getAppContext(), PrintConstans.IS_LOGIN, true);
                            GsaCloudApplication.userName = info.getData().getUser().getUserName();
                            mRootView.showMessage("登陸成功");
                            mRootView.loginSuccess(info);
                        } else {
                            GsaCloudApplication.isLogin = false;
                            mRootView.showMessage(info.getErrMsg());
                            if (IAcitivity instanceof LoginActivity) {

                            } else {
                                mRootView.launchActivity(new Intent(IAcitivity, LoginActivity.class));
                            }
                        }
                    }

                    @Override
                    public void onError(Throwable t) {
                        super.onError(t);
                        OkHttp3Utils.noticePersonnel(AppConstans.RP_LOGIN_ERROR, "登陸報錯：" + t.getMessage());
                        if (IAcitivity instanceof LoginActivity) {
                        } else {
                            mRootView.launchActivity(new Intent(IAcitivity, LoginActivity.class));
                        }
                    }
                });
    }


    public void getRestaurantList() {
        mModel.getRestaurantList()
                .subscribeOn(Schedulers.io())
                .subscribeOn(AndroidSchedulers.mainThread())
                .doOnSubscribe(disposable -> mRootView.showLoading("獲取餐廳信息中..."))
                .observeOn(AndroidSchedulers.mainThread())
                .doAfterTerminate(() -> mRootView.hideLoading())
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .subscribe(new ErrorHandleSubscriber<BrandsBean>(mErrorHandler) {

                    @Override
                    public void onNext(@NonNull BrandsBean info) {
                        if (info != null) {
                            if (TextUtil.isNotEmptyOrNullOrUndefined(info.getMessage())) {
                                mRootView.showMessage(info.getMessage());
                            }
                            mRootView.saveRestaurantListInfo(info.getData());
                        } else {
                            mRootView.saveRestaurantListInfo(null);
                        }
                    }

                    @Override
                    public void onError(Throwable t) {
                        super.onError(t);
                        if (IAcitivity instanceof LoginActivity) {
                        } else {
                            mRootView.launchActivity(new Intent(IAcitivity, LoginActivity.class));
                        }
                    }
                });
    }

    /**
     * @param restaurantId 餐廳ID
     * @param isDownload   是否去下載頁面
     */
    public void getLoginLimit(int restaurantId, boolean isDownload) {
        mModel.getLoginLimit(restaurantId)
                .subscribeOn(Schedulers.io())
                .subscribeOn(AndroidSchedulers.mainThread())
                .doOnSubscribe(disposable -> mRootView.showLoading("獲取登錄人數中..."))
                .observeOn(AndroidSchedulers.mainThread())
                .doAfterTerminate(() -> mRootView.hideLoading())
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .subscribe(new ErrorHandleSubscriber<PublicBean>(mErrorHandler) {
                    @Override
                    public void onNext(PublicBean s) {
                        if (s != null && s.isSuccess()) {
                            List<LoginLimitBean> loginLimitBeans = new Gson().fromJson(GsonUtils.GsonString(s.getData()), new TypeToken<List<LoginLimitBean>>() {
                            }.getType());
//                            List<LoginLimitBean> logins = GsonUtils.GsonToList("", LoginLimitBean.class);
                            if (loginLimitBeans == null || loginLimitBeans.size() <= 0) {
                                if (isDownload) {
                                    mRootView.jumpDownloadActivity();
                                } else {
                                    mRootView.jumpMainActivity();
                                }
                            } else {
                                mRootView.showMessage("登錄人數達到上限");
                                //已達上限，彈出彈窗
                                mRootView.showLoginLimit(loginLimitBeans);
                            }
                        } else {
                            mRootView.showMessage("獲取登陸人數失敗");
                            mRootView.launchActivity(new Intent(IAcitivity, LoginActivity.class));
                        }
                    }

                    @Override
                    public void onError(Throwable t) {
                        super.onError(t);
                        mRootView.showLoginLimit(null);
//                        mRootView.launchActivity(new Intent(IAcitivity, LoginActivity.class));
//                        mRootView.jumpDownloadActivity();
                    }
                });
    }

    /**
     * 踢出用戶
     */
    public void loginOut(int userId) {
        RequestBody requestBody = new FormBody.Builder()
                .add("type", "2")
                .build();
        mModel.loginOut(userId, 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<Object>(mErrorHandler) {

                    @Override
                    public void onNext(@NonNull Object info) {
                        mRootView.kickOut();
                    }

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