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.app.GsaCloudApplication;
import com.gingersoft.gsa.cloud.common.bean.BaseResult;
import com.gingersoft.gsa.cloud.common.constans.AppConstans;
import com.gingersoft.gsa.cloud.common.core.login.LoginBean;
import com.gingersoft.gsa.cloud.common.core.user.UserContext;
import com.gingersoft.gsa.cloud.common.core.user.state.LoginedState;
import com.gingersoft.gsa.cloud.common.utils.JsonUtils;
import com.gingersoft.gsa.cloud.common.utils.gson.GsonUtils;
import com.gingersoft.gsa.cloud.common.utils.okhttpUtils.OkHttp3Utils;
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.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<BaseResult>(mErrorHandler) {

                    @Override
                    public void onNext(@NonNull BaseResult info) {
                        if (info.isSuccess()) {
                            LoginBean loginBean = JsonUtils.parseObject(info.getData(), LoginBean.class);
                            if (loginBean != null) {
                                UserContext.newInstance().setState(new LoginedState());
                                mRootView.showMessage("登陸成功");
                                mRootView.loginSuccess(loginBean);
                            }
                        } else {
                            mRootView.showMessage(info.getErrMsg());
                            UserContext.newInstance().logOut();
                        }
                    }

                    @Override
                    public void onError(Throwable t) {
                        super.onError(t);
                        UserContext.newInstance().logOut();
                        OkHttp3Utils.noticePersonnel(AppConstans.RP_LOGIN_ERROR, "登陸報錯：" + t.getMessage());
                        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<BaseResult>(mErrorHandler) {
                    @Override
                    public void onNext(BaseResult 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();
                    }
                });
    }
}
