package com.gingersoft.gsa.cloud.pay.pos.hywebpos.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.core.table.TableBean;
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.order.billItem.BillItem;
import com.gingersoft.gsa.cloud.pay.bean.PayMethod;
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.PosPay;
import com.gingersoft.gsa.cloud.pay.pos.bean.PosMatter;
import com.gingersoft.gsa.cloud.pay.pos.hywebpos.bean.request.bg.GetTxnIdRequest;
import com.gingersoft.gsa.cloud.pay.pos.hywebpos.bean.request.pos.SaleRequest;
import com.gingersoft.gsa.cloud.pay.pos.hywebpos.bean.response.bg.GetTxnIdResponse;
import com.gingersoft.gsa.cloud.pay.pos.hywebpos.bean.response.pos.HywebPosResponse;
import com.gingersoft.gsa.cloud.pay.pos.hywebpos.bean.response.pos.SaleRespose;
import com.gingersoft.gsa.cloud.pay.pos.hywebpos.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.List;
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 IPosAction<SaleRespose> {

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

    private TableBean.DataBean mTableBean;
    private MealOrderPayRequest mMealOrderPayRequest;
    private List<BillItem> mBillItemList;
    private List<PayMethod> mPayMethodList;

    public SaleActionImpl(Context context, IView iView, PosAction action, SaleRequest saleRequest, GetTxnIdRequest getTxnIdRequest, TableBean.DataBean tableBean, MealOrderPayRequest mealOrderPayRequest, List<BillItem> billItemList, List<PayMethod> payMethodList, OnPosActionListener onPosActionListener, boolean showLoading) {
        super(context, iView, action, showLoading);
        this.mSaleRequest = saleRequest;
        this.mTxnIdRequest = getTxnIdRequest;
        this.mTableBean = tableBean;
        this.mMealOrderPayRequest = mealOrderPayRequest;
        this.mBillItemList = billItemList;
        this.mPayMethodList = payMethodList;
        this.mOnPosActionListener = onPosActionListener;
        if (mStatusLoadingDialog != null) {
            mStatusLoadingDialog.setOnLoadStautsListener(new StatusLoadingDialog.OnLoadStautsListener() {

                @Override
                public void loadSuccessEnd() {

                }

                @Override
                public void loadFailureEnd() {

                }
            });
        }
    }

    @Override
    protected void onPosActionBefore() {

        mTxnIdRequest.setContent(mMealOrderPayRequest.toString());
        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()));
                    }
                });
    }

    /**
     * 支付回調成功
     * 1、更新上傳支付狀態
     * 2、顯示支付結果
     * 3、跳轉支付詳情頁
     *
     * @param context
     * @param response         支付回調結果
     * @param originalActivity 原來跳轉到pos的支付頁
     */
    @Override
    public void onPosSuccess(Context context, SaleRespose response, Activity originalActivity) {
        //1、更新上傳支付狀態
        OkHttp3Utils.post(HttpsConstans.ROOT_SERVER_ADDRESS_FORMAL + "orderPay/add", getPosMatterRequest(response))
                .compose(RxSchedulerUtils._io_main_o())
                .compose(RxLifecycleUtils.bindToLifecycle(mView))
                .subscribe(new Observer<String>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        printPaymentStub();
                    }

                    @Override
                    public void onNext(String result) {

                        displayPaymentResult(context, response, originalActivity);

                        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) {
                        displayPaymentResult(context, response, originalActivity);
                        startPaymentDetailActivity(context, response);
                    }

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

    /**
     * 打印Hyweb支付存根
     */
    private void printPaymentStub() {
        PosPay.printStub(mContext, mView, mTxnIdResponse.getTxnId(),null);
    }

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

    /**
     * 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(SaleRespose response) {

        PosMatter posMatter = new PosMatter();
        posMatter.setOrderId(mTxnIdRequest.getOrderId());
        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(mMealOrderPayRequest));
        String json = GsonUtils.GsonString(mMealOrderPayRequest);

        return requestBody;
    }


}
