package com.gingersoft.gsa.cloud.pay.pos.hywebpos.imp;

import android.app.Activity;
import android.content.Context;
import android.text.TextUtils;

import com.gingersoft.gsa.cloud.common.bean.BaseResult;
import com.gingersoft.gsa.cloud.common.constans.HttpsConstans;
import com.gingersoft.gsa.cloud.common.utils.gson.GsonUtils;
import com.gingersoft.gsa.cloud.common.utils.okhttpUtils.OkHttp3Utils;
import com.gingersoft.gsa.cloud.pay.contract.PayErrorCode;
import com.gingersoft.gsa.cloud.pay.pos.IPosAction;
import com.gingersoft.gsa.cloud.pay.pos.OnPosActionListener;
import com.gingersoft.gsa.cloud.pay.pos.PosAction;
import com.gingersoft.gsa.cloud.pay.pos.bean.PosMatter;
import com.gingersoft.gsa.cloud.pay.pos.hywebpos.bean.request.bg.GetTxnIdRequest;
import com.gingersoft.gsa.cloud.pay.pos.hywebpos.bean.request.pos.RefundRequest;
import com.gingersoft.gsa.cloud.pay.pos.hywebpos.bean.response.bg.GetTxnIdResponse;
import com.gingersoft.gsa.cloud.pay.pos.hywebpos.bean.response.pos.HywebPosResponse;
import com.gingersoft.gsa.cloud.pay.pos.hywebpos.bean.response.pos.RefundRespose;
import com.gingersoft.gsa.cloud.pay.pos.hywebpos.constant.PayStatusCode;
import com.jess.arms.integration.AppManager;
import com.jess.arms.mvp.IView;
import com.jess.arms.utils.ArmsUtils;
import com.jess.arms.utils.RxLifecycleUtils;

import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import okhttp3.MediaType;
import okhttp3.RequestBody;

/**
 * @作者: bin
 * @創建時間: 2020-12-26 10:38
 * @更新時間: 2020-12-26 10:38
 * @描述:
 */
public class RefundActionImpl extends IPosAction {

    private GetTxnIdRequest mGetTxnIdRequest;
    private GetTxnIdResponse mTxnIdResponse;

    private RefundRequest mRefundRequest;

    public RefundActionImpl(Context context, IView iView, PosAction action, RefundRequest refundRequest, GetTxnIdRequest getTxnIdRequest, OnPosActionListener onPosActionListener, boolean showLoading) {
        super(context, iView, action, showLoading);
        this.mRefundRequest = refundRequest;
        this.mGetTxnIdRequest = getTxnIdRequest;
        this.mOnPosActionListener = onPosActionListener;
    }

    @Override
    protected void onRequestBefore() {

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

        OkHttp3Utils.post(HttpsConstans.ROOT_SERVER_ADDRESS_FORMAL + "posPay/getRefundTxnId", requestBody)
                .subscribeOn(Schedulers.io())
                .observeOn(Schedulers.io())
                .doOnSubscribe(disposable -> {

                })
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<String>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(String result) {
                        String error = "調起補退款異常";
                        if (!TextUtils.isEmpty(result)) {
                            BaseResult baseResult = GsonUtils.GsonToBean(result, BaseResult.class);
                            if (baseResult != null) {
                                if (baseResult.isSuccess() && baseResult.getData() != null) {
                                    mTxnIdResponse = GsonUtils.GsonToBean(baseResult.getData(), GetTxnIdResponse.class);
                                    if (mRefundRequest != null) {
                                        mRefundRequest.setTXN_ID(mTxnIdResponse.getTxnId());
                                        //調起N5退款
                                        onRequestPOS(GsonUtils.GsonString(mRefundRequest));
                                        canCelLoadingDialog();
                                    } else {
                                        onActionError(new Exception(error + PayErrorCode.tips_701));
                                    }
                                } else {
                                    onActionError(new Exception(error + PayErrorCode.tips_702));
                                }
                            } else {
                                onActionError(new Exception(error + PayErrorCode.tips_703));
                            }
                        } else {
                            onActionError(new Exception(error + PayErrorCode.tips_704));
                        }
                    }

                    @Override
                    public void onComplete() {
                    }

                    @Override
                    public void onError(Throwable t) {
                        if (mOnPosActionListener != null) {
                            mOnPosActionListener.onError(new Exception(t.getMessage()));
                        }
                    }
                });
    }

    /**
     * 退款回調成功
     * 1、更新上傳退款狀態
     * 2、顯示退款結果
     *
     * @param context
     * @param response
     * @param originalActivity
     */
    @Override
    public void onActionComplte(Context context, HywebPosResponse response, Activity originalActivity) {
        if (PayStatusCode.withException(response.getSTATUS())) {
            onActionError(new Exception("回調異常" + PayErrorCode.pos_response_102));
        } else {
            if (mOnPosActionListener != null) {
                mOnPosActionListener.onPosSuccess(response);
            }
        }
        //1、更新上傳退款狀態
        OkHttp3Utils.post(HttpsConstans.ROOT_SERVER_ADDRESS_FORMAL + "orderPay/add", getPosMatterRequest((RefundRespose) response))
                .subscribeOn(Schedulers.io())
                .observeOn(Schedulers.io())
                .doOnSubscribe(disposable -> {
                })
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .doAfterTerminate(() -> {

                })
                .compose(RxLifecycleUtils.bindToLifecycle(mView))
                .subscribe(new Observer<String>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                    }

                    @Override
                    public void onNext(String result) {

                        showRefundResult(context, response, originalActivity);

                        if (!TextUtils.isEmpty(result)) {
                            BaseResult baseResult = GsonUtils.GsonToBean(result, BaseResult.class);
                            if (baseResult != null) {
                                if (baseResult.isSuccess() && baseResult.getData() != null) {
                                    if (mOnPosActionListener != null) {
                                        mOnPosActionListener.onSuccess(response);
                                    }
                                } else {
                                    onActionError(new Exception(mPosAction.getCallbackExceptionText() + PayErrorCode.sale_412));
                                }
                            } else {
                                onActionError(new Exception(mPosAction.getCallbackExceptionText() + PayErrorCode.sale_413));
                            }
                        } else {
                            onActionError(new Exception(mPosAction.getCallbackExceptionText() + PayErrorCode.sale_414));
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        showRefundResult(context, response, originalActivity);
                        if (mOnPosActionListener != null) {
                            mOnPosActionListener.onError(e);
                        }
                    }

                    @Override
                    public void onComplete() {
                    }
                });
    }

    /**
     * 2、顯示退款結果
     *
     * @param context
     * @param response
     * @param originalActivity
     */
    private void showRefundResult(Context context, HywebPosResponse response, Activity originalActivity) {
        if (PayStatusCode.withSuccess(response.getSTATUS())) {
            //退款成功
            AppManager appManager = ArmsUtils.obtainAppComponentFromContext(context).appManager();
            Activity activity = appManager.getCurrentActivity();
            if (activity.getClass().equals(originalActivity.getClass())) {
                super.onActionComplte(context, response, originalActivity);
            }
        } else {
            //退款失敗
            onActionError(new Exception(mPosAction.getActionName() + PayStatusCode.getHywebRequestTextByCode(response.getSTATUS()) + PayErrorCode.tips_710));
        }
    }

    private RequestBody getPosMatterRequest(RefundRespose response) {

        PosMatter posMatter = new PosMatter();
        posMatter.setOrderId(mGetTxnIdRequest.getOrderId());
        posMatter.setPayId(response.getTXN_ID());
        posMatter.setContent(GsonUtils.GsonString(response));
        posMatter.setStatus(getPosMatterStatus(response.getSTATUS()));

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

        return requestBody;
    }

}
