package com.philisense.rdgo.viewModel;

import android.content.Context;

import com.jakewharton.rxbinding2.InitialValueObservable;
import com.philisense.rdgo.bean.OError;
import com.philisense.rdgo.bean.request.PasswordRequestBean;
import com.philisense.rdgo.bean.response.BaseBean;
import com.philisense.rdgo.db.DBFactory;
import com.philisense.rdgo.db.UserDb;
import com.philisense.rdgo.http.HttpClient;
import com.philisense.rdgo.http.RequestImpl;
import com.philisense.rdgo.http.cache.ACache;
import com.philisense.rdgo.util.Constant;
import com.philisense.rdgo.util.MD5Util;

import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function3;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by shaop on 2017/12/14.
 */

public class PasswordViewModel {

    public Observable<Integer> passwordValidation;


    private Context context;
    private String originPassword;
    private String newPassword;
    private String reNewPassword;

    public PasswordViewModel(Context context,
                             InitialValueObservable<CharSequence> observableOriginPassword,
                             InitialValueObservable<CharSequence> observableNewPasswrod,
                             InitialValueObservable<CharSequence> observableReNewPasswrod) {
        this.context = context;

        // 原始密码获取
        observableOriginPassword.subscribe(new Consumer<CharSequence>() {
            @Override
            public void accept(CharSequence charSequence) throws Exception {
                originPassword = charSequence.length()>0 ? charSequence + "" : "";
            }
        });

        // 新密码获取
        observableNewPasswrod.subscribe(new Consumer<CharSequence>() {
            @Override
            public void accept(CharSequence charSequence) throws Exception {
                newPassword = charSequence.length()>0 ? charSequence + "" : "";
            }
        });

        // 二次新密码获取
        observableReNewPasswrod.subscribe(new Consumer<CharSequence>() {
            @Override
            public void accept(CharSequence charSequence) throws Exception {
                reNewPassword = charSequence.length()>0 ? charSequence + "" : "";
            }
        });

        // 验证密码合法性，0代表通过，1代表空字段，2代表二次密码不一致
        passwordValidation = Observable.combineLatest(
                observableOriginPassword,
                observableNewPasswrod,
                observableReNewPasswrod,
                new Function3<CharSequence, CharSequence, CharSequence, Integer>() {
                    @Override
                    public Integer apply(CharSequence charSequence, CharSequence charSequence2, CharSequence charSequence3) throws Exception {
                        if (charSequence.length()==0||charSequence2.length()==0||charSequence3.length()==0) {
                            return 1;
                        }else if (!charSequence2.toString().equals(charSequence3.toString())) {
                            return 2;
                        }else if (charSequence.toString().equals(charSequence2.toString())) {
                            return 3;
                        } else {
                            return 0;
                        }
                    }
                }
        );
    }

    public void modifyPassword(final RequestImpl listener) {

        ACache aCache = ACache.get(context);

        UserDb userDb = DBFactory.getUserInfo(context);

        PasswordRequestBean.LastUpdatedBy lastUpdatedBy = new PasswordRequestBean.LastUpdatedBy();
        lastUpdatedBy.setAccount(userDb.getAccount()==null ? "" : userDb.getAccount());
        lastUpdatedBy.setFactory(userDb.getFactory()==null ? "" : userDb.getFactory());
        lastUpdatedBy.setIDCard(userDb.getIDCard()==null ? "" : userDb.getIDCard());
        lastUpdatedBy.setLine(userDb.getLine()==null ? "" : userDb.getLine());
        lastUpdatedBy.setPerson(userDb.getName()==null ? "" : userDb.getName());
        lastUpdatedBy.setSex(userDb.getSex()==null ? "" : userDb.getSex());
        lastUpdatedBy.setWarehouse(userDb.getWarehouse()==null ? "" : userDb.getWarehouse());

        PasswordRequestBean bean = new PasswordRequestBean();
        bean.setAccessToken(aCache.getAsString(Constant.ACCESSTOKEN));
        bean.setId(aCache.getAsString(Constant.USERID));
        bean.setNewPassword(MD5Util.getMD5(newPassword));
        bean.setOriginalPassword(MD5Util.getMD5(originPassword));
        bean.setLastUpdatedBy(lastUpdatedBy);

        HttpClient.Builder.getBaseService()
                .modifyPassword(bean)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<BaseBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(BaseBean value) {
                        if (value.getSuccess() == 0){
                            listener.loadSuccess(value.getMessage());
                        }else {
                            listener.loadFailed(new OError(value.getSuccess(),value.getMessage()));
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        listener.loadFailed(new OError(Constant.SystemErrorCode,e.getMessage()));
                    }

                    @Override
                    public void onComplete() {
                    }
                });
    }
}
