package com.casic.dcms.vm;

import android.content.Context;

import androidx.lifecycle.MutableLiveData;

import com.casic.dcms.model.ActionResultBean;
import com.casic.dcms.model.LoginResultBean;
import com.casic.dcms.model.UserBean;
import com.casic.dcms.utils.LocaleConstant;
import com.casic.dcms.utils.StringHelper;
import com.casic.dcms.utils.retrofit.RetrofitServiceManager;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.pengxh.androidx.lite.base.BaseViewModel;
import com.pengxh.androidx.lite.kit.StringKit;
import com.pengxh.androidx.lite.utils.LoadState;
import com.pengxh.androidx.lite.utils.ObserverSubscriber;
import com.pengxh.androidx.lite.utils.SaveKeyValues;

import java.io.IOException;

import okhttp3.ResponseBody;
import rx.Observable;

public class UserViewModel extends BaseViewModel {
    private static final String TAG = "UserViewModel";
    private final Gson gson = new Gson();
    public MutableLiveData<UserBean> userDataResult = new MutableLiveData<>();
    public MutableLiveData<LoginResultBean> loginResult = new MutableLiveData<>();
    public MutableLiveData<ActionResultBean> loginOutResult = new MutableLiveData<>();
    public MutableLiveData<ActionResultBean> changePwdResult = new MutableLiveData<>();
    public MutableLiveData<ActionResultBean> updateResult = new MutableLiveData<>();

    public void getUserData(Context context) {
        Observable<ResponseBody> observable = RetrofitServiceManager.getUserData();
        ObserverSubscriber.addSubscribe(observable, new ObserverSubscriber.OnObserverCallback() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onNext(ResponseBody responseBody) {
                try {
                    String response = responseBody.string();
                    int responseCode = StringHelper.getResponseCode(response);
                    if (responseCode == 200) {
                        UserBean userBean = gson.fromJson(response, new TypeToken<UserBean>() {
                        }.getType());
                        userDataResult.setValue(userBean);
                        SaveKeyValues.putValue(LocaleConstant.USER_DETAIL_MODEL, gson.toJson(userBean.getData()));
                    } else {
                        UserBean errorModel = new UserBean();
                        errorModel.setCode(responseCode);
                        userDataResult.setValue(errorModel);
                        //如果此次获取不到用户信息，那么就清空之前的用户缓存，然后让用户重新登录
                        SaveKeyValues.removeKey(LocaleConstant.USER_DETAIL_MODEL);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    public void login(Context context, String username, String key) {
        loadState.setValue(LoadState.Loading);
        Observable<ResponseBody> loginObservable = RetrofitServiceManager.login(username, key);
        ObserverSubscriber.addSubscribe(loginObservable, new ObserverSubscriber.OnObserverCallback() {
            @Override
            public void onCompleted() {
                loadState.setValue(LoadState.Success);
            }

            @Override
            public void onError(Throwable e) {
                loadState.setValue(LoadState.Fail);
            }

            @Override
            public void onNext(ResponseBody responseBody) {
                try {
                    String response = responseBody.string();
                    int responseCode = StringHelper.getResponseCode(response);
                    if (responseCode == 200) {
                        LoginResultBean loginResultBean = gson.fromJson(response, new TypeToken<LoginResultBean>() {
                        }.getType());
                        loginResult.setValue(loginResultBean);
                        loadState.setValue(LoadState.Success);
                    } else {
                        loadState.setValue(LoadState.Fail);
                        StringKit.show(context, StringHelper.getResponseMessage(response));
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    public void loginOut(Context context) {
        Observable<ResponseBody> observable = RetrofitServiceManager.loginOut();
        ObserverSubscriber.addSubscribe(observable, new ObserverSubscriber.OnObserverCallback() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onNext(ResponseBody responseBody) {
                try {
                    String response = responseBody.string();
                    int responseCode = StringHelper.getResponseCode(response);
                    if (responseCode == 200) {
                        ActionResultBean resultBean = gson.fromJson(response, new TypeToken<ActionResultBean>() {
                        }.getType());
                        loginOutResult.setValue(resultBean);
                    } else {
                        StringKit.show(context, StringHelper.getResponseMessage(response));
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    public void changePassword(Context context, String oldPwd, String newPwd) {
        loadState.setValue(LoadState.Loading);
        Observable<ResponseBody> observable = RetrofitServiceManager.getChangePasswordResult(oldPwd, newPwd);
        ObserverSubscriber.addSubscribe(observable, new ObserverSubscriber.OnObserverCallback() {
            @Override
            public void onCompleted() {
                loadState.setValue(LoadState.Success);
            }

            @Override
            public void onError(Throwable e) {
                loadState.setValue(LoadState.Fail);
            }

            @Override
            public void onNext(ResponseBody responseBody) {
                try {
                    String response = responseBody.string();
                    int responseCode = StringHelper.getResponseCode(response);
                    if (responseCode == 200) {
                        ActionResultBean actionResultBean = gson.fromJson(response, new TypeToken<ActionResultBean>() {
                        }.getType());
                        changePwdResult.setValue(actionResultBean);
                        loadState.setValue(LoadState.Success);
                    } else {
                        loadState.setValue(LoadState.Fail);
                        StringKit.show(context, StringHelper.getResponseMessage(response));
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    public void updateUserInfo(Context context, String id, String account, String name, String deptid, String roleid, String avatar, String sex, String birthday, String phone) {
        loadState.setValue(LoadState.Loading);
        Observable<ResponseBody> observable = RetrofitServiceManager.updateUserInfo(id, account, name, deptid, roleid, avatar, sex, birthday, phone);
        ObserverSubscriber.addSubscribe(observable, new ObserverSubscriber.OnObserverCallback() {
            @Override
            public void onCompleted() {
                loadState.setValue(LoadState.Success);
            }

            @Override
            public void onError(Throwable e) {
                loadState.setValue(LoadState.Fail);
            }

            @Override
            public void onNext(ResponseBody responseBody) {
                try {
                    String response = responseBody.string();
                    int responseCode = StringHelper.getResponseCode(response);
                    if (responseCode == 200) {
                        ActionResultBean actionResultBean = gson.fromJson(response, new TypeToken<ActionResultBean>() {
                        }.getType());
                        updateResult.setValue(actionResultBean);
                        loadState.setValue(LoadState.Success);
                    } else {
                        loadState.setValue(LoadState.Fail);
                        StringKit.show(context, StringHelper.getResponseMessage(response));
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
    }
}
