package com.gingersoft.gsa.cloud.pay.pos.fragment;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.gingersoft.gsa.cloud.common.constans.AppConstans;
import com.gingersoft.gsa.cloud.common.loadsir.pos.BasePosCallback;
import com.gingersoft.gsa.cloud.common.loadsir.pos.PosPayStatusExceptionCallback;
import com.gingersoft.gsa.cloud.common.loadsir.pos.PosRefundStatusExceptionCallback;
import com.gingersoft.gsa.cloud.common.loadsir.pos.PosSettlementStatusExceptionCallback;
import com.gingersoft.gsa.cloud.common.loadsir.pos.PosTipsStatusExceptionCallback;
import com.gingersoft.gsa.cloud.common.loadsir.pos.PosVoidStatusExceptionCallback;
import com.gingersoft.gsa.cloud.order.R;
import com.gingersoft.gsa.cloud.order.R2;
import com.gingersoft.gsa.cloud.pay.bean.PosActionStatusExceptionParam;
import com.gingersoft.gsa.cloud.pay.pos.OnPosActionListener;
import com.gingersoft.gsa.cloud.pay.pos.PosPay;
import com.gingersoft.gsa.cloud.pay.pos.hywebpos.bean.request.pos.RetrievalRequest;
import com.gingersoft.gsa.cloud.pay.pos.hywebpos.bean.response.pos.HywebPosResponse;
import com.gingersoft.gsa.cloud.pay.pos.hywebpos.constant.HywebActionStatusCode;
import com.jess.arms.base.BaseFragment;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.mvp.IView;
import com.kingja.loadsir.callback.Callback;
import com.kingja.loadsir.core.LoadService;
import com.kingja.loadsir.core.LoadSir;
import com.kingja.loadsir.core.Transport;
import com.qmuiteam.qmui.alpha.QMUIAlphaButton;

import org.simple.eventbus.EventBus;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * @作者: bin
 * @創建時間: 2020-12-30 10:37
 * @更新時間: 2020-12-30 10:37
 * @描述:支付狀態異常頁面，POS未回調成功的情況下顯示此頁面，重試POS查詢狀態
 */
public class PosActionStatusExceptionFragment extends BaseFragment implements IView {

    @BindView(R2.id.tv_order_num)
    TextView tvOrderNum;
    @BindView(R2.id.tv_pos_status)
    TextView tvPosStatus;
    @BindView(R2.id.tv_amount)
    TextView tvAmount;
    @BindView(R2.id.tv_pay_method)
    TextView tvPaymethod;
    @BindView(R2.id.btn_back)
    QMUIAlphaButton btnBack;
    @BindView(R2.id.ll_content)
    LinearLayout llContent;
    @BindView(R2.id.rl_container)
    RelativeLayout rlContainer;

    private LoadService loadService;
    private PosActionStatusExceptionParam mPosStatusExceptionParam;

    private TextView tv_order_num, tv_final_prompt, tv_exception, tv_amount, tv_pay_method;

    /**
     * 最多重试三次,显示联系开发人员提示
     */
    private int retryCount = 3;

    public static final String REFREAFSH_ORDER_EVENT = "refreafsh_order";

    public static PosActionStatusExceptionFragment newInstance(PosActionStatusExceptionParam posStatusExceptionParam) {
        Bundle args = new Bundle();
        PosActionStatusExceptionFragment fragment = new PosActionStatusExceptionFragment();
        args.putParcelable("posStatusExceptionParam", posStatusExceptionParam);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void setupFragmentComponent(@NonNull AppComponent appComponent) {
    }

    @Override
    public View initView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.pay_fragment_pos_status_exception, container, false);
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        Bundle bundle = getArguments();
        mPosStatusExceptionParam = bundle.getParcelable("posStatusExceptionParam");

        initPage();
        initLoadService();
        retrievalStatus();
    }

    private void initLoadService() {
        BasePosCallback posCallback = null;
        loadService = LoadSir.getDefault().register(rlContainer, new Callback.OnReloadListener() {
            @Override
            public void onReload(View v) {
                if (retryCount == 0) {
                    tv_final_prompt.setVisibility(View.VISIBLE);
                }
                //支付状态异常 重试查询
                retrievalStatus();
                retryCount--;
            }
        });
        switch (mPosStatusExceptionParam.getPosAction()) {
            case SALE:
                posCallback = new PosPayStatusExceptionCallback();
                break;
            case REFUND:
                posCallback = new PosRefundStatusExceptionCallback();
                break;
            case VOID:
                posCallback = new PosVoidStatusExceptionCallback();
                break;
            case TIP:
                posCallback = new PosTipsStatusExceptionCallback();
                break;
            case SETTLEMENT:
                posCallback = new PosSettlementStatusExceptionCallback();
                break;
            default:
                break;
        }
        if (posCallback != null) {
            loadService.setCallBack(posCallback.getClass(), new OnTransport());
            loadService.showCallback(posCallback.getClass());
        }
    }

    private final class OnTransport implements Transport {
        @Override
        public void order(Context context, View rootView) {
            tv_order_num = rootView.findViewById(com.gingersoft.gsa.cloud.common.R.id.tv_order_num);
            tv_final_prompt = rootView.findViewById(com.gingersoft.gsa.cloud.common.R.id.tv_final_prompt);
            tv_exception = rootView.findViewById(com.gingersoft.gsa.cloud.common.R.id.tv_exception);
            tv_amount = rootView.findViewById(com.gingersoft.gsa.cloud.common.R.id.tv_amount);
            tv_pay_method = rootView.findViewById(com.gingersoft.gsa.cloud.common.R.id.tv_pay_method);

            tv_order_num.setText("單號：" + mPosStatusExceptionParam.getOrderId());
            tv_amount.setText(AppConstans.CARSH_STR + mPosStatusExceptionParam.getAmount());
            tv_pay_method.setText(mPosStatusExceptionParam.getPayMethodName());
        }
    }

    private void initPage() {
        tvOrderNum.setText("單號：" + mPosStatusExceptionParam.getOrderId());
        tvAmount.setText(AppConstans.CARSH_STR + mPosStatusExceptionParam.getAmount());
        tvPaymethod.setText(mPosStatusExceptionParam.getPayMethodName());
    }

    private void setPosActionStatus(String status) {
        Drawable drawable;
        if (HywebActionStatusCode.withSuccess(status)) {
            drawable = getResources().getDrawable(R.mipmap.pay_status_success);
            drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
        } else {
            drawable = getResources().getDrawable(R.mipmap.pay_status_exception);
            drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
        }
        tvPosStatus.setCompoundDrawables(null, drawable, null, null);
        tvPosStatus.setText(HywebActionStatusCode.getHywebRequestTextByCode(status));
    }

    private void retrievalStatus() {
        RetrievalRequest retrievalRequest = new RetrievalRequest();
        retrievalRequest.setTXN_ID(mPosStatusExceptionParam.getTxnId());
        PosPay.retrieval(mContext, this, mPosStatusExceptionParam.getOrderId(), mPosStatusExceptionParam.getPosAction(),retrievalRequest, new OnPosActionListener() {

            @Override
            public void onPosSuccess(HywebPosResponse response) {

            }

            @Override
            public void onPosException(Exception e) {
            }

            @Override
            public void onPosInvalid(String e) {

            }

            @Override
            public void onUpdateStatusSuccess(HywebPosResponse response) {
                EventBus.getDefault().post(true,REFREAFSH_ORDER_EVENT);
                tvPosStatus.setText(mPosStatusExceptionParam.getPosAction().getActionName() + "成功");
                loadService.showSuccess();
                setPosActionStatus(response.getSTATUS());
            }

            @Override
            public void onUpdateStatusError(Throwable e) {
            }
        });
    }

    @OnClick({R2.id.btn_back})
    public void onViewClicked(View view) {
        int id = view.getId();
        if (id == R.id.btn_back) {
            killMyself();
        }
    }

    @Override
    public void setData(@Nullable Object data) {

    }


    @Override
    public void showLoading(String message) {

    }

    @Override
    public void hideLoading() {

    }

    @Override
    public void showMessage(@NonNull String message) {

    }

    @Override
    public void launchActivity(@NonNull Intent intent) {

    }

    @Override
    public void killMyself() {
        onBackPressedSupport();
    }

    @Override
    public boolean onBackPressedSupport() {
        return super.onBackPressedSupport();
    }
}
