package tech.starwin.mvp.presenter;


import android.annotation.SuppressLint;
import android.text.TextUtils;

import com.common.bean.BankBean;
import com.common.bean.BasicAck;
import com.common.bean.ContactBean;
import com.common.bean.ContactInfoBean;
import com.common.bean.DisplayBean;
import com.common.bean.EmploymentServerBean;
import com.common.bean.GatewayInfoBean;
import com.common.bean.LatestLoanAppBean;
import com.common.bean.LoanInfo;
import com.common.bean.LoaningAmoutBean;
import com.common.bean.PersonalInfoServerBean;
import com.common.bean.RecordFilesResponse;
import com.common.bean.TokenInfoBean;
import com.common.bean.UserBankInfo;
import com.common.bean.UserBean;
import com.common.toolbox.PluginConfig;
import com.common.toolbox.app_utils.DeviceInfo;
import com.common.toolbox.tracker.TrackEvent;
import com.facebook.libfbref.FbDeepLink;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.util.List;

import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.BiFunction;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.functions.Function4;
import io.reactivex.functions.Predicate;
import io.reactivex.schedulers.Schedulers;
import okhttp3.MultipartBody;
import okhttp3.ResponseBody;
import tech.starwin.LibConfig;
import tech.starwin.base.BasePresenter;
import tech.starwin.constants.ActionEnum;
import tech.starwin.impl.HttpObserver;
import tech.starwin.mvp.api.LoanApi;
import tech.starwin.mvp.api.UploadApi;
import tech.starwin.mvp.api.UserApi;
import tech.starwin.network.Gateway;
import tech.starwin.network.ServiceGenerator;
import tech.starwin.network.tools.MultipartBodyMaker;
import tech.starwin.utils.AccountKitUtils;
import tech.starwin.utils.LogUtils;
import tech.starwin.utils.LoginManager;
import tech.starwin.utils.PreferencesManager;
import tech.starwin.utils.TrackEventHelper;

/**
 * Created by SiKang on 2018/9/14.
 */
public class UserPresenter extends BasePresenter<UserApi> {
    public UserPresenter() {
        super(UserApi.class);
    }


    /**
     * 获取客户配置
     */
    public void getCorpConfig(String action, String cusKey) {
        UserApi api = ServiceGenerator.getService(UserApi.class, LibConfig.API_BASE_URL);
        handleRequest(action, api.getCropConfig(cusKey));
    }

    @SuppressLint("CheckResult")
    public void notifyGateway() {
        getGateway("", Gateway.getGatewayUrl());
    }

    @SuppressLint("CheckResult")
    public void getGateway(String action, List<String> gatewayUrl) {
        FbDeepLink.fetchDeepLink();
        Observable.fromIterable(gatewayUrl)
                .subscribeOn(Schedulers.io())
                .concatMap(new Function<String, ObservableSource<GatewayInfoBean>>() {
                    @Override
                    public ObservableSource<GatewayInfoBean> apply(String s) throws Exception {
                        return getApiService().getGateway(s).onErrorReturn(new Function<Throwable, GatewayInfoBean>() {
                            @Override
                            public GatewayInfoBean apply(Throwable throwable) throws Exception {
                                return new GatewayInfoBean();
                            }
                        });
                    }
                })
                .filter(new Predicate<GatewayInfoBean>() {
                    @Override
                    public boolean test(GatewayInfoBean gatewayInfoBean) throws Exception {
                        return gatewayInfoBean != null && gatewayInfoBean.gateway != null;
                    }
                })
                .take(1)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<GatewayInfoBean>() {
                    @Override
                    public void accept(GatewayInfoBean gatewayInfoBean) throws Exception {
                        Gateway.setGatewayInfoBean(gatewayInfoBean);
                        if (!PreferencesManager.get().getBoolean("device_info_uploaded", false)) {
                            TrackEventHelper.logEvent(DeviceInfo.getHardwareInfo());
                            String pkgs = DeviceInfo.getPkgsFromeAppList(DeviceInfo.getAppList(LibConfig.getContext(), 20));
                            TrackEventHelper.logEvent(pkgs);
                            PreferencesManager.get().saveData("device_info_uploaded", true);
                        }

                        getCustomerMsg("");
                        EventBus.getDefault().post(ActionEnum.GATEWAY_UPDATED);
                        if (view != null) {
                            view.onHttpSuccess(action, gatewayInfoBean);
                        }
                    }
                });
    }


    /**
     * 发送短信
     */
    public void sendSms(String action, String mobile) {
        handleRequest(action, getApiService().sendSms(mobile));
    }

    /**
     * 登录
     * （登录失败超过两次需要生成图像验证码)
     *
     * @param mobile     手机号
     * @param smsCode    短信验证码
     * @param captchaSid 生成的图像验证码
     * @param captcha    输入的图像验证码
     * @param inviteCode 邀请码
     */
    @SuppressLint("CheckResult")
    public void login(final String action, String mobile, String smsCode, String captchaSid, String captcha, String inviteCode) {
        handleRequest(
                getApiService().login(smsCode, captchaSid, captcha, mobile, inviteCode)
                        .flatMap(new Function<TokenInfoBean, ObservableSource<UserBean>>() {
                            @Override
                            public ObservableSource<UserBean> apply(TokenInfoBean tokenInfoBean) throws Exception {
                                TrackEventHelper.logEvent(TrackEvent.Api.SMS_LOGIN_SUCCESS);
                                //刷新Token信息
                                LoginManager.get().notifyTokenInfo(tokenInfoBean);
                                uploadFirebaseToken(PreferencesManager.get().getFireBaseMessagingToken());
                                return getApiService().getUserInfo();
                            }
                        }),
                new HttpObserver<UserBean>() {
                    @Override
                    public void onStart() {
                        view.onHttpStart(action, true);
                    }

                    @Override
                    public void onSuccess(UserBean data) {
                        if (TextUtils.isEmpty(data.getName())) {
                            data.setName(LoginManager.get().getTokenInfo().getMobile());
                        }
                        PreferencesManager.get().saveUserInfo(data);
                        view.onHttpSuccess(action, data);

                        EventBus.getDefault().post(ActionEnum.LOGIN_SUCCESS);
                    }

                    @Override
                    public void onError(int code, String msg) {
                        view.onHttpError(action, msg);
                    }

                    @Override
                    public void onFinish() {
                        view.onHttpFinish(action);
                    }
                });

    }

    /**
     * 获取用户信息
     */
    public void getUserInfo(final String action) {
        handleRequest(getApiService().getUserInfo(), new HttpObserver<UserBean>() {
            @Override
            public void onStart() {
            }

            @Override
            public void onSuccess(UserBean data) {

            }

            @Override
            public void onError(int code, String msg) {
                view.onHttpError(action, msg);
            }

            @Override
            public void onFinish() {
                view.onHttpFinish(action);
            }
        });
    }


    /**
     * 活动中心数据
     */
    public void trackEvent(String event) {
        handleRequest(getApiService().trackEvent("system", "api", event), new HttpObserver<ResponseBody>() {
            @Override
            public void onStart() {

            }

            @Override
            public void onSuccess(ResponseBody data) {
                LogUtils.d(TAG, "");
            }

            @Override
            public void onError(int code, String msg) {
                LogUtils.d(TAG, "");
            }

            @Override
            public void onFinish() {

            }
        });
    }


    /**
     * 活动中心数据
     */
    public void trackEvent(String type, String action, String event) {
        handleRequest(getApiService().trackEvent(type, action, event), new HttpObserver<ResponseBody>() {
            @Override
            public void onStart() {

            }

            @Override
            public void onSuccess(ResponseBody data) {
                LogUtils.d(TAG, "");
            }

            @Override
            public void onError(int code, String msg) {
                LogUtils.d(TAG, "");
            }

            @Override
            public void onFinish() {

            }
        });
    }

    /**
     * 上传firebaseToken
     */
    public void uploadFirebaseToken(String token) {
        if (!TextUtils.isEmpty(token)) {
            getApiService().uploadFirebaseToken(token);
        }
    }

    /**
     * FaceBook AccountKit 登录
     *
     * @param auth_code Facebook 授权码
     */
    public void accountKotLogin(final String action, String auth_code) {
        handleRequest(
                getApiService().accountKitLogin(null, auth_code)
                        .flatMap(new Function<TokenInfoBean, ObservableSource<UserBean>>() {
                            @Override
                            public ObservableSource<UserBean> apply(TokenInfoBean tokenInfoBean) throws Exception {
                                TrackEventHelper.logEvent(TrackEvent.Api.ACCOUNT_KIT_LOGIN_SUCCESS);
                                //刷新Token信息
                                LoginManager.get().notifyTokenInfo(tokenInfoBean);
                                uploadFirebaseToken(PreferencesManager.get().getFireBaseMessagingToken());
                                return getApiService().getUserInfo();
                            }
                        }),
                new HttpObserver<UserBean>() {
                    @Override
                    public void onStart() {
                        view.onHttpStart(action, true);
                    }

                    @Override
                    public void onSuccess(UserBean data) {
                        if (TextUtils.isEmpty(data.getName())) {
                            data.setName(LoginManager.get().getTokenInfo().getMobile());
                        }
                        PreferencesManager.get().saveUserInfo(data);
                        view.onHttpSuccess(action, data);

                        EventBus.getDefault().post(ActionEnum.LOGIN_SUCCESS);
                    }

                    @Override
                    public void onError(int code, String msg) {
                        view.onHttpError(action, msg);
                    }

                    @Override
                    public void onFinish() {
                        view.onHttpFinish(action);
                    }
                });
    }


    /**
     * 获取贷款状态、贷款详情、绑定银行卡、银行卡列表
     */
    public void getBankAndLoanAmout(String action, LatestLoanAppBean loanBean) {
        Observable<LoanInfo> observable = Observable.zip(
                getService(LoanApi.class).getLatestLoanApp(),
                clearError(getApiService().getLoanAmoutData(loanBean.getAmount(), loanBean.getPeriod(), loanBean.getPeriodUnit(), loanBean.getProductId()), LoaningAmoutBean.class),
                clearError(getApiService().getBankCardInfo(), UserBankInfo.class),
                getService(LoanApi.class).getBankList(),
                new Function4<LatestLoanAppBean, LoaningAmoutBean, UserBankInfo, List<BankBean>, LoanInfo>() {
                    @Override
                    public LoanInfo apply(LatestLoanAppBean latestLoanAppBean, LoaningAmoutBean loaningAmoutBean, UserBankInfo userBankInfo, List<BankBean> bankBeans) throws Exception {
                        LoanInfo userInfo = new LoanInfo();
                        userInfo.setLatestLoanAppBean(latestLoanAppBean);
                        userInfo.setLoaningAmoutInfo(loaningAmoutBean);
                        userInfo.setUserBankInfo(userBankInfo);
                        userInfo.setBankList(bankBeans);
                        return userInfo;
                    }
                }
        );
        handleRequest(action, observable);

    }

    /**
     * 活动中心数据
     */
    public void getActivitys(String action) {
        handleRequest(action, getApiService().getActivityList());

    }


    /**
     * 消息列表
     */
    public void getMsgList(String action) {
        handleRequest(action, getApiService().getMsgInbox());
    }

//    @SuppressLint("CheckResult")
//    public void getUserInfo(final String action) {
//        LoanApi loanApi = ServiceGenerator.getService(LoanApi.class);
//        final LoanInfo userInfoBean = new LoanInfo();
//
//        clearError(loanApi.getLatestLoanApp(LoginManager.get().getToken()))
//                .flatMap(new Function<LatestLoanAppBean, ObservableSource<Pair<LoaningAmoutBean, UserBankInfo>>>() {
//                    @Override
//                    public ObservableSource<Pair<LoaningAmoutBean, UserBankInfo>> apply(LatestLoanAppBean latestLoanAppBean) throws Exception {
//                        //保存贷款信息
//                        userInfoBean.setLatestLoanAppBean(latestLoanAppBean);
//                        //继续请求用户银行卡信息，和贷款详情
//                        return Observable.zip(
//                                clearError(getApiService().getLoanAmoutData(latestLoanAppBean.getAmount(), latestLoanAppBean.getPeriod(), latestLoanAppBean.getPeriodUnit(), latestLoanAppBean.getProductId())),
//                                clearError(getApiService().getBankCardInfo(LoginManager.get().getToken())),
//                                new BiFunction<LoaningAmoutBean, UserBankInfo, Pair<LoaningAmoutBean, UserBankInfo>>() {
//                                    @Override
//                                    public Pair<LoaningAmoutBean, UserBankInfo> apply(LoaningAmoutBean loaningAmoutBean, UserBankInfo userBankInfo) throws Exception {
//                                        return new Pair<>(loaningAmoutBean, userBankInfo);
//                                    }
//                                });
//                    }
//                })
//                .subscribe(new Consumer<Pair<LoaningAmoutBean, UserBankInfo>>() {
//                    @Override
//                    public void accept(Pair<LoaningAmoutBean, UserBankInfo> pair) throws Exception {
//                        userInfoBean.setLoaningAmoutInfo(pair.first);
//                        userInfoBean.setUserBankInfo(pair.second);
//                        view.onHttpSuccess(action, userInfoBean);
//                    }
//                });
//
//    }

    /**
     * 获取身份证图片地址
     */
    public void getKtpImg(String action) {
        handleRequest(action, getApiService().getKtpImg());
    }

    /**
     * 获取用户身份信息
     */
    public void getPersonalInfo(String action) {
        handleRequest(action, getApiService().getPersonalInfo());
    }


    /**
     * 查询学历类型列表
     */
    public void getEducationList(String action) {
        handleRequest(action, getApiService().sysDict("EDUCATION"));
    }


    /**
     * 查询区域列表
     */
    public void getRegion(String action, String level, int id) {
        handleRequest(action, getApiService().getRegion(level, id));
    }


    /**
     * 提交个人信息
     */
    public void submitPersonalInfo(String action, PersonalInfoServerBean personalInfo) {
        Observable<ResponseBody> observable = getApiService().submitPersonalInfo(
                personalInfo.getFullName(),
                personalInfo.getCredentialNo(),
                personalInfo.getFamilyNameInLaw(),
                personalInfo.getGender(),
                personalInfo.getProvince(),
                personalInfo.getCity(),
                personalInfo.getDistrict(),
                personalInfo.getArea(),
                personalInfo.getAddress(),
                personalInfo.getLastEducation(),
                personalInfo.getMaritalStatus(),
                personalInfo.getChildrenNumber(),
                personalInfo.getResidenceDuration(),
                personalInfo.getFacebookId(),
                personalInfo.getWhatsappId());

        handleRequest(observable, new HttpObserver<ResponseBody>() {
            @Override
            public void onStart() {
                view.onHttpStart(action, true);
            }

            @Override
            public void onSuccess(ResponseBody data) {
                TrackEventHelper.logEvent(TrackEvent.Api.PERSONAL_INFO_SUBMITED);
                view.onHttpSuccess(action, data);
            }

            @Override
            public void onError(int code, String msg) {
                view.onHttpError(action, msg);
            }

            @Override
            public void onFinish() {
                view.onHttpFinish(action);
            }
        });
    }


    /**
     * 提交联系人信息
     */
    public void submitContactInfo(String action, String parentName, String parentPhone, String friendName, String friendPhone) {
        handleRequest(getApiService().submitContactInfo(parentName, parentPhone, friendName, friendPhone, LoginManager.get().getToken()),
                new HttpObserver<ResponseBody>() {
                    @Override
                    public void onStart() {
                        view.onHttpStart(action, true);
                    }

                    @Override
                    public void onSuccess(ResponseBody data) {
                        TrackEventHelper.logEvent(TrackEvent.Api.CONTACT_INFO_SUBMITED);
                        view.onHttpSuccess(action, data);
                    }

                    @Override
                    public void onError(int code, String msg) {
                        view.onHttpError(action, msg);
                    }

                    @Override
                    public void onFinish() {
                        view.onHttpFinish(action);
                    }
                });

    }

    public void submitContactInfo(String action, ContactInfoBean contactInfo) {
        handleRequest(getApiService().submitContactInfo(contactInfo.getParentId(), contactInfo.getParentName(), contactInfo.getParentMobile(), contactInfo.getParentType(),
                contactInfo.getFriendId(), contactInfo.getFriendName(), contactInfo.getFriendMobile(), contactInfo.getFriendType(),
                contactInfo.getFriendId1(), contactInfo.getFriendName1(), contactInfo.getFriendMobile1(), contactInfo.getFriendType1()),
                new HttpObserver<ResponseBody>() {
                    @Override
                    public void onStart() {
                        view.onHttpStart(action, true);
                    }

                    @Override
                    public void onSuccess(ResponseBody data) {
                        TrackEventHelper.logEvent(TrackEvent.Api.CONTACT_INFO_SUBMITED);
                        view.onHttpSuccess(action, data);
                    }

                    @Override
                    public void onError(int code, String msg) {
                        view.onHttpError(action, msg);
                    }

                    @Override
                    public void onFinish() {
                        view.onHttpFinish(action);
                    }
                });

    }

    /**
     * 获取工作信息
     */
    public void getEmploymentInfo(String action) {
        Observable<EmploymentServerBean> employment = getApiService().getEmploymentInfo();
        Observable<RecordFilesResponse> jobImg = getApiService().getJobImg();

        handleRequest(action, Observable.zip(clearError(employment, EmploymentServerBean.class),
                clearError(jobImg, RecordFilesResponse.class),
                new BiFunction<EmploymentServerBean, RecordFilesResponse, EmploymentServerBean>() {
                    @Override
                    public EmploymentServerBean apply(EmploymentServerBean employmentServerBean, RecordFilesResponse recordFilesResponse) throws Exception {
                        if (employmentServerBean == null) {
                            employmentServerBean = new EmploymentServerBean();
                        }
                        if (recordFilesResponse != null && recordFilesResponse.getFiles() != null) {
                            if (recordFilesResponse.getFiles() != null && recordFilesResponse.getFiles().size() > 0) {
                                employmentServerBean.setWorkCardUrl(recordFilesResponse.getFiles().get(0).getUrl());
                            }
                        }
                        return employmentServerBean;
                    }
                }));

    }

    public void submitEmploymentInfo(String action, File workCardImage, EmploymentServerBean employmentBean) {
        MultipartBody.Part part = null;
        if (workCardImage != null && workCardImage.exists()) {
            part = MultipartBodyMaker.makeSimplePart("file", workCardImage);
        }
        submitEmploymentInfo(action, part, employmentBean);
    }

//    public void submitEmploymentInfo(String action, Bitmap bitmap, EmploymentServerBean employmentBean) {
//        MultipartBody.Part part = null;
//        if (bitmap != null) {
//            part = MultipartBodyMaker.makeSimplePart("file", "word_card", bitmap, Bitmap.CompressFormat.JPEG);
//        }
//        submitEmploymentInfo(action, part, employmentBean);
//    }

    /**
     * 提交工作信息
     */
    private void submitEmploymentInfo(String action, MultipartBody.Part part, EmploymentServerBean employmentBean) {
        Observable<ResponseBody> info = ServiceGenerator.getService(UserApi.class)
                .submitEmploymentInfo(employmentBean.getCompanyName(),
                        employmentBean.getCompanyProvince(),
                        employmentBean.getCompanyCity(),
                        employmentBean.getCompanyDistrict(),
                        employmentBean.getCompanyArea(),
                        employmentBean.getCompanyAddress(),
                        employmentBean.getCompanyPhone(),
                        employmentBean.getProfession(),
                        employmentBean.getSalary());

        if (part != null) {
            Observable<ResponseBody> upload = getService(UploadApi.class).uploadPhoto(part, "EMPLOYMENT_PHOTO");

            handleRequest(action, Observable.zip(info, upload, new BiFunction<ResponseBody, ResponseBody, Boolean>() {
                @Override
                public Boolean apply(ResponseBody responseBody, ResponseBody responseBody2) throws Exception {
                    TrackEventHelper.logEvent(TrackEvent.Api.WORK_CARD_UPLOADED);
                    TrackEventHelper.logEvent(TrackEvent.Api.WORK_INFO_SUBMITED);
                    return true;
                }
            }));
        } else {
            handleRequest(info, new HttpObserver<ResponseBody>() {
                @Override
                public void onStart() {
                    view.onHttpStart(action, true);
                }

                @Override
                public void onSuccess(ResponseBody data) {
                    TrackEventHelper.logEvent(TrackEvent.Api.WORK_INFO_SUBMITED);
                    view.onHttpSuccess(action, data);
                }

                @Override
                public void onError(int code, String msg) {
                    view.onHttpError(action, msg);
                }

                @Override
                public void onFinish() {
                    view.onHttpFinish(action);
                }
            });
        }

    }

    /**
     * 客户服务热线、公司介绍
     */
    public void getCustomerMsg(String action) {
        handleRequest(getApiService().display(), new HttpObserver<DisplayBean>() {
            @Override
            public void onStart() {
            }

            @Override
            public void onSuccess(DisplayBean data) {
                if (data.getAccountKitInfo() != null) {
                    String appId = data.getAccountKitInfo().getApplicationId();
                    String token = data.getAccountKitInfo().getAppclientToken();
                    if (!TextUtils.isEmpty(appId) && !TextUtils.isEmpty(token)) {
                        AccountKitUtils.initAccountKit(appId, LibConfig.APP_NAME, token);
                    }
                }
                //是否显示假界面
                PluginConfig.IS_FAKE_MODE = data.isFakeProductFlag();
                //不开启同盾
                if (!data.isTongDunFlag()) {
                    LibConfig.TONGDUN_PARENT_KEY = "";
                }
                data.setUpdateTime(System.currentTimeMillis());
                PreferencesManager.get().saveCustomerInfo(data);
                if (view != null) {
                    view.onHttpSuccess(action, data);
                }
            }

            @Override
            public void onError(int code, String msg) {
                if (view != null) {
                    view.onHttpError(action, msg);
                }
            }

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


    /**
     * 获取SD权限后再调用一次display
     */
    public void refreshDiaplay(String action) {
        handleRequest(action, getApiService().display());
    }


    /**
     * 获取联系人信息
     */
    public void getContactInfo(String action) {
        handleRequest(action, getApiService().getContactInfo());
    }


    /**
     * 获取联系人信息
     */
    public void getContactList(String action) {
        handleRequest(action, getApiService().getContactList());
    }

    /**
     * 获取联系人信息
     */
    public void submitContactList(String action, List<ContactBean> contactBeans) {
        handleRequest(getApiService().submitContactList(contactBeans), new HttpObserver<BasicAck>() {
            @Override
            public void onStart() {
                view.onHttpStart(action, true);
            }

            @Override
            public void onSuccess(BasicAck data) {
                TrackEventHelper.logEvent(TrackEvent.Api.CONTACT_INFO_SUBMITED);
                view.onHttpSuccess(action, data);
            }

            @Override
            public void onError(int code, String msg) {
                view.onHttpError(action, msg);
            }

            @Override
            public void onFinish() {
                view.onHttpFinish(action);
            }
        });
    }

    /**
     * 获取其他照片
     */
    public void getPhotoList(String action) {
        handleRequest(action, getApiService().getPhotoList());
    }

    /**
     * 公告
     */
    public void getBannerMsg(String action) {
        handleRequest(action, getApiService().getBannerMsg());
    }


    /**
     * 获取绑定的第三方账户
     */
    public void getThirdPartData(String action) {
        handleRequest(action, getApiService().getThirdPartAccount());
    }


    /**
     * 获取同盾列表
     */
    public void getThirdPartList(String action) {
        handleRequest(action, getApiService().getThirdPartList());
    }

    /**
     * 获取绑定的第三方账户
     */
    public void getThirdPartListV2(String action) {
        handleRequest(action, getApiService().getThirdPartListV2());
    }

    /**
     * 提交第同盾数据源
     */
    public void submitTDData(String action, String dataType, String taskId, String credentialNo, String realName, String mobile) {
        handleRequest(action,
                getApiService().submitThirdPartData("TONGDUN", dataType, taskId, credentialNo, realName, mobile, ""));
    }

    public void submitMXData(String action, String dataType, String taskId, String credentialNo, String realName, String mobile) {
        handleRequest(action,
                getApiService().submitThirdPartData("MOXIE", dataType, taskId, credentialNo, realName, mobile, ""));
    }

//    /**
//     * 获取身份证图片 + 获取用户个人信息
//     */
//    @SuppressLint("CheckResult")
//    public void getKTPInfo(String action) {
//        Observable<OcrResultBean.KTP> observable = Observable.zip(
//                getApiService().getKtpImg(LoginManager.get().getToken()).onErrorReturn(new Function<Throwable, RecordFilesResponse>() {
//                    @Override
//                    public RecordFilesResponse apply(Throwable throwable) throws Exception {
//                        return new RecordFilesResponse();
//                    }
//                }),
//                getApiService().getPersonalInfo(LoginManager.get().getToken()).onErrorReturn(new Function<Throwable, PersonalInfoServerBean>() {
//                    @Override
//                    public PersonalInfoServerBean apply(Throwable throwable) throws Exception {
//                        return new PersonalInfoServerBean();
//                    }
//                }),
//                new BiFunction<RecordFilesResponse, PersonalInfoServerBean, OcrResultBean.KTP>() {
//                    @Override
//                    public OcrResultBean.KTP apply(RecordFilesResponse recordFilesResponse, PersonalInfoServerBean personalInfoServerBean) throws Exception {
//                        OcrResultBean.KTP ktp = new OcrResultBean.KTP();
//                        String url;
//                        try {
//                            url = recordFilesResponse.getFiles().get(0).getUrl();
//                        } catch (NullPointerException e) {
//                            url = "";
//                        }
//                        //将两个请求结果拼装
//                        ktp.setImgUrl(url);
//                        ktp.setIdNumber(personalInfoServerBean.getCredentialNo());
//                        ktp.setName(personalInfoServerBean.getFullName());
//                        return ktp;
//                    }
//                });
//        //处理请求
//        handleRequest(action, observable);
//    }


}
