package com.wd.workoffice.presenter;

import android.text.TextUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.wd.workoffice.app.BaseBean;
import com.wd.workoffice.bean.UserInfoBean;
import com.wd.workoffice.contract.LoginContract;
import com.wd.workoffice.model.LoginModel;
import com.wd.workoffice.retrofit.RtfUtils;
import com.wd.workoffice.retrofit.WorkObserver;
import com.wd.workoffice.util.UserKeeper;

import java.io.IOException;
import java.util.Map;

import flexible.xd.android_base.mvpBase.BasePresenter;
import flexible.xd.android_base.network.rtfhttp.Transformer;
import flexible.xd.android_base.utils.ToastUtil;
import io.reactivex.disposables.Disposable;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * author : flexible
 * email : lgd19940421@163.com
 * github: https://github.com/FlexibleXd
 **/
public class LoginPresenter extends BasePresenter<LoginContract.View, LoginContract.Model>
        implements LoginContract.Presenter {
    @Override
    public void getCode(String phone, String type) {
        mView.showLoading();
        mModel.getCode(phone, type).compose(Transformer.schedule()).subscribe(new WorkObserver<BaseBean>() {
            @Override
            public void doOnSubscribe(Disposable d) {
                mDisposable.add(d);
            }

            @Override
            public void onFail(String errorMsg) {
                mView.hideLoading();
                mView.onError(errorMsg);
            }

            @Override
            public void onSuccess(BaseBean data) {
                mView.hideLoading();
                if (data.getCode() != 0) {
                    mView.onError(data.getMessage());
                    return;
                }
                mView.codeSuccess();
            }
        });
    }

    @Override
    public void login(String type, Map<String, Object> param) {
        mView.showLoading();
        mModel.login(type, param).enqueue(new Callback<BaseBean>() {
            @Override
            public void onResponse(Call<BaseBean> call, Response<BaseBean> response) {
                if (response.isSuccessful()) {
                    BaseBean data = response.body();
                    mView.hideLoading();
                    if (data.getCode() != 0) {
                        mView.onError(data.getMessage());
                        return;
                    }
                    UserKeeper.getInstance().keepLoginInfo(JSON.toJSONString(data.getData()));
                    getUserInfo(JSON.toJSONString(data.getData()));
                } else {
                    ResponseBody data = response.errorBody();
                    mView.hideLoading();
                    try {
                        BaseBean backData = JSON.parseObject(data.string(), BaseBean.class);
                        if (backData.getCode() != 0) {
                            mView.onError(backData.getMessage());
                            return;
                        }
//                        UserKeeper.getInstance().keepLoginInfo(JSON.toJSONString(backData.getData()));
//                        mView.loginSuccess();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }

            }

            @Override
            public void onFailure(Call<BaseBean> call, Throwable t) {
                mView.hideLoading();
                mView.onError("获取失败，请检查网络状态");
            }
        });


//                compose(Transformer.schedule()).subscribe(new Observer<BaseBean>() {
//            @Override
//            public void onSubscribe(Disposable d) {
//                mDisposable.add(d);
//            }
//
//            @Override
//            public void onNext(BaseBean data) {
//
//            }
//
//            @Override
//            public void onError(Throwable e) {
//                mView.hideLoading();
//                if (e instanceof HttpException) {
//                    HttpException httpException = (HttpException) e;
//                    if (httpException.code() == 401) {//一般用于判断登录状态
//
//                    } else {
//                        mView.onError("服务器异常，请稍后再试");
//                    }
//                } else {
//                    mView.onError("获取失败，请检查网络状态");
//                }
//            }
//
//            @Override
//            public void onComplete() {
//            }
//
//        });
    }

    private void getUserInfo(String loginInfo) {
        RtfUtils.getRtf().userInfo().compose(Transformer.schedule()).subscribe(new WorkObserver<BaseBean>() {
            @Override
            public void doOnSubscribe(Disposable d) {
            }

            @Override
            public void onFail(String errorMsg) {
                UserKeeper.getInstance().clearUserInfo();
            }

            @Override
            public void onSuccess(BaseBean data) {
                if (data.getCode() != 0) {
                    return;
                }
                JSONObject userData = JSON.parseObject(data.getData().toString());
                if (UserKeeper.getInstance().getMesLogin()&&
                        !TextUtils.equals(UserKeeper.getInstance().getMesErpId(),userData.getString("erpId"))){
                    ToastUtil.showShort("MES和BAT账号不属于同一个员工，请确认后在登录");
                    UserKeeper.getInstance().clearUserInfo();
                    return;
                }
                mView.loginSuccess();
                UserKeeper.getInstance().keepUserInfo(data.getData().toString());
            }
        });
    }

    @Override
    public LoginContract.Model bindModel() {
        return LoginModel.newInstance();
    }
}
