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.VoidRequest;
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.VoidRespose;
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 VoidActionImpl extends IPosAction {

    private VoidRequest mVoidRequest;

    private GetTxnIdRequest mTxnIdRequest;
    private GetTxnIdResponse mTxnIdResponse;

    private OnPosActionListener mOnPosActionListener;

    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 onRequestBefore() {
        OkHttp3Utils.post(HttpsConstans.ROOT_SERVER_ADDRESS_FORMAL + "posPay/getRefundTxnId", null)
                .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 (mVoidRequest != null) {
                                        mVoidRequest.setTXN_ID(mTxnIdResponse.getTxnId());
                                        //調起N5取消訂單
                                        onRequestPOS(GsonUtils.GsonString(mVoidRequest));
                                        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) {
                        onActionError(new Exception(t.getMessage()));
                    }
                });
    }


    /**
     * 取消回調成功
     * 1、顯示取消結果
     * 2、更新上傳取消狀態
     * 3、刷新當前頁面
     *
     * @param context
     * @param response
     * @param originalActivity
     */
    @Override
    public void onActionComplte(Context context, HywebPosResponse response, Activity originalActivity) {

        //1、顯示取消結果
        showVoidResult(context, response, originalActivity);

        //2、更新上傳取消狀態
        OkHttp3Utils.post(HttpsConstans.ROOT_SERVER_ADDRESS_FORMAL + "orderPay/updatePosCancel", getPosMatterRequest((VoidRespose) 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) {
                        if (!TextUtils.isEmpty(result)) {
                            BaseResult baseResult = GsonUtils.GsonToBean(result, BaseResult.class);
                            if (baseResult != null) {
                                if (baseResult.isSuccess() && baseResult.getData() != null) {

                                } else {
//                                    onActionError(new Exception(mPosAction.getCallbackExceptionText() + PayErrorCode.tips_711));
                                }
                            } else {
//                                onActionError(new Exception(mPosAction.getCallbackExceptionText() + PayErrorCode.tips_712));
                            }
                        } else {
//                            onActionError(new Exception(mPosAction.getCallbackExceptionText() + PayErrorCode.tips_713));
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        if (mOnPosActionListener != null) {
                            mOnPosActionListener.onError(e);
                        }
                    }

                    @Override
                    public void onComplete() {
                        if (mOnPosActionListener != null) {
                            mOnPosActionListener.onSuccess(response);
                        }
                    }
                });
    }

    /**
     * 1、顯示小費結果
     *
     * @param context
     * @param response
     * @param originalActivity
     */
    private void showVoidResult(Context context, HywebPosResponse response, Activity originalActivity) {
        if (response.getSTATUS().equals(PayStatusCode.PAY_STATUS_00)) {
            //補小費成功
            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(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);

        return requestBody;
    }
}
