package com.gingersoft.gsa.cloud.pay.device.pos.hyweb.imp;

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

import com.billy.cc.core.component.CC;
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.component.ComponentAction;
import com.gingersoft.gsa.cloud.component.ComponentName;
import com.gingersoft.gsa.cloud.order.bean.event.MealPayResultParam;
import com.gingersoft.gsa.cloud.order.bean.request.MealOrderPayRequest;
import com.gingersoft.gsa.cloud.pay.contract.PayExceptionCode;
import com.gingersoft.gsa.cloud.pay.device.pos.hyweb.PosCallbackListener;
import com.gingersoft.gsa.cloud.pay.PayAction;
import com.gingersoft.gsa.cloud.pay.device.pos.base.bean.PosMatter;
import com.gingersoft.gsa.cloud.pay.device.pos.hyweb.bean.request.bg.GetTxnIdRequest;
import com.gingersoft.gsa.cloud.pay.device.pos.hyweb.bean.request.pos.SaleRequest;
import com.gingersoft.gsa.cloud.pay.device.pos.hyweb.bean.response.bg.GetTxnIdResponse;
import com.gingersoft.gsa.cloud.pay.device.pos.hyweb.bean.response.pos.HywebPosResponse;
import com.gingersoft.gsa.cloud.pay.device.pos.hyweb.bean.response.pos.SaleRespose;
import com.gingersoft.gsa.cloud.pay.device.pos.hyweb.constant.HywebActionStatusCode;
import com.gingersoft.gsa.cloud.pay.widget.StatusLoadingDialog;
import com.jess.arms.mvp.IView;
import com.jess.arms.utils.RxLifecycleUtils;
import com.xuexiang.rxutil2.rxjava.RxJavaUtils;
import com.xuexiang.rxutil2.rxjava.RxSchedulerUtils;

import java.util.concurrent.TimeUnit;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import okhttp3.MediaType;
import okhttp3.RequestBody;

/**
 * @作者: bin
 * @創建時間: 2020-12-26 10:38
 * @更新時間: 2020-12-26 10:38
 * @描述:
 */
public class SaleActionImpl extends IHywebAction<SaleRespose> {

    private SaleRequest mSaleRequest;
    private GetTxnIdRequest mTxnIdRequest;
    private GetTxnIdResponse mTxnIdResponse;

    public SaleActionImpl(Context context, IView iView, PayAction action, SaleRequest saleRequest, GetTxnIdRequest getTxnIdRequest, PosCallbackListener onPosActionListener, boolean showLoading) {
        super(context, iView, action, showLoading);
        this.mSaleRequest = saleRequest;
        this.mTxnIdRequest = getTxnIdRequest;
        this.mOnPosActionListener = onPosActionListener;
        if (mStatusLoadingDialog != null) {
            mStatusLoadingDialog.setOnLoadStautsListener(new StatusLoadingDialog.OnLoadStautsListener() {

                @Override
                public void loadSuccessEnd() {

                }

                @Override
                public void loadFailureEnd() {

                }
            });
        }
    }

    @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/getTxnId", 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(), GetTxnIdResponse.class);
                                    if (mSaleRequest != null) {
                                        mSaleRequest.setTXN_ID(mTxnIdResponse.getTxnId());
                                        //調起N5支付 936E4F01A0A5473C971503433F78027E
                                        onPosToAction(GsonUtils.GsonString(mSaleRequest));
//                                        canCelLoadingDialog();
                                    } else {
                                        onBeforeActionPosError(new Exception(error + PayExceptionCode.sale_401));
                                    }
                                } else {
                                    onBeforeActionPosError(new Exception(error + baseResult.getErrMsg()));
                                }
                            } else {
                                onBeforeActionPosError(new Exception(error + PayExceptionCode.sale_403));
                            }
                        } else {
                            onBeforeActionPosError(new Exception(error + PayExceptionCode.sale_404));
                        }
                    }

                    @Override
                    public void onComplete() {
                    }

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

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

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

    @Override
    public void onPosInvalid(Context context, Activity originalActivity, SaleRespose 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, SaleRespose response, String status) {
        //1、更新上傳支付狀態
        OkHttp3Utils.post(HttpsConstans.ROOT_SERVER_ADDRESS_FORMAL + "orderPay/add", getPosMatterRequest(GsonUtils.GsonString(response), status, mTxnIdResponse.getTxnId()))
                .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, "SaleResponse onNext :" + result);

                        if (!TextUtils.isEmpty(result)) {
                            BaseResult baseResult = GsonUtils.GsonToBean(result, BaseResult.class);
                            if (baseResult != null) {
                                if (baseResult.isSuccess()) {
                                    onUpdateStatusSuccess(response);
//                                    startPaymentDetailActivity(context, 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) {
                        LoganManager.w_pay(TAG, "SaleResponse onError :" + e.getMessage());
                    }

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

    /**
     * 2、顯示支付結果
     *
     * @param context
     * @param response
     * @param originalActivity
     */
    private void displayPaymentResult(Context context, SaleRespose response, Activity originalActivity) {
        if (HywebActionStatusCode.withSuccess(response.getSTATUS())) {
            super.onPosSuccess(context, originalActivity, response);
//            startPaymentDetailActivity(context, response);
        } else if (HywebActionStatusCode.withException(response.getSTATUS())) {
            super.onPosException(context, originalActivity, response);
//            startPaymentDetailActivity(context, response);
        } else {
            super.onPosInvalid(context, originalActivity, response);
        }
    }

    /**
     * 3、跳轉支付詳情頁
     *
     * @param response
     */
    private void startPaymentDetailActivity(Context context, HywebPosResponse response) {
        MealPayResultParam payResultParam = new MealPayResultParam();
        payResultParam.setTxnId(mTxnIdResponse.getTxnId());
//        payResultParam.setTableBean(mTableBean);
//        payResultParam.setMealOrderPayRequest(mMealOrderPayRequest);
//        payResultParam.setBillItemList(mBillItemList);
//        payResultParam.setPayMethodList(mPayMethodList);
        payResultParam.setSaleRespose((SaleRespose) response);

        //等待Dialog動畫加載完再跳轉支付結果頁面
        RxJavaUtils.delay(2, TimeUnit.SECONDS)
                .subscribe(new Consumer<Long>() {
                    @Override
                    public void accept(Long aLong) throws Exception {
                        //kill orderPayActivity,orderContentActivity,mealActivity
                        CC.obtainBuilder(ComponentName.COMPONENT_TABLE)
                                .setActionName(ComponentAction.Table.KILL_MEAL_ORDER_PAY)
                                .build()
                                .call();
                        CC.obtainBuilder(ComponentName.COMPONENT_PAY)
                                .setActionName(ComponentAction.Pay.OPEN_PAY_RESULT)
                                .addParam("payResultParam", payResultParam)
                                .build()
                                .call();
                    }
                });
    }

    private RequestBody getPosMatterRequest(String response, String status, String txnId) {

        MealOrderPayRequest mealOrderPayRequest = GsonUtils.GsonToBean(mTxnIdRequest.getContent(),MealOrderPayRequest.class);

        PosMatter posMatter = new PosMatter();
        posMatter.setOrderId(mTxnIdRequest.getOrderId());
        posMatter.setPayId(txnId);
        posMatter.setContent(response);
        posMatter.setStatus(getPosMatterStatus(status));
        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;
    }


}
