package com.gingersoft.gsa.cloud.pay.device.pos.yedpay.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.rxjava.ErrorHandleSingleSubscriber;
import com.gingersoft.gsa.cloud.common.utils.gson.GsonUtils;
import com.gingersoft.gsa.cloud.pay.PayStep;
import com.gingersoft.gsa.cloud.pay.PaymentCommand;
import com.gingersoft.gsa.cloud.pay.RequestParms;
import com.gingersoft.gsa.cloud.pay.ResultCallback;
import com.gingersoft.gsa.cloud.pay.bean.PayMethod;
import com.gingersoft.gsa.cloud.pay.device.pos.yedpay.YedpayCommand;
import com.gingersoft.gsa.cloud.pay.device.pos.yedpay.constant.YedpayConstant;
import com.gingersoft.gsa.cloud.pay.device.pos.yedpay.lifecycle.model.bean.request.GetYedPayRefundTxnIdRequest;
import com.gingersoft.gsa.cloud.pay.device.pos.yedpay.lifecycle.model.bean.request.GetYedPayTxnIdRequest;
import com.gingersoft.gsa.cloud.pay.device.pos.yedpay.lifecycle.model.bean.response.YedpayFindSaleStatusBean;
import com.gingersoft.gsa.cloud.pay.device.pos.yedpay.lifecycle.model.bean.response.bg.GetYedPayTxnIdResponse;
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 me.jessyan.rxerrorhandler.core.RxErrorHandler;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.RequestBody;

import javax.inject.Inject;

import com.gingersoft.gsa.cloud.pay.device.pos.yedpay.lifecycle.contract.YedpayContract;
import com.jess.arms.utils.RxLifecycleUtils;


/**
 * ================================================
 * Description:
 * <p>
 * Created by MVPArmsTemplate on 04/30/2021 16:23
 * <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 YedpayPresenter extends BasePresenter<YedpayContract.Model, YedpayContract.View> {
    @Inject
    RxErrorHandler mErrorHandler;
    @Inject
    Application mApplication;
    @Inject
    ImageLoader mImageLoader;
    @Inject
    AppManager mAppManager;

    private RequestParms mRequestParms;
    private ResultCallback mResultCallback;

    @Inject
    public YedpayPresenter(YedpayContract.Model model, YedpayContract.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 getYedPayTxnId(GetYedPayTxnIdRequest payTxnIdRequest) {

        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), GsonUtils.GsonString(payTxnIdRequest));
        String json = GsonUtils.GsonString(payTxnIdRequest);

        mModel.getYedPayTxnId(requestBody)
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .subscribe(new ErrorHandleSingleSubscriber<BaseResult>(mErrorHandler) {

                    @Override
                    public void onSuccess(BaseResult result) {
                        if (result.isSuccess() && result.getData() != null) {
                            final GetYedPayTxnIdResponse yedPayTxnIdResponse = GsonUtils.GsonToBean(result.getData(), GetYedPayTxnIdResponse.class);
                            mRequestParms.setTxnId(yedPayTxnIdResponse.getTxnId());
                            executeAction();
                        } else {
                            mRootView.showStatusLoadingDialog(PayStep.FAILURE_OBTAIN_ID);
                            if (mResultCallback != null) {
                                mResultCallback.onFailure(null);
                            }
                        }
                    }

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

    public void getYedPayRefundTxnId(GetYedPayRefundTxnIdRequest refundTxnIdRequest) {

        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), GsonUtils.GsonString(refundTxnIdRequest));
        String json = GsonUtils.GsonString(refundTxnIdRequest);

        mModel.getYedPayRefundTxnId(requestBody)
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .subscribe(new ErrorHandleSingleSubscriber<BaseResult>(mErrorHandler) {

                    @Override
                    public void onSuccess(BaseResult result) {
                        if (result.isSuccess() && result.getData() != null) {
                            final GetYedPayTxnIdResponse yedPayTxnIdResponse = GsonUtils.GsonToBean(result.getData(), GetYedPayTxnIdResponse.class);
                            mRequestParms.setTxnId(yedPayTxnIdResponse.getTxnId());
                            executeAction();
                        } else {
                            mRootView.showStatusLoadingDialog(PayStep.FAILURE_OBTAIN_ID);
                            if (mResultCallback != null) {
                                mResultCallback.onFailure(null);
                            }
                        }
                    }

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

    public void findSaleStatus(String transactionId, long orderId, int payType, int restaurantId, String txnId) {
        RequestBody requestBody = new FormBody.Builder()
                .add("transactionId", transactionId)
                .add("orderId", orderId + "")
                .add("payType", payType + "")
                .add("restaurantId", restaurantId + "")
                .add("payId", txnId)
                .build();
        mModel.findSaleStatus(requestBody)
                .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) {
                                final Integer status = saleStatusBean.getStatus();
                                if (status != null) {
                                    mRootView.showStatusLoadingDialog(getPayStepByStatus(status));
                                    if (status == YedpayConstant.Status.PAY_STATUS_0) {
                                        if (mResultCallback != null) {
                                            mResultCallback.onSuccess();
                                        }
                                    } else {
                                        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 refundOrder(String refundReason, long orderId, int payType, int restaurantId, String txnId) {
        RequestBody requestBody = new FormBody.Builder()
                .add("refundReason", refundReason)
                .add("orderId", String.valueOf(orderId))
                .add("payType", String.valueOf(payType))
                .add("restaurantId", String.valueOf(restaurantId))
                .add("payId", txnId)
                .build();
        mModel.refundOrder(requestBody)
                .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 apply(RequestParms requestParms) {
        this.mRequestParms = requestParms;
        this.mResultCallback = mRequestParms.getResultCallback();
        switch (requestParms.getAction()) {
            case SALE:
                getYedPayTxnId(getTxnIdRequestBean(requestParms));
                break;
            case REFUND:
                getYedPayRefundTxnId(getRefundTxnIdRequestBean(requestParms));
                break;
            case RETRIEVAL:
                executeAction();
                break;
        }
    }

    public void executeAction() {
        if (mRequestParms == null) {
            mRootView.showStatusLoadingDialog(PayStep.FAILURE_OBTAIN_ID);
            return;
        }
        mRequestParms.setCommandCallback(yedpayCommand);
        switch (mRequestParms.getAction()) {
            case SALE:
                PaymentCommand.newInstance().pay(mRequestParms);
                break;
            case REFUND:
                PaymentCommand.newInstance().refund(mRequestParms);
                break;
        }
    }

    private GetYedPayRefundTxnIdRequest getRefundTxnIdRequestBean(RequestParms requestParms) {
        GetYedPayRefundTxnIdRequest refundTxnIdRequest = new GetYedPayRefundTxnIdRequest();
        refundTxnIdRequest.setOrderId(requestParms.getOrderId());
        refundTxnIdRequest.setTableId(requestParms.getTableId());
        refundTxnIdRequest.setTableExtId(requestParms.getTableExtId());
        refundTxnIdRequest.setAmount(requestParms.getPayMoney());
        return refundTxnIdRequest;
    }

    private GetYedPayTxnIdRequest getTxnIdRequestBean(RequestParms requestParms) {
        GetYedPayTxnIdRequest txnIdRequest = new GetYedPayTxnIdRequest();
        txnIdRequest.setOrderId(requestParms.getOrderId());
        txnIdRequest.setTableId(requestParms.getTableId());
        txnIdRequest.setTableExtId(requestParms.getTableExtId());
        PayMethod currPosPaymethod = requestParms.getCurrPosPaymethod();
        txnIdRequest.setPayMethodId(currPosPaymethod.getId());
        txnIdRequest.setPayType(currPosPaymethod.getPayType());
        txnIdRequest.setPayName(currPosPaymethod.getPayName());
        txnIdRequest.setAmount(requestParms.getPayMoney());
        return txnIdRequest;
    }

    private YedpayCommand yedpayCommand = new YedpayCommand() {

        @Override
        public void callSaleUri(String uri) {
            Uri uri2 = Uri.parse(uri);
            Intent intent = new Intent(Intent.ACTION_VIEW, uri2);
            mRootView.startActivityForResult2(intent, YedpayConstant.CallRequestCode.SALE_REQUEST_CODE);
        }

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

        @Override
        public void retrieval(String uri) {
            Uri uri2 = Uri.parse(uri);
            Intent intent = new Intent(Intent.ACTION_VIEW, uri2);
            mRootView.startActivityForResult2(intent, YedpayConstant.CallRequestCode.RETRIEVAL_REQUEST_CODE);
        }
    };

    private PayStep getPayStepByStatus(Integer status) {
        switch (status) {
            case YedpayConstant.Status.PAY_STATUS_0:
                return PayStep.LOADING;
            case YedpayConstant.Status.PAY_STATUS_1:
                return PayStep.FAILURE;
            case YedpayConstant.Status.PAY_STATUS_2:
                return PayStep.SUCCESS;
            case YedpayConstant.Status.PAY_STATUS_3:
                return PayStep.NOT_ARRIVED;
            case YedpayConstant.Status.PAY_STATUS_4:
                return PayStep.LOADING;
            case YedpayConstant.Status.PAY_STATUS_5:
                return PayStep.REFUNDED;
            case YedpayConstant.Status.PAY_STATUS_6:
                return PayStep.REPEAL;
            default:
                return PayStep.FAILURE_OBTAIN_ID;
        }
    }
}
