package com.gingersoft.gsa.cloud.pay.lifecycle.presenter;

import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;

import com.gingersoft.gsa.cloud.common.bean.BaseResult;
import com.gingersoft.gsa.cloud.common.rxjava.ErrorHandleSingleSubscriber;
import com.gingersoft.gsa.cloud.common.utils.AppDevices;
import com.gingersoft.gsa.cloud.common.utils.gson.GsonUtils;
import com.gingersoft.gsa.cloud.pay.PayStep;
import com.gingersoft.gsa.cloud.pay.PaymentControl;
import com.gingersoft.gsa.cloud.pay.RequestParms;
import com.gingersoft.gsa.cloud.pay.ResultCallback;
import com.gingersoft.gsa.cloud.pay.device.pos.bbpos.BBposCallbackImp;
import com.gingersoft.gsa.cloud.pay.device.pos.hyweb.HywebCallbackImp;
import com.gingersoft.gsa.cloud.pay.device.pos.yedpay.YedpayCallbackImp;
import com.gingersoft.gsa.cloud.pay.lifecycle.model.bean.YedpayFindSaleStatusBean;
import com.gingersoft.gsa.cloud.pay.device.phone.PhoneCallback;
import com.gingersoft.gsa.cloud.pay.device.pos.PosPayAction;
import com.gingersoft.gsa.cloud.pay.device.pos.bbpos.BBposCallback;
import com.gingersoft.gsa.cloud.pay.device.pos.hyweb.HywebCallback;
import com.gingersoft.gsa.cloud.pay.device.pos.yedpay.YedpayCallback;
import com.gingersoft.gsa.cloud.pay.device.pos.yedpay.constant.YedpayConstant;
import com.jess.arms.integration.AppManager;
import com.jess.arms.di.scope.FragmentScope;
import com.jess.arms.mvp.BasePresenter;
import com.jess.arms.http.imageloader.ImageLoader;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import me.jessyan.rxerrorhandler.core.RxErrorHandler;
import okhttp3.FormBody;
import okhttp3.RequestBody;

import javax.inject.Inject;

import com.gingersoft.gsa.cloud.pay.lifecycle.contract.PayFlowContract;
import com.jess.arms.utils.RxLifecycleUtils;

import java.lang.ref.WeakReference;


/**
 * ================================================
 * Description:
 * <p>
 * Created by MVPArmsTemplate on 04/15/2021 14:44
 * <a href="mailto:jess.yan.effort@gmail.com">Contact me</a>
 * <a href="https://github.com/JessYanCoding">Follow me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms">Star me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms/wiki">See me</a>
 * <a href="https://github.com/JessYanCoding/MVPArmsTemplate">模版请保持更新</a>
 * ================================================
 */
@FragmentScope
public class PayFlowPresenter extends BasePresenter<PayFlowContract.Model, PayFlowContract.View> {
    @Inject
    RxErrorHandler mErrorHandler;
    @Inject
    Application mApplication;
    @Inject
    ImageLoader mImageLoader;
    @Inject
    AppManager mAppManager;

    private RequestParms mRequestParms;
    private ResultCallback mResultCallback;

    @Inject
    public PayFlowPresenter(PayFlowContract.Model model, PayFlowContract.View rootView) {
        super(model, rootView);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        this.mErrorHandler = null;
        this.mAppManager = null;
        this.mImageLoader = null;
        this.mApplication = null;
    }

    public void yedPayUpdateStatus(String transactionId, long orderId, int payType, int restaurantId) {
        RequestBody requestBody = new FormBody.Builder()
                .add("transactionId", transactionId)
                .add("orderId", orderId + "")
                .add("payType", payType + "")
                .add("restaurantId", restaurantId + "")
                .build();

        mModel.yedPayFindSaleStatus(requestBody)
                .subscribeOn(Schedulers.io())
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .subscribe(new ErrorHandleSingleSubscriber<BaseResult>(mErrorHandler) {

                    @Override
                    public void onSuccess(BaseResult result) {
                        if (result.isSuccess()) {
                            YedpayFindSaleStatusBean saleStatusBean = GsonUtils.GsonToBean(result.getData(), YedpayFindSaleStatusBean.class);
                            if (saleStatusBean != null) {
                                if (saleStatusBean.getStatus() == YedpayConstant.Status.PAY_STATUS_0) {
                                    mRootView.showStatusLoadingDialog(PayStep.SUCCESS);
                                    if (mResultCallback != null) {
                                        mResultCallback.onSuccess();
                                    }
                                } else {
                                    mRootView.showStatusLoadingDialog(PayStep.FAILURE);
                                    if (mResultCallback != null) {
                                        mResultCallback.onFailure(null);
                                    }
                                }
                            } else {
                                mRootView.showStatusLoadingDialog(PayStep.FAILURE);
                                if (mResultCallback != null) {
                                    mResultCallback.onFailure(null);
                                }
                            }
                        } else {
                            mRootView.showStatusLoadingDialog(PayStep.FAILURE);
                            mRootView.showMessage(result.getErrMsg());
                            if (mResultCallback != null) {
                                mResultCallback.onFailure(null);
                            }
                        }
                    }

                    @Override
                    public void onError(Throwable t) {
                        super.onError(t);
                        mRootView.showStatusLoadingDialog(PayStep.FAILURE);
                        if (mResultCallback != null) {
                            mResultCallback.onFailure(t);
                        }
                    }
                });
    }

    public void yedPayRefundOrder(String refundReason, long orderId, int payType, int restaurantId) {
        RequestBody requestBody = new FormBody.Builder()
                .add("refundReason", refundReason)
                .add("orderId", String.valueOf(orderId))
                .add("payType", String.valueOf(payType))
                .add("restaurantId", String.valueOf(restaurantId))
                .build();
        mModel.yedPayRefundOrder(requestBody)
                .subscribeOn(Schedulers.io())
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .subscribe(new ErrorHandleSingleSubscriber<BaseResult>(mErrorHandler) {

                    @Override
                    public void onSuccess(BaseResult result) {
                        if (result.isSuccess()) {
                            mRootView.showStatusLoadingDialog(PayStep.SUCCESS);
                            if (mResultCallback != null) {
                                mResultCallback.onSuccess();
                            }
                        } else {
                            mRootView.showStatusLoadingDialog(PayStep.FAILURE);
                            if (mResultCallback != null) {
                                mResultCallback.onFailure(null);
                            }
                        }
                    }

                    @Override
                    public void onError(Throwable t) {
                        super.onError(t);
                        mRootView.showStatusLoadingDialog(PayStep.FAILURE);
                        if (mResultCallback != null) {
                            mResultCallback.onFailure(t);
                        }
                    }
                });
    }

    public void excutePayFlow(RequestParms requestParms) {
        this.mRequestParms = requestParms;
        this.mResultCallback = mRequestParms.getResultCallback();

        setCallbackBy(requestParms);

        switch (requestParms.getAction()) {
            case SALE:
                PaymentControl.newInstance().pay(requestParms);
                break;
            case REFUND:
                PaymentControl.newInstance().refund(requestParms);
                break;
        }
    }

    private void setCallbackBy(RequestParms requestParms) {
        if (AppDevices.isHywebPos()) {
            requestParms.setCallback(new HywebCallbackImp());
        } else if (AppDevices.isBBPos()) {
            requestParms.setCallback(new BBposCallbackImp());
        } else if (AppDevices.isYedpay()) {
            requestParms.setCallback(new YedpayCallbackImp(mRootView.getFragment(), this, mRequestParms));
        } else {
            requestParms.setCallback(new YedpayCallbackImp(mRootView.getFragment(), this, mRequestParms));
        }
    }

}
