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

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

import com.gingersoft.gsa.cloud.common.bean.BaseResult;
import com.gingersoft.gsa.cloud.common.core.user.UserContext;
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.lifecycle.model.bean.YedpayFindSaleStatusBean;
import com.gingersoft.gsa.cloud.pay.phone.PhoneCallbackListener;
import com.gingersoft.gsa.cloud.pay.pos.PosPayAction;
import com.gingersoft.gsa.cloud.pay.pos.bbpos.BBposCallback;
import com.gingersoft.gsa.cloud.pay.pos.hyweb.HywebCallback;
import com.gingersoft.gsa.cloud.pay.pos.yedpay.YedpayCallback;
import com.gingersoft.gsa.cloud.pay.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;


/**
 * ================================================
 * 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 PosPayAction mPosPayAction;
    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 yedPayActivityForResult() {

    }

    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);
                            }
                        }
                        mRootView.killMyself();
                    }


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

    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);
                            }
                        }
                    }
                });
    }

    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(hywebCallback);
        } else if (AppDevices.isBBPos()) {
            requestParms.setCallback(bBposCallback);
        } else if (AppDevices.isYedpay()) {
            requestParms.setCallback(yedpayCallback);
        } else {
            requestParms.setCallback(yedpayCallback);
        }
    }

    private HywebCallback hywebCallback = new HywebCallback() {


    };

    private YedpayCallback yedpayCallback = new YedpayCallback() {

        @Override
        public void callSaleUri(String uri) {
            if (mRootView != null) {
                Uri uri2 = Uri.parse(uri);
                Intent intent = new Intent(Intent.ACTION_VIEW, uri2);
                mRootView.startActivityForResult(intent);
            }
        }

        @Override
        public void refundResult(boolean result) {
            yedPayRefundOrder(mRequestParms.getRefundReason(), mRequestParms.getOrderId(), mRequestParms.getPayType(), mRequestParms.getResturantId());
        }
    };

    private BBposCallback bBposCallback = new BBposCallback() {

    };

    private PhoneCallbackListener phoneCallbackListener = new PhoneCallbackListener() {

        @Override
        public void onSuccess(Object response) {

        }

        @Override
        public void onException(Object response, Exception e) {

        }
    };


}
