package com.gingersoft.gsa.cloud.pay.pos.hyweb.command;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;

import com.billy.cc.core.component.CC;
import com.etps.aca.lib.action.ICommand;
import com.etps.aca.lib.activity.CommandActivity;
import com.etps.aca.lib.constant.Constant;
import com.gingersoft.gsa.cloud.common.logan.LoganManager;
import com.gingersoft.gsa.cloud.common.utils.gson.GsonUtils;
import com.gingersoft.gsa.cloud.common.utils.log.LogUtil;
import com.gingersoft.gsa.cloud.component.ComponentAction;
import com.gingersoft.gsa.cloud.component.ComponentName;
import com.gingersoft.gsa.cloud.pay.contract.PayExceptionCode;
import com.gingersoft.gsa.cloud.pay.pos.hyweb.imp.IHywebAction;
import com.gingersoft.gsa.cloud.pay.pos.PosAction;
import com.gingersoft.gsa.cloud.pay.pos.hyweb.bean.response.pos.AdjustTipRespose;
import com.gingersoft.gsa.cloud.pay.pos.hyweb.bean.response.pos.HywebPosResponse;
import com.gingersoft.gsa.cloud.pay.pos.hyweb.bean.response.pos.PrintPaymentStubResponse;
import com.gingersoft.gsa.cloud.pay.pos.hyweb.bean.response.pos.RefundRespose;
import com.gingersoft.gsa.cloud.pay.pos.hyweb.bean.response.pos.RetrievalRespose;
import com.gingersoft.gsa.cloud.pay.pos.hyweb.bean.response.pos.SaleRespose;
import com.gingersoft.gsa.cloud.pay.pos.hyweb.bean.response.pos.SettlementRespose;
import com.gingersoft.gsa.cloud.pay.pos.hyweb.bean.response.pos.VoidRespose;
import com.gingersoft.gsa.cloud.pay.pos.hyweb.constant.HywebActionStatusCode;
import com.jess.arms.integration.AppManager;
import com.jess.arms.utils.ArmsUtils;

import org.json.JSONException;
import org.json.JSONObject;

public class CommandImpl implements ICommand {

    private static final String TAG = CommandImpl.class.getSimpleName();

    private IHywebAction mPosAction;

    public CommandImpl() {
    }

    public CommandImpl(IHywebAction posAction) {
        this.mPosAction = posAction;
    }

    @Override
    public void onRequest(Context context, String request) {

        LoganManager.w_pay(TAG, "onRequest : " + request);

        try {
            JSONObject msgObj = new JSONObject(request);
            String eventName = msgObj.getString(Constant.EVENT.ATTR.EVENT_NAME);
            if (Constant.EVENT.NAME.SALE.equals(eventName)) {
                startInitHywebActivity(context);
            } else if (Constant.EVENT.NAME.REFUND.equals(eventName)) {
                startInitHywebActivity(context);
            } else if (Constant.EVENT.NAME.VOID.equals(eventName)) {
                startInitHywebActivity(context);
            } else if (Constant.EVENT.NAME.GOTO.equals(eventName)) {
                startInitHywebActivity(context);
            }
        } catch (JSONException e) {
            startInitHywebActivity(context);
        }
    }

    private void startInitHywebActivity(Context context) {
        CC.obtainBuilder(ComponentName.COMPONENT_LOGIN)
                .setActionName(ComponentAction.Login.OPEN_WELCOME)
                .build()
                .call();
    }


    /**
     * 支付失败 {"EVENT_NAME":"SALE_RESP","STATUS":"09","TXN_ID":"20171205153245643043436585106024","TXN_AMT":1,"TIPS":0.00}
     * 支付成功 {"EVENT_NAME":"SALE_RESP","MID":"181500000260","PAYMENT_TYPE":"WCP","TRACE_NO":"20171205153245643043436585122154","RESP_CODE":"F0000","TIPS":0,"HOST_REF":"4200000136201805303582803320","TXN_TIME":"162530","TXN_DATE":"20181116","TXN_ID":"20171205153245643043436585122154","STATUS":"00","TID":"12189001","TXN_AMT":0.10}
     * 取消成功 {"EVENT_NAME":"VOID_RESP","STATUS":"00","PAYMENT_TYPE":"UP","RESP_CODE":"C1000","HOST_REF":"729706000007","TXN_TIME":"175305","TXN_ID":"PAY201911011747001513","TXN_DATE":"20191101"}
     */
    @Override
    public void onResponse(Context context, String response) {

        LoganManager.w_pay(TAG, "onResponse : " + response);

        AppManager appManager = ArmsUtils.obtainAppComponentFromContext(context).appManager();
        //kill掉hyweb支付頁
        appManager.killActivity(CommandActivity.class);

        Activity currentActivity = appManager.getTopActivity();

        if (TextUtils.isEmpty(response)) {
            onPosException(context, currentActivity,returnErrorPosActionResponse(mPosAction.getPosAction(),PayExceptionCode.pos_response_null));
            return;
        }

        try {
            JSONObject msgObj = new JSONObject(response);
            String eventName = msgObj.getString(Constant.EVENT.ATTR.EVENT_NAME);
            HywebPosResponse posResponse = parsePosResponse(response, eventName);
            if (posResponse != null) {
                if (HywebActionStatusCode.withInvalid(posResponse.getSTATUS())) {
                    //調起POS失敗
                    onPosInvalid(context, currentActivity,posResponse);
                } else {
                    //回調成功
                    onPosSuccess(context, currentActivity,posResponse);
                }
            } else {
                //回調異常
                onPosException(context, currentActivity,returnErrorPosActionResponse(mPosAction.getPosAction(),PayExceptionCode.pos_response_101));
            }
        } catch (JSONException e) {
            e.printStackTrace();
            try {
                JSONObject msgObj = new JSONObject(response);
                String status = msgObj.getString("STATUS");
                if (HywebActionStatusCode.withInvalid(status)) {
                    //調起POS失敗
                    onPosInvalid(context, currentActivity,returnErrorPosActionResponse(mPosAction.getPosAction(),status));
                } else {
                    //回調異常
                    onPosException(context, currentActivity,returnErrorPosActionResponse(mPosAction.getPosAction(),status));
                }
            } catch (JSONException ex) {
                ex.printStackTrace();
                //回調異常
                onPosException(context, currentActivity,returnErrorPosActionResponse(mPosAction.getPosAction(),PayExceptionCode.pos_response_102));
            }
        } finally {
            returnLastActivity(context, currentActivity);
        }
    }

    /**
     * 返回操作頁
     *
     * @param context
     * @param currentActivity
     */
    private void returnLastActivity(Context context, Activity currentActivity) {
        if (currentActivity != null) {
            LoganManager.w_pay(TAG, "currentActivity : " + currentActivity.getClass().getName());
            //返回上次操作的頁面
            Intent intent = new Intent();
            intent.setComponent(currentActivity.getComponentName());
            context.startActivity(intent);
        }
    }

    private HywebPosResponse parsePosResponse(String response, String eventName) {
        switch (eventName) {
            case com.etps.aca.lib.constant.Constant.EVENT.NAME.SALE_RESP:
                return GsonUtils.GsonToBean(response, SaleRespose.class);
            case com.etps.aca.lib.constant.Constant.EVENT.NAME.VOID_RESP:
                return GsonUtils.GsonToBean(response, VoidRespose.class);
            case com.etps.aca.lib.constant.Constant.EVENT.NAME.REFUND_RESP:
                return GsonUtils.GsonToBean(response, RefundRespose.class);
            case com.etps.aca.lib.constant.Constant.EVENT.NAME.PRINT_RESP:
                return GsonUtils.GsonToBean(response, PrintPaymentStubResponse.class);
            case com.etps.aca.lib.constant.Constant.EVENT.NAME.ADJUST_RESP:
                return GsonUtils.GsonToBean(response, AdjustTipRespose.class);
            case "RETRIEVAL_RESP":
                return GsonUtils.GsonToBean(response, RetrievalRespose.class);
            case "SETTLE_RESP":
                return GsonUtils.GsonToBean(response, SettlementRespose.class);
        }
        return null;
    }

    private HywebPosResponse returnErrorPosActionResponse(PosAction posAction,String errorStatus){
        HywebPosResponse posResponse;
        if(posAction == PosAction.SALE){
            posResponse = new SaleRespose();
        }else if(posAction == PosAction.VOID){
            posResponse = new VoidRespose();
        }else if(posAction == PosAction.REFUND){
            posResponse = new RefundRespose();
        }else if(posAction == PosAction.PRINT){
            posResponse = new PrintPaymentStubResponse();
        }else if(posAction == PosAction.TIP){
            posResponse = new AdjustTipRespose();
        }else if(posAction == PosAction.RETRIEVAL){
            posResponse = new RetrievalRespose();
        }else if(posAction == PosAction.SETTLEMENT){
            posResponse = new SettlementRespose();
        }else{
            posResponse = new HywebPosResponse();
        }
        if(posResponse != null) {
            posResponse.setSTATUS(errorStatus);
        }
        return posResponse;
    }


    @Override
    public void onGoto(Context context) {
        LogUtil.d(TAG, "onGoto");
    }

    /**
     * 回調成功轉發到具體的實現類
     * @param context
     * @param actionActivity
     * @param posResponse
     */
    private void onPosSuccess(Context context, Activity actionActivity, HywebPosResponse posResponse) {
        if (mPosAction != null) {
            mPosAction.onPosSuccess(context, actionActivity,posResponse);
        }
    }

    /**
     * 回調失敗轉發到具體的實現類
     * @param context
     * @param actionActivity
     * @param posResponse
     */
    public void onPosException(Context context, Activity actionActivity, HywebPosResponse posResponse) {
        if (mPosAction != null) {
            mPosAction.onPosException(context, actionActivity,posResponse);
        }
    }

    /**
     * 調起失敗轉發到具體的實現類
     * @param context
     * @param actionActivity
     * @param posResponse
     */
    public void onPosInvalid(Context context, Activity actionActivity, HywebPosResponse posResponse) {
        if (mPosAction != null) {
            mPosAction.onPosInvalid(context, actionActivity,posResponse);
        }
    }


}
