package com.gingersoft.gsa.cloud.pay.device.pos.yedpay.lifecycle.presenter;

import android.app.Application;
import android.content.Intent;
import android.net.Uri;
import android.util.ArrayMap;

import com.gingersoft.gsa.cloud.common.bean.BaseResult;
import com.gingersoft.gsa.cloud.common.rxjava.ErrorHandleSingleSubscriber;
import com.gingersoft.gsa.cloud.common.utils.gson.GsonUtils;
import com.gingersoft.gsa.cloud.pay.PayStep;
import com.gingersoft.gsa.cloud.pay.PaymentCommand;
import com.gingersoft.gsa.cloud.pay.RequestParms;
import com.gingersoft.gsa.cloud.pay.ResultCallback;
import com.gingersoft.gsa.cloud.pay.device.pos.yedpay.YedpayCommand;
import com.gingersoft.gsa.cloud.pay.device.pos.yedpay.constant.YedpayConstant;
import com.gingersoft.gsa.cloud.pay.device.pos.yedpay.lifecycle.contract.YedpayMatterContract;
import com.gingersoft.gsa.cloud.pay.device.pos.yedpay.lifecycle.model.bean.response.YedpayFindSaleStatusBean;
import com.jess.arms.integration.AppManager;
import com.jess.arms.di.scope.FragmentScope;
import com.jess.arms.mvp.BasePresenter;
import com.jess.arms.http.imageloader.ImageLoader;
import com.jess.arms.utils.RxLifecycleUtils;

import me.jessyan.rxerrorhandler.core.RxErrorHandler;
import okhttp3.FormBody;
import okhttp3.RequestBody;

import javax.inject.Inject;


/**
 * ================================================
 * Description:
 * <p>
 * Created by MVPArmsTemplate on 05/10/2021 10:50
 * <a href="mailto:jess.yan.effort@gmail.com">Contact me</a>
 * <a href="https://github.com/JessYanCoding">Follow me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms">Star me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms/wiki">See me</a>
 * <a href="https://github.com/JessYanCoding/MVPArmsTemplate">模版请保持更新</a>
 * ================================================
 */
@FragmentScope
public class YedpayMatterPresenter extends BasePresenter<YedpayMatterContract.Model, YedpayMatterContract.View> {
    @Inject
    RxErrorHandler mErrorHandler;
    @Inject
    Application mApplication;
    @Inject
    ImageLoader mImageLoader;
    @Inject
    AppManager mAppManager;

    private RequestParms mRequestParms;
    private ResultCallback mResultCallback;

    private ArrayMap<Integer, String> mSaleStatusNameArrayMap;

    @Inject
    public YedpayMatterPresenter(YedpayMatterContract.Model model, YedpayMatterContract.View rootView) {
        super(model, rootView);
        initSaleStatusNameArrayMap();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        this.mErrorHandler = null;
        this.mAppManager = null;
        this.mImageLoader = null;
        this.mApplication = null;
    }

    /**
     * 查詢支付狀態，後台會更新事項記錄
     *
     * @param transactionId
     * @param orderId
     * @param payType
     * @param restaurantId
     * @param txnId
     */
    public void findSaleStatus(String transactionId, long orderId, int payType, int restaurantId, String txnId) {
        RequestBody requestBody = new FormBody.Builder()
                .add("transactionId", transactionId)
                .add("orderId", orderId + "")
                .add("payType", payType + "")
                .add("restaurantId", restaurantId + "")
                .add("txnId", txnId)
                .build();
        mModel.findSaleStatus(requestBody)
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .subscribe(new ErrorHandleSingleSubscriber<BaseResult>(mErrorHandler) {

                    @Override
                    public void onSuccess(BaseResult result) {
                        if (result.isSuccess()) {
                            YedpayFindSaleStatusBean saleStatusBean = GsonUtils.GsonToBean(result.getData(), YedpayFindSaleStatusBean.class);
                            if (saleStatusBean != null) {
                                final Integer status = saleStatusBean.getStatus();
                                if (status != null) {
                                    if (mSaleStatusNameArrayMap.containsKey(status)) {
                                        final String name = mSaleStatusNameArrayMap.get(status);
                                        final boolean saleStatus = getSaleStatusByStatus(status);
                                        mRootView.setPosMatterStep(saleStatus, name);
                                    }
                                }
                            } else {
                                mRootView.setPosMatterStep(false, "查詢失敗");
                            }
                        } else {
                            mRootView.setPosMatterStep(false, "查詢失敗");
                        }
                    }

                    @Override
                    public void onError(Throwable t) {
                        super.onError(t);
                        mRootView.setPosMatterStep(false, "查詢失敗");
                    }
                });
    }

    private void initSaleStatusNameArrayMap() {
        mSaleStatusNameArrayMap = new ArrayMap<>();
        mSaleStatusNameArrayMap.put(YedpayConstant.Status.PAY_STATUS_0, "未支付");
        mSaleStatusNameArrayMap.put(YedpayConstant.Status.PAY_STATUS_1, "支付失敗");
        mSaleStatusNameArrayMap.put(YedpayConstant.Status.PAY_STATUS_2, "支付成功");
        mSaleStatusNameArrayMap.put(YedpayConstant.Status.PAY_STATUS_3, "已支付未到賬");
        mSaleStatusNameArrayMap.put(YedpayConstant.Status.PAY_STATUS_4, "支付中");
        mSaleStatusNameArrayMap.put(YedpayConstant.Status.PAY_STATUS_5, "已退款");
        mSaleStatusNameArrayMap.put(YedpayConstant.Status.PAY_STATUS_6, "廢棄(第二次結賬)");
    }

    private boolean getSaleStatusByStatus(Integer status) {
        switch (status) {
            case YedpayConstant.Status.PAY_STATUS_0:
            case YedpayConstant.Status.PAY_STATUS_1:
            case YedpayConstant.Status.PAY_STATUS_4:
            case YedpayConstant.Status.PAY_STATUS_6:
                return false;
            case YedpayConstant.Status.PAY_STATUS_2:
            case YedpayConstant.Status.PAY_STATUS_3:
            case YedpayConstant.Status.PAY_STATUS_5:
                return true;
        }
        return false;
    }

    public void executeRetrieval(RequestParms requestParms) {
        this.mRequestParms = requestParms;
        this.mResultCallback = mRequestParms.getResultCallback();
        mRequestParms.setCommandCallback(yedpayCommand);

        PaymentCommand.newInstance().retrieval(mRequestParms);
    }

    private YedpayCommand yedpayCommand = new YedpayCommand() {

        @Override
        public void callSaleUri(String uri) {
        }

        @Override
        public void refundResult(boolean result) {
        }

        @Override
        public void retrieval(String uri) {
            Uri uri2 = Uri.parse(uri);
            Intent intent = new Intent(Intent.ACTION_VIEW, uri2);
            mRootView.startActivityForResult2(intent, YedpayConstant.CallRequestCode.RETRIEVAL_REQUEST_CODE);
        }
    };
}
