package com.gingersoft.gsa.cloud.pay.pos.hyweb.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.hyweb.PosCallbackListener;
import com.gingersoft.gsa.cloud.pay.PayAction;
import com.gingersoft.gsa.cloud.pay.pos.bean.PosMatter;
import com.gingersoft.gsa.cloud.pay.pos.hyweb.bean.request.bg.GetTxnIdRequest;
import com.gingersoft.gsa.cloud.pay.pos.hyweb.bean.request.pos.RefundRequest;
import com.gingersoft.gsa.cloud.pay.pos.hyweb.bean.response.bg.GetRefundIdResponse;
import com.gingersoft.gsa.cloud.pay.pos.hyweb.bean.response.pos.RefundRespose;
import com.gingersoft.gsa.cloud.pay.pos.hyweb.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 RefundActionImpl extends IHywebAction<RefundRespose> {

    private GetTxnIdRequest mGetTxnIdRequest;
    private GetRefundIdResponse mGetRefundIdResponse;

    private RefundRequest mRefundRequest;

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

    @Override
    public void onPosActionBefore() {

        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)
                .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) {
                                    mGetRefundIdResponse = GsonUtils.GsonToBean(baseResult.getData(), GetRefundIdResponse.class);
                                    if (mRefundRequest != null) {
                                        mRefundRequest.setTXN_ID(mGetRefundIdResponse.getRefundId());
                                        //調起N5退款
                                        onPosToAction(GsonUtils.GsonString(mRefundRequest));
                                    } else {
                                        onBeforeActionPosError(new Exception(error + PayExceptionCode.refund_901));
                                    }
                                } else {
                                    onBeforeActionPosError(new Exception(error + baseResult.getErrMsg()));
                                }
                            } else {
                                onBeforeActionPosError(new Exception(error + PayExceptionCode.refund_903));
                            }
                        } else {
                            onBeforeActionPosError(new Exception(error + PayExceptionCode.refund_904));
                        }
                    }

                    @Override
                    public void onComplete() {
                    }

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

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

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

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

    /**
     * 退款回調
     * 1、更新上傳退款狀態
     * 2、顯示退款結果
     *
     * @param context
     * @param response
     * @param originalActivity
     * @param status
     */
    private void updateMatter(Context context, Activity originalActivity, RefundRespose response, String status){
        //1、更新上傳退款狀態
        OkHttp3Utils.post(HttpsConstans.ROOT_SERVER_ADDRESS_FORMAL + "orderPay/updatePosRefund", 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, "RefundResponse 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.refund_913));
                            }
                        } else {
                            onUpdateStatusError(new Exception(mPosAction.getCallbackExceptionText() + PayExceptionCode.refund_914));
                        }
                    }

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

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

    /**
     * 2、顯示退款結果
     *
     * @param context
     * @param response
     * @param originalActivity
     */
    private void displayRefundResult(Context context, RefundRespose 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(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);

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

        return requestBody;
    }

}
