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

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

import com.etps.aca.lib.constant.Constant;
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.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.pos.RetrievalRequest;
import com.gingersoft.gsa.cloud.pay.pos.hywebpos.bean.response.pos.RetrievalRespose;
import com.gingersoft.gsa.cloud.pay.pos.hywebpos.bean.response.pos.SettlementRespose;
import com.gingersoft.gsa.cloud.pay.pos.hywebpos.constant.HywebActionStatusCode;
import com.gingersoft.gsa.cloud.pay.pos.hywebpos.constant.TransactionStatusCode;
import com.jess.arms.mvp.IView;
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 RetrievalActionImpl extends IPosAction<RetrievalRespose> {

    private RetrievalRequest mRetrievalRequest;
    private Long mOrderId;
    private PosAction mRetrievalAction;

    public RetrievalActionImpl(Context context, IView iView, PosAction action, PosAction retrievalAction, Long orderId, RetrievalRequest request, OnPosActionListener onPosActionListener, boolean showLoading) {
        super(context, iView, action, showLoading);
        this.mOrderId = orderId;
        this.mRetrievalRequest = request;
        this.mRetrievalAction = retrievalAction;
        this.mOnPosActionListener = onPosActionListener;
    }

    @Override
    protected void onPosActionBefore() {
        //調起N5狀態查詢
        onPosToAction(GsonUtils.GsonString(mRetrievalRequest));
    }

    /**
     * 查詢回調成功
     * 1、更新上傳狀態
     * 2、顯示查询結果
     *
     * @param context
     * @param response
     * @param originalActivity
     */
    @Override
    public void onPosSuccess(Context context, RetrievalRespose response, Activity originalActivity) {

        String url = null;
        RequestBody requestBody;
        switch (response.getTXN_TYPE()) {
            case Constant.EVENT.NAME.SALE:
                if (mRetrievalAction == PosAction.TIP) {
                    //查詢補消費狀態
                    url = "posPay/updatePosTip";
                    requestBody = getPosMatterTipsRequest(response);
                } else if (mRetrievalAction == PosAction.VOID) {
                    //查詢取消狀態
                    url = "posPay/updatePosCancel";
                    requestBody = getPosMatterVoidRequest(response);
                } else {
                    //查詢支付狀態
                    url = "posPay/updatePosMatter";
                    requestBody = getPosMatterSaleRequest(response);
                }
                break;
            case Constant.EVENT.NAME.REFUND:
                url = "posPay/updatePosRefund";
                requestBody = getPosMatterRefundRequest(response);
                break;
//            case Constant.EVENT.NAME.VOID_RESP:
//                requestBody = getPosMatterVoidRequest((VoidRespose) response);
//                break;
//            case Constant.EVENT.NAME.ADJUST_RESP:
//                requestBody = getPosMatterTipsRequest((AdjustTipRespose) response);
//                break;
//            case "SETTLE_RESP":
//                requestBody = getPosMatterSettlementRequest((SettlementRespose) response);
//                break;
            default:
                return;
        }
        //1、更新上傳狀態
        OkHttp3Utils.post(HttpsConstans.ROOT_SERVER_ADDRESS_FORMAL + url, 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) {

                        displayRetrievalResult(context, response, originalActivity);

                        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.sale_413));
                            }
                        } else {
                            onUpdateStatusError(new Exception(mPosAction.getCallbackExceptionText() + PayExceptionCode.sale_414));
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        displayRetrievalResult(context, response, originalActivity);
                    }

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

    /**
     * 2、顯示查询結果
     *
     * @param context
     * @param response
     * @param originalActivity
     */
    private void displayRetrievalResult(Context context, RetrievalRespose response, Activity originalActivity) {
        if (HywebActionStatusCode.withException(response.getSTATUS())) {
            super.onPosException(new Exception(response.getSTATUS()));
        } else {
            super.onPosSuccess(context, response, originalActivity);
        }
    }

    private RequestBody getPosMatterSaleRequest(RetrievalRespose response) {

        PosMatter posMatter = new PosMatter();
        posMatter.setOrderId(mOrderId);
        posMatter.setPayId(response.getTXN_ID());
        posMatter.setContent(GsonUtils.GsonString(response));
        posMatter.setStatus(getPosMatterStatus(response.getSTATUS()));
//        mMealOrderPayRequest.setPosMatter(posMatter);

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

        return requestBody;
    }

    private RequestBody getPosMatterRefundRequest(RetrievalRespose response) {
        PosMatter posMatter = new PosMatter();
        posMatter.setOrderId(mOrderId);
        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;
    }

    private RequestBody getPosMatterVoidRequest(RetrievalRespose response) {
        PosMatter posMatter = new PosMatter();
        posMatter.setOrderId(mOrderId);
        posMatter.setPayId(response.getTXN_ID());
        posMatter.setContent(GsonUtils.GsonString(response));
        if (response.getTXN_STATUS().equals(TransactionStatusCode.TXN_STATUS_V)) {
            //TXN_STATUS:V 訂單已取消
            posMatter.setStatus(getPosMatterStatus(response.getSTATUS()));
        } else {
            posMatter.setStatus(getPosMatterStatus(HywebActionStatusCode.PAY_STATUS_99));
        }
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), GsonUtils.GsonString(posMatter));
        String json = GsonUtils.GsonString(posMatter);
        return requestBody;
    }

    private RequestBody getPosMatterTipsRequest(RetrievalRespose response) {

        PosMatter posMatter = new PosMatter();
        posMatter.setOrderId(mOrderId);
        posMatter.setTipsPrice(response.getTIPS());
        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;
    }


    private RequestBody getPosMatterSettlementRequest(SettlementRespose response) {
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), GsonUtils.GsonString(response));
        String json = GsonUtils.GsonString(response);
        return requestBody;
    }

}
