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.logan.LoganManager;
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.PayExceptionCode;
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.VoidRequest;
import com.gingersoft.gsa.cloud.pay.pos.hywebpos.bean.response.bg.GetCancelTxnIdResponse;
import com.gingersoft.gsa.cloud.pay.pos.hywebpos.bean.response.pos.VoidRespose;
import com.gingersoft.gsa.cloud.pay.pos.hywebpos.constant.HywebActionStatusCode;
import com.jess.arms.mvp.IView;
import com.jess.arms.utils.RxLifecycleUtils;
import com.xuexiang.rxutil2.rxjava.RxSchedulerUtils;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import okhttp3.MediaType;
import okhttp3.RequestBody;

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

    private VoidRequest mVoidRequest;

    private GetTxnIdRequest mTxnIdRequest;
    private GetCancelTxnIdResponse mTxnIdResponse;

    public VoidActionImpl(Context context, IView iView, PosAction action, VoidRequest voidRequest, GetTxnIdRequest txnIdRequest, OnPosActionListener onPosActionListener, boolean showLoading) {
        super(context, iView, action, showLoading);
        this.mTxnIdRequest = txnIdRequest;
        this.mVoidRequest = voidRequest;
        this.mOnPosActionListener = onPosActionListener;
    }

    @Override
    protected void onPosActionBefore() {

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

        OkHttp3Utils.post(HttpsConstans.ROOT_SERVER_ADDRESS_FORMAL + "posPay/getCancelTxnId", requestBody)
                .compose(RxSchedulerUtils._io_main_o())
                .compose(RxLifecycleUtils.bindToLifecycle(mView))
                .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(), GetCancelTxnIdResponse.class);
                                    if (mVoidRequest != null) {
                                        mVoidRequest.setTXN_ID(mTxnIdResponse.getCancelTxnId());
                                        //調起N5取消訂單
                                        onPosToAction(GsonUtils.GsonString(mVoidRequest));
//                                        canCelLoadingDialog();
                                    } else {
                                        onBeforeActionPosError(new Exception(error + PayExceptionCode.void_801));
                                    }
                                } else {
                                    onBeforeActionPosError(new Exception(error + baseResult.getErrMsg()));
                                }
                            } else {
                                onBeforeActionPosError(new Exception(error + PayExceptionCode.void_803));
                            }
                        } else {
                            onBeforeActionPosError(new Exception(error + PayExceptionCode.void_804));
                        }
                    }

                    @Override
                    public void onComplete() {
                    }

                    @Override
                    public void onError(Throwable t) {
                        onBeforeActionPosError(new Exception(t.getMessage()));
                    }
                });
    }

    @Override
    public void onPosSuccess(Context context, Activity originalActivity, VoidRespose response) {
        updateMatter(context, originalActivity, response, response.getSTATUS());
    }

    @Override
    public void onPosException(Context context, Activity originalActivity, VoidRespose response) {
        updateMatter(context, originalActivity, response, response.getSTATUS());
    }

    @Override
    public void onPosInvalid(Context context, Activity originalActivity, VoidRespose response) {
        updateMatter(context, originalActivity, response, response.getSTATUS());
    }

    /**
     * 取消回調成功
     * <p>
     * 1、更新上傳取消狀態
     * 2、顯示取消結果
     * 3、刷新當前頁面
     *
     * @param context
     * @param originalActivity
     * @param response
     * @param status
     */
    private void updateMatter(Context context, Activity originalActivity, VoidRespose response, String status) {
        //1、更新上傳取消狀態
        OkHttp3Utils.post(HttpsConstans.ROOT_SERVER_ADDRESS_FORMAL + "posPay/updatePosCancel", getPosMatterRequest(response))
                .compose(RxSchedulerUtils._io_main_o())
                .compose(RxLifecycleUtils.bindToLifecycle(mView))
                .subscribe(new Observer<String>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                    }

                    @Override
                    public void onNext(String result) {

                        LoganManager.w_pay(TAG, "VoidResponse onNext :" + result);

                        if (!TextUtils.isEmpty(result)) {
                            BaseResult baseResult = GsonUtils.GsonToBean(result, BaseResult.class);
                            if (baseResult != null) {
                                if (baseResult.isSuccess()) {
                                    onUpdateStatusSuccess(response);
                                } else {
                                    onUpdateStatusError(new Exception(mPosAction.getCallbackExceptionText() + baseResult.getErrMsg()));
                                }
                            } else {
                                onUpdateStatusError(new Exception(mPosAction.getCallbackExceptionText() + PayExceptionCode.void_811));
                            }
                        } else {
                            onUpdateStatusError(new Exception(mPosAction.getCallbackExceptionText() + PayExceptionCode.void_812));
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        LoganManager.w_pay(TAG, "VoidResponse onError :" + e.getMessage());
                    }

                    @Override
                    public void onComplete() {
                        displayVoidResult(context, response, originalActivity);
                    }
                });
    }

    /**
     * 2、顯示取消結果
     *
     * @param context
     * @param response
     * @param originalActivity
     */
    private void displayVoidResult(Context context, VoidRespose response, Activity originalActivity) {
        if (HywebActionStatusCode.withSuccess(response.getSTATUS())) {
            super.onPosSuccess(context, originalActivity, response);
        } else if (HywebActionStatusCode.withException(response.getSTATUS())) {
            super.onPosException(context, originalActivity, response);
        } else {
            super.onPosInvalid(context, originalActivity, response);
        }
    }

    private RequestBody getPosMatterRequest(VoidRespose response) {

        PosMatter posMatter = new PosMatter();
        posMatter.setOrderId(mTxnIdRequest.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);

        LoganManager.w_pay(TAG, "VoidRequest JSON :" + json);

        return requestBody;
    }
}
