package tech.starwin.mvp.presenter;


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

import org.greenrobot.eventbus.EventBus;

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

import io.reactivex.Observable;
import io.reactivex.ObservableSource;
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.ResponseBody;
import tech.starwin.base.BasePresenter;
import tech.starwin.constants.ActionEnum;
import tech.starwin.constants.TrackEvent;
import tech.starwin.impl.HttpObserver;
import tech.starwin.mvp.api.LoanApi;
import tech.starwin.mvp.api.UploadApi;
import tech.starwin.mvp.api.UserApi;

import com.common.bean.BankBean;
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 tech.starwin.network.Gateway;
import tech.starwin.network.ServiceGenerator;
import tech.starwin.utils.LoginManager;
import tech.starwin.utils.MultipartBodyMaker;
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);
    }

    @SuppressLint("CheckResult")
    public void notifyGateway() {
        Observable.fromIterable(Gateway.getGatewayUrl())
                .observeOn(Schedulers.io())
                .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.setGatewayInfoBean(gatewayInfoBean);
                        EventBus.getDefault().post(ActionEnum.GATEWAY_UPDATED);
                    }
                });
    }


    /**
     * 发送短信
     */
    public void sendSms(String action, String mobile) {
        handleRequest(action, apiService.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(
                apiService.login(smsCode, captchaSid, captcha, mobile, inviteCode)
                        .flatMap(new Function<TokenInfoBean, ObservableSource<UserBean>>() {
                            @Override
                            public ObservableSource<UserBean> apply(TokenInfoBean tokenInfoBean) throws Exception {
                                TrackEventHelper.logEvent(TrackEvent.SMS_LOGIN_SUCCESS);
                                //刷新Token信息
                                LoginManager.get().notifyTokenInfo(tokenInfoBean);
                                uploadFirebaseToken(PreferencesManager.get().getFireBaseMessagingToken());
                                return apiService.getUserInfo(tokenInfoBean.getToken());
                            }
                        }),
                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(apiService.getUserInfo(LoginManager.get().getToken()), 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);
            }
        });
    }


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

    /**
     * FaceBook AccountKit 登录
     *
     * @param auth_code Facebook 授权码
     */
    public void accountKotLogin(final String action, String auth_code) {
        handleRequest(
                apiService.accountKitLogin(null, auth_code)
                        .flatMap(new Function<TokenInfoBean, ObservableSource<UserBean>>() {
                            @Override
                            public ObservableSource<UserBean> apply(TokenInfoBean tokenInfoBean) throws Exception {
                                TrackEventHelper.logEvent(TrackEvent.FACEBOOK_LOGIN_SUCCESS);
                                //刷新Token信息
                                LoginManager.get().notifyTokenInfo(tokenInfoBean);
                                uploadFirebaseToken(PreferencesManager.get().getFireBaseMessagingToken());
                                return apiService.getUserInfo(tokenInfoBean.getToken());
                            }
                        }),
                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(LoginManager.get().getToken()),
                clearError(apiService.getLoanAmoutData(loanBean.getAmount(), loanBean.getPeriod(), loanBean.getPeriodUnit(), loanBean.getProductId()), LoaningAmoutBean.class),
                clearError(apiService.getBankCardInfo(LoginManager.get().getToken()), 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, apiService.getActivityList());

    }


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

//    @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(apiService.getLoanAmoutData(latestLoanAppBean.getAmount(), latestLoanAppBean.getPeriod(), latestLoanAppBean.getPeriodUnit(), latestLoanAppBean.getProductId())),
//                                clearError(apiService.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, 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 submitPersonalInfo(String action, PersonalInfoServerBean personalInfo) {
        Observable<ResponseBody> observable = apiService.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(),
                LoginManager.get().getToken());

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

            @Override
            public void onSuccess(ResponseBody data) {
                TrackEventHelper.logEvent(TrackEvent.PERSONAL_INFO_SUBMIT);
                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(apiService.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.CONTACT_INFO_SUBMIT);
                        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(apiService.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(),
                LoginManager.get().getToken()),
                new HttpObserver<ResponseBody>() {
                    @Override
                    public void onStart() {
                        view.onHttpStart(action, true);
                    }

                    @Override
                    public void onSuccess(ResponseBody data) {
                        TrackEventHelper.logEvent(TrackEvent.CONTACT_INFO_SUBMIT);
                        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 = apiService.getEmploymentInfo(LoginManager.get().getToken());
        Observable<RecordFilesResponse> jobImg = apiService.getJobImg(LoginManager.get().getToken());

        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) {
        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(),
                        LoginManager.get().getToken());

        if (workCardImage != null && workCardImage.exists()) {
            Observable<ResponseBody> upload = getService(UploadApi.class).uploadPhoto(MultipartBodyMaker.makeSimplePart("file", workCardImage), "EMPLOYMENT_PHOTO", LoginManager.get().getToken());

            handleRequest(action, Observable.zip(info, upload, new BiFunction<ResponseBody, ResponseBody, Boolean>() {
                @Override
                public Boolean apply(ResponseBody responseBody, ResponseBody responseBody2) throws Exception {
                    TrackEventHelper.logEvent(TrackEvent.PROFESSIONAL_INFO_SUBMIT);
                    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.PROFESSIONAL_INFO_SUBMIT);
                    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(apiService.display(), new HttpObserver<DisplayBean>() {
            @Override
            public void onStart() {
                view.onHttpStart(action, true);
            }

            @Override
            public void onSuccess(DisplayBean data) {
                data.setUpdateTime(System.currentTimeMillis());
                PreferencesManager.get().saveCustomerInfo(data);
                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 getContactInfo(String action) {
        handleRequest(action, apiService.getContactInfo(LoginManager.get().getToken()));
    }


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

    /**
     * 获取联系人信息
     */
    public void submitContactList(String action, List<ContactBean> contactBeans) {
        handleRequest(action, apiService.submitContactList(contactBeans));
    }

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

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


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


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

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

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


//    /**
//     * 获取身份证图片 + 获取用户个人信息
//     */
//    @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);
//    }


}
