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.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.order.bean.request.MealOrderPayRequest;
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.RefundRespose;
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.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 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));
    }

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

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

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

    /**
     * 查詢回調成功
     * 1、更新上傳狀態
     * 2、顯示查询結果
     *
     * @param context
     * @param originalActivity
     * @param response
     * @param status
     */
    private void updateMatter(Context context, Activity originalActivity, RetrievalRespose response, String status) {
        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 = "orderPay/add";
                    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) {

                        LoganManager.w_pay(TAG, "RetrievalResponse 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.retrieval_513));
                            }
                        } else {
                            onUpdateStatusError(new Exception(mPosAction.getCallbackExceptionText() + PayExceptionCode.retrieval_514));
                        }
                    }

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

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

    /**
     * 2、顯示查询結果
     *
     * @param context
     * @param response
     * @param originalActivity
     */
    private void displayRetrievalResult(Context context, RetrievalRespose 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 getPosMatterSaleRequest(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_A)) {
            //TXN_STATUS:A 支付成功
            posMatter.setStatus(PosMatter.status_1);
        } else {
            posMatter.setStatus(getPosMatterStatus(HywebActionStatusCode.PAY_STATUS_99));
        }
        MealOrderPayRequest mealOrderPayRequest = new MealOrderPayRequest();
        mealOrderPayRequest.setPosMatter(posMatter);

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

        LoganManager.w_pay(TAG, "SaleRequest JSON :" + json);
        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);

        LoganManager.w_pay(TAG, "RefundRequest JSON :" + json);
        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);

        LoganManager.w_pay(TAG, "VoidRequest JSON :" + json);
        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);

        LoganManager.w_pay(TAG, "TipRequest JSON :" + json);
        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;
    }

}
