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.MealPayResultEvent;
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.integration.AppManager;
import com.jess.arms.mvp.IView;
import com.jess.arms.utils.ArmsUtils;
import com.jess.arms.utils.RxLifecycleUtils;

import org.simple.eventbus.EventBus;

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支付
                                        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) {
        //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) {
                                    startPayResultActivity(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(response);
                    }

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

    /**
     * 2、顯示支付結果
     *
     * @param context
     * @param response
     * @param originalActivity
     */
    private void showPayResult(Context context, HywebPosResponse response, Activity originalActivity) {
        if (response.getSTATUS().equals(PayStatusCode.PAY_STATUS_00)) {
            //支付成功
            AppManager appManager = ArmsUtils.obtainAppComponentFromContext(context).appManager();
            Activity activity = appManager.getCurrentActivity();
            if (activity.getClass().equals(originalActivity.getClass())) {
                super.onActionComplte(context, response, originalActivity);
            }
        } else {
            //支付失敗
            onActionError(new Exception(mPosAction.getActionName() + PayStatusCode.getHywebRequestTextByCode(response.getSTATUS()) + PayErrorCode.tips_710));
        }
    }

    /**
     * 3、跳轉支付詳情頁
     *
     * @param response
     */
    private void startPayResultActivity(HywebPosResponse response) {
        CC.obtainBuilder(ComponentName.COMPONENT_PAY)
                .setActionName(ComponentAction.Pay.OPEN_PAY_RESULT)
                .build()
                .call();
        MealPayResultEvent payResultEvent = new MealPayResultEvent();
        payResultEvent.setTxnId(mTxnIdResponse.getTxnId());
        payResultEvent.setTableBean(mTableBean);
        payResultEvent.setMealOrderPayRequest(mMealOrderPayRequest);
        payResultEvent.setBillItemList(mBillItemList);
        payResultEvent.setPayMethodList(mPayMethodList);
        payResultEvent.setSaleRespose((SaleRespose) response);
        EventBus.getDefault().post(payResultEvent, "onIntentPayStatusSuccess");
    }

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


}
