package com.gingersoft.gsa.cloud.table.app.payment;

import android.content.Context;
import android.os.Handler;
import android.os.Message;

import com.etps.aca.lib.constant.Constant;
import com.etps.aca.lib.util.CommandUtil;
import com.gingersoft.gsa.cloud.base.utils.gson.GsonUtils;
import com.gingersoft.gsa.cloud.base.utils.log.LogUtil;
import com.gingersoft.gsa.cloud.table.app.payment.bean.AdjustTipRequest;
import com.gingersoft.gsa.cloud.table.app.payment.bean.PayRequest;
import com.gingersoft.gsa.cloud.table.app.payment.bean.RefundRequest;
import com.gingersoft.gsa.cloud.table.app.payment.bean.RetrievalRequest;
import com.gingersoft.gsa.cloud.table.app.payment.bean.SettlementRequest;
import com.gingersoft.gsa.cloud.table.app.payment.bean.VoidRequest;
import com.gingersoft.gsa.cloud.table.app.payment.contract.IN5Action;
import com.gingersoft.gsa.cloud.table.app.printer.PrintPaymentStub;
import com.gingersoft.gsa.cloud.ui.widget.dialog.LoadingDialog;

import java.util.Timer;
import java.util.TimerTask;

/**
 * 作者：ELEGANT_BIN
 * 版本：1.6.0
 * 创建日期：2019/6/13
 * 修订历史：2019/6/13
 * 描述：
 */
public class N5ActionManage implements IN5Action {

    private final String TAG = this.getClass().getSimpleName();
    private static N5ActionManage sInstance;

    /**
     * 期望:
     * 1.timeout時間120秒 > 等待回應(成功, 失敗, 繁忙BUSY(97代表中端繁忙)等狀態)
     * 2.120秒內每次收到繁忙都繼續等待, 直到120秒
     * 3.120秒後每5秒調用一次, 合共12次如果仍然繁忙或沒有回應請退出
     */
    private final long actionTimeout = 120 * 1000;
    private final int queryCount = 2;
    private final long queryInterval = 2 * 1000;

    private boolean cancel;

    public static N5ActionManage getInstance() {
        if (sInstance == null) {
            sInstance = new N5ActionManage();
        }
        return sInstance;
    }

    private N5ActionManage() {

    }


    @Override
    public void sendSaleRequest(Context context, PayRequest request) {
        String payRequest = GsonUtils.GsonString(request);
//        setRequestTimeout(context, Constant.EVENT.NAME.SALE, request.getTXN_ID(), false);
        CommandUtil.sendRequest(context, payRequest);
    }

    @Override
    public void sendVoidRequest(Context context, VoidRequest request) {
        String voidRequest = GsonUtils.GsonString(request);
//        setRequestTimeout(context, Constant.EVENT.NAME.VOID, request.getTXN_ID(), false);
        CommandUtil.sendRequest(context, voidRequest);
    }

    @Override
    public void sendRefundRequest(Context context, RefundRequest request) {
        String refundRequest = GsonUtils.GsonString(request);
//        setRequestTimeout(context, Constant.EVENT.NAME.REFUND, request.getTXN_ID(), false);
        CommandUtil.sendRequest(context, refundRequest);
    }

    @Override
    public void sendAdjustTipResuest(Context context, AdjustTipRequest request) {
        String adjustRequest = GsonUtils.GsonString(request);
//        setRequestTimeout(context, Constant.EVENT.NAME.ADJUST, request.getTXN_ID(), false);
        CommandUtil.sendRequest(context, adjustRequest);
    }

    @Override
    public void sendPrintPaymentStubRequest(Context context, PrintPaymentStub request) {
        String adjustRequest = GsonUtils.GsonString(request);
        CommandUtil.sendRequest(context, adjustRequest);
    }

    @Override
    public void sendRetrievalRequest(Context context, RetrievalRequest request) {
        String retrievalRequest = GsonUtils.GsonString(request);
        CommandUtil.sendRequest(context, retrievalRequest);
    }

    @Override
    public void sendSettlementRequest(Context context, SettlementRequest request) {
        String settlementRequest = GsonUtils.GsonString(request);
        CommandUtil.sendRequest(context, settlementRequest);
    }

    private Handler mHander = new Handler() {

        @Override
        public void handleMessage(Message msg) {

            LoadingDialog.cancelDialogForLoading();

//            if (!TextUtils.isEmpty((String) msg.obj)) {
//                ArmsUtils.makeText(GSAApplication.getAppContext(), (String) msg.obj);
//            }
        }
    };

    /**
     * 设置N5请求超时处理
     */
    public void setRequestTimeout(Context context, String action, String txn_id, boolean showDialog) {

        LogUtil.d(TAG, "setRequestTimeout : " + action);

        if (action.equals(Constant.EVENT.NAME.SALE) || action.equals(Constant.EVENT.NAME.VOID)
                || action.equals(Constant.EVENT.NAME.REFUND) || action.equals(Constant.EVENT.NAME.ADJUST) || action.equals("RETRIEVAL")) {
            //回調記錄這裡(支付、退款、取消、调整、查詢交易)使用操作類型+交易ID作為key，防止回調記錄被重疊
            String callKey = action + "_" + txn_id;
            N5CallbackManage.getInstance().getCallbackRecordMap().put(callKey, false);
        } else {
            N5CallbackManage.getInstance().getCallbackRecordMap().put(action, false);
        }

        cancel = false;

        Timer time = new Timer();
        time.schedule(new TimerTask() {

            @Override
            public void run() {

                String callKey = action + "_" + txn_id;

                if (cancel) {
                    LogUtil.d(TAG, "setRequestTimeout cancel(): " + callKey + " - " + N5CallbackManage.getInstance().getCallbackRecordMap().get(callKey));
                    time.cancel();
                    return;
                }

                if (action.equals(Constant.EVENT.NAME.SALE)
                        || action.equals(Constant.EVENT.NAME.VOID)
                        || action.equals(Constant.EVENT.NAME.REFUND)
                        || action.equals(Constant.EVENT.NAME.ADJUST)
                        || action.equals("RETRIEVAL")) {
                    LogUtil.d(TAG, "setRequestTimeout run(): " + callKey + " - " + N5CallbackManage.getInstance().getCallbackRecordMap().get(callKey));
                } else {
                    LogUtil.d(TAG, "setRequestTimeout run(): " + action + " - " + N5CallbackManage.getInstance().getCallbackRecordMap().get(action));
                }

                //查詢訂單狀態參數
                RetrievalRequest retrievalRequest = new RetrievalRequest();
                retrievalRequest.setEVENT_NAME("RETRIEVAL");
                retrievalRequest.setTXN_ID(txn_id);

//                switch (action) {
//                    case Constant.EVENT.NAME.SALE:
//                        if (!N5CallbackManage.getInstance().getCallbackRecordMap().get(callKey)) {
//                            sendMarkToast(LanguageUtils.get_language_system(context,"prompt.payment request.timed.out","支付請求超時"));
//                            queryOrderStatus(context, retrievalRequest, showDialog);
//                        }
//                        break;
//                    case Constant.EVENT.NAME.VOID:
//                        if (!N5CallbackManage.getInstance().getCallbackRecordMap().get(callKey)) {
//                            sendMarkToast(LanguageUtils.get_language_system(context,"prompt.void request.timed.out","取消請求超時"));
//                            queryOrderStatus(context, retrievalRequest, showDialog);
//                        }
//                        break;
//                    case Constant.EVENT.NAME.REFUND:
//                        if (!N5CallbackManage.getInstance().getCallbackRecordMap().get(callKey)) {
//                            sendMarkToast(LanguageUtils.get_language_system(context,"prompt.refund request.timed.out","退款請求超時"));
//                            queryOrderStatus(context, retrievalRequest, showDialog);
//                        }
//                        break;
//                    case Constant.EVENT.NAME.ADJUST:
//                        if (!N5CallbackManage.getInstance().getCallbackRecordMap().get(callKey)) {
//                            sendMarkToast(LanguageUtils.get_language_system(context,"prompt.tip request.timed.out","貼士調整請求超時"));
//                            queryOrderStatus(context, retrievalRequest, showDialog);
//                        }
//                        break;
//                    case "RETRIEVAL":
//                        if (!N5CallbackManage.getInstance().getCallbackRecordMap().get(callKey)) {
//                            sendMarkToast(LanguageUtils.get_language_system(context,"prompt.transaction request.timed.out","交易查詢請求超時"));
//                        }
//                        break;
//                    case Constant.EVENT.NAME.PRINT_RESP:
//                        if (!N5CallbackManage.getInstance().getCallbackRecordMap().get(action)) {
//                            sendMarkToast(LanguageUtils.get_language_system(context,"prompt.printer request.timed.out","打印請求超時"));
//                        }
//                        break;
//                    case "SETTLEMENT":
//                        if (!N5CallbackManage.getInstance().getCallbackRecordMap().get(action)) {
//                            sendMarkToast(LanguageUtils.get_language_system(context,"prompt.settlement request.timed.out","清機請求超時"));
//                        }
//                        break;
//                }
                //重置为未响应
                N5CallbackManage.getInstance().getCallbackRecordMap().put(action, false);

            }
        }, actionTimeout);
    }

    private void sendMarkToast(String msg) {
        Message message = Message.obtain();
        message.arg1 = 2;
        message.obj = msg;
        mHander.sendMessage(message);
    }

    /**
     * （支付、退款、取消、调整）请求超时，执行查询接口
     *
     * @param context
     * @param request
     */
//    public void queryOrderStatus(Context context, RetrievalRequest request, boolean showDialog) {
////        if (showDialog) {
////            LoadingDialog.showDialogForLoading(context, LanguageUtils.get_language_system(context, "comm.getdata", " get data"), true);
////        }
//        RxTimer timer = new RxTimer();
//        timer.interval(queryInterval, new RxTimer.RxAction() {
//
//            @Override
//            public void action(long number) {
//
//                int count = (int) (number + 1);
//
//                String retrievalCallKey = "RETRIEVAL" + "_" + request.getTXN_ID();
//
//                if (N5CallbackManage.getInstance().getCallbackRecordMap().containsKey(retrievalCallKey)
//                        && N5CallbackManage.getInstance().getCallbackRecordMap().get(retrievalCallKey)) {
//                    //收到了查詢交易回調，斷掉查詢
////                    GSAApplication.getAppContext().getCrashHandler()
//                    LogUtil.d(TAG, "queryOrderStatus stop: " + count + " - " + request.getEVENT_NAME() + " - " + request.getTXN_ID());
//                    timer.cancel();
//                    cancel = true;
//                    return;
//                }
//
//                if (count == queryCount) {
//                    //已到查詢最大數，斷掉查詢
//                    LogUtil.d(TAG, "queryOrderStatus cancel: " + count + " - " + request.getEVENT_NAME() + " - " + request.getTXN_ID());
//                    timer.cancel();
//                    cancel = true;
//                    return;
//                }
//
//                LogUtil.d(TAG, "queryOrderStatus: " + count + " - " + request.getEVENT_NAME() + " - " + request.getTXN_ID());
//
//                sendRetrievalRequest(context, request);
//                mHander.sendEmptyMessage(1);
//            }
//        });
//    }

}
