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.PayErrorCode;
import com.gingersoft.gsa.cloud.pay.pos.IPosAction;
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.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.PayStatusCode;
import com.gingersoft.gsa.cloud.pay.widget.StatusLoadingDialog;
import com.jess.arms.mvp.IView;
import com.jess.arms.utils.RxLifecycleUtils;

import java.util.List;

import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import okhttp3.MediaType;
import okhttp3.RequestBody;

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

    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, 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;
        if (mStatusLoadingDialog != null) {
            mStatusLoadingDialog.setOnLoadStautsListener(new StatusLoadingDialog.OnLoadStautsListener() {

                @Override
                public void loadSuccessEnd() {

                }

                @Override
                public void loadFailureEnd() {

                }
            });
        }

    }

    @Override
    protected void onRequestBefore() {

        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)
                .subscribeOn(Schedulers.io())
                .observeOn(Schedulers.io())
                .doOnSubscribe(disposable -> {

                })
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .doAfterTerminate(() -> {
                })
                .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
                                        onRequestPOS(GsonUtils.GsonString(mSaleRequest));
                                        canCelLoadingDialog();
                                    } else {
                                        onActionError(new Exception(error + PayErrorCode.sale_401));
                                    }
                                } else {
                                    onActionError(new Exception(error + PayErrorCode.sale_402));
                                }
                            } else {
                                onActionError(new Exception(error + PayErrorCode.sale_403));
                            }
                        } else {
                            onActionError(new Exception(error + PayErrorCode.sale_404));
                        }
                    }

                    @Override
                    public void onComplete() {
                    }

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

    /**
     * 支付回調成功
     * 1、更新上傳支付狀態
     * 2、顯示支付結果
     * 3、跳轉支付詳情頁
     *
     * @param context
     * @param response         支付回調結果
     * @param originalActivity 原來跳轉到pos的支付頁
     */
    @Override
    public void onActionComplte(Context context, HywebPosResponse response, Activity originalActivity) {
        if (PayStatusCode.withException(response.getSTATUS())) {
            onActionError(new Exception("回調異常" + PayErrorCode.pos_response_102));
        } else {
            if (mOnPosActionListener != null) {
                mOnPosActionListener.onPosSuccess(response);
            }
        }
        //1、更新上傳支付狀態
        OkHttp3Utils.post(HttpsConstans.ROOT_SERVER_ADDRESS_FORMAL + "orderPay/add", getPosMatterRequest((SaleRespose) response))
                .subscribeOn(Schedulers.io())
                .observeOn(Schedulers.io())
                .doOnSubscribe(disposable -> {
                })
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .doAfterTerminate(() -> {

                })
                .compose(RxLifecycleUtils.bindToLifecycle(mView))
                .subscribe(new Observer<String>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                    }

                    @Override
                    public void onNext(String result) {

                        showPayResult(context, response, originalActivity);

                        if (!TextUtils.isEmpty(result)) {
                            BaseResult baseResult = GsonUtils.GsonToBean(result, BaseResult.class);
                            if (baseResult != null) {
                                if (baseResult.isSuccess() && baseResult.getData() != null) {
                                    if (mOnPosActionListener != null) {
                                        mOnPosActionListener.onSuccess(response);
                                    }
                                    startPayResultActivity(context, response);
                                } else {
                                    onActionError(new Exception(mPosAction.getCallbackExceptionText() + PayErrorCode.sale_412));
                                }
                            } else {
                                onActionError(new Exception(mPosAction.getCallbackExceptionText() + PayErrorCode.sale_413));
                            }
                        } else {
                            onActionError(new Exception(mPosAction.getCallbackExceptionText() + PayErrorCode.sale_414));
                        }
                    }

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

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

    /**
     * 2、顯示支付結果
     *
     * @param context
     * @param response
     * @param originalActivity
     */
    private void showPayResult(Context context, HywebPosResponse response, Activity originalActivity) {
        super.onActionComplte(context, response, originalActivity);
    }

    /**
     * 3、跳轉支付詳情頁
     *
     * @param response
     */
    private void startPayResultActivity(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);

        //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;
    }

    @Override
    public void onActionError(Exception error) {
        super.onActionError(error);
    }


}
