package tech.starwin.mvp.presenter;


import android.annotation.SuppressLint;

import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.functions.Predicate;
import okhttp3.ResponseBody;
import tech.starwin.base.BasePresenter;
import tech.starwin.impl.HttpObserver;
import tech.starwin.mvp.api.UserApi;
import tech.starwin.mvp.beans.EmploymentBean;
import tech.starwin.mvp.beans.GatewayInfoBean;
import tech.starwin.mvp.beans.TokenInfoBean;
import tech.starwin.network.Gateway;
import tech.starwin.network.ServiceGenerator;
import tech.starwin.utils.LoginManager;

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

    @SuppressLint("CheckResult")
    public void notifyGateway() {
        Observable.fromIterable(Gateway.getGatewayUrl())
                .concatMap(new Function<String, ObservableSource<GatewayInfoBean>>() {
                    @Override
                    public ObservableSource<GatewayInfoBean> apply(String s) throws Exception {
                        return apiService.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)
                .subscribe(new Consumer<GatewayInfoBean>() {
                    @Override
                    public void accept(GatewayInfoBean gatewayInfoBean) throws Exception {
                        Gateway.notify(gatewayInfoBean);
                    }
                });
    }

    /**
     * 登录
     * （登录失败超过两次需要生成图像验证码)
     *
     * @param mobile     手机号
     * @param smsCode    短信验证码
     * @param captchaSid 生成的图像验证码
     * @param captcha    输入的图像验证码
     * @param inviteCode 邀请码
     */
    public void login(final String action, String mobile, String smsCode, String captchaSid, String captcha, String inviteCode) {
        handleRequest(apiService.login(smsCode, captchaSid, captcha, mobile, inviteCode),
                new HttpObserver<TokenInfoBean>() {
                    @Override
                    public void onStart() {
                        view.onHttpStart(action, true);
                    }

                    @Override
                    public void onSuccess(TokenInfoBean tokenInfoBean) {
                        //刷新Token信息
                        LoginManager.get().notifyTokenInfo(tokenInfoBean);
                        view.onHttpSuccess(action, tokenInfoBean);
                    }

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

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


    /**
     * FaceBook AccountKit 登录
     *
     * @param auth_code Facebook 授权码
     */
    public void accountKotLogin(final String action, String auth_code) {
        handleRequest(apiService.accountKitLogin(null, auth_code), new HttpObserver<TokenInfoBean>() {
            @Override
            public void onStart() {
                view.onHttpStart(action, true);
            }

            @Override
            public void onSuccess(TokenInfoBean tokenInfoBean) {
                //刷新Token信息
                LoginManager.get().notifyTokenInfo(tokenInfoBean);
                view.onHttpSuccess(action, tokenInfoBean);
            }

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

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

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

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

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


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

    /**
     * 提交联系人信息
     */
    public void submitContactInfo(String action, String parentName, String parentPhone, String friendName, String friendPhone) {
        handleRequest(action, apiService.submitContactInfo(parentName, parentPhone, friendName, friendPhone, LoginManager.get().getToken()));

    }

    /**
     * 提交联系人信息
     */
    public void submitEmploymentInfo(String action, EmploymentBean employmentBean) {
        Observable<ResponseBody> observable = ServiceGenerator.getService(UserApi.class)
                .submitEmploymentInfo(employmentBean.getCompanyName(),
                        employmentBean.getCompanyProvince().getName(),
                        employmentBean.getCompanyCity().getName(),
                        employmentBean.getCompanyDistrict().getName(),
                        employmentBean.getCompanyArea().getName(),
                        employmentBean.getCompanyAddress(),
                        employmentBean.getCompanyPhone(),
                        employmentBean.getJobType(),
                        employmentBean.getSalary(),
                        LoginManager.get().getToken());

        handleRequest(action, observable);

    }




//    /**
//     * 获取身份证图片 + 获取用户个人信息
//     */
//    @SuppressLint("CheckResult")
//    public void getKTPInfo(String action) {
//        Observable<OcrResultBean.KTP> observable = Observable.zip(
//                apiService.getKtpImg(LoginManager.get().getToken()).onErrorReturn(new Function<Throwable, RecordFilesResponse>() {
//                    @Override
//                    public RecordFilesResponse apply(Throwable throwable) throws Exception {
//                        return new RecordFilesResponse();
//                    }
//                }),
//                apiService.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);
//    }


}
