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.AdjustTipRequest;
import com.gingersoft.gsa.cloud.pay.pos.hyweb.bean.response.bg.GetTipTxnIdResponse;
import com.gingersoft.gsa.cloud.pay.pos.hyweb.bean.response.pos.AdjustTipRespose;
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 TipsActionImpl extends IHywebAction<AdjustTipRespose> {


    private AdjustTipRequest mAdjustTipRequest;

    private GetTxnIdRequest mTxnIdRequest;
    private GetTipTxnIdResponse mTxnIdResponse;

    public TipsActionImpl(Context context, IView iView, PayAction action, GetTxnIdRequest txnIdRequest, AdjustTipRequest adjustTipRequest, PosCallbackListener onPosActionListener, boolean showLoading) {
        super(context, iView, action, showLoading);
        this.mTxnIdRequest = txnIdRequest;
        this.mAdjustTipRequest = adjustTipRequest;
        this.mOnPosActionListener = onPosActionListener;
    }

    @Override
    public 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/getTipTxnId", 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(), GetTipTxnIdResponse.class);
                                    if (mAdjustTipRequest != null) {
                                        mAdjustTipRequest.setTXN_ID(mTxnIdResponse.getTipTxnId());
                                        //調起N5補小費
                                        onPosToAction(GsonUtils.GsonString(mAdjustTipRequest));
//                                        canCelLoadingDialog();
                                    } else {
                                        onBeforeActionPosError(new Exception(error + baseResult.getErrMsg()));
                                    }
                                } else {
                                    if (!TextUtils.isEmpty(baseResult.getErrMsg())) {
                                        onBeforeActionPosError(new Exception(baseResult.getErrMsg()));
                                    } else {
                                        onBeforeActionPosError(new Exception(error + PayExceptionCode.tips_702));
                                    }
                                }
                            } else {
                                onBeforeActionPosError(new Exception(error + PayExceptionCode.tips_703));
                            }
                        } else {
                            onBeforeActionPosError(new Exception(error + PayExceptionCode.tips_704));
                        }
                    }

                    @Override
                    public void onComplete() {
                    }

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

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

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

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

    /**
     * 補小費回調成功
     * 1、更新上傳小費狀態
     * 2、顯示小費結果
     * 3、刷新當前頁面
     *
     * @param context
     * @param originalActivity
     * @param response
     * @param status
     */
    private void updateMatter(Context context, Activity originalActivity, AdjustTipRespose response, String status) {
        //1、更新上傳小費狀態
        OkHttp3Utils.post(HttpsConstans.ROOT_SERVER_ADDRESS_FORMAL + "posPay/updatePosTip", 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, "TipResponse 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() + PayExceptionCode.tips_711));
                                    onUpdateStatusError(new Exception(mPosAction.getCallbackExceptionText() + "["+baseResult.getErrMsg()+"]"));
                                }
                            } else {
                                onUpdateStatusError(new Exception(mPosAction.getCallbackExceptionText() + PayExceptionCode.tips_712));
                            }
                        } else {
                            onUpdateStatusError(new Exception(mPosAction.getCallbackExceptionText() + PayExceptionCode.tips_713));
                        }
                    }

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

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

    /**
     * 2、顯示小費結果
     *
     * @param context
     * @param response
     * @param originalActivity
     */
    private void displayTipsResult(Context context, AdjustTipRespose 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(AdjustTipRespose response) {

        PosMatter posMatter = new PosMatter();
        posMatter.setOrderId(mTxnIdRequest.getOrderId());
        posMatter.setTipsPrice(response.getTIPS());
        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, "TipRequest JSON :" + json);

        return requestBody;
    }


}
