package com.gingersoft.gsa.cloud.pay.device.pos.base.lifecycle.fragment;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
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.PosPayMatterCallback;
import com.gingersoft.gsa.cloud.common.loadsir.pos.PosRefundMatterCallback;
import com.gingersoft.gsa.cloud.common.loadsir.pos.PosSettlementMatterCallback;
import com.gingersoft.gsa.cloud.common.loadsir.pos.PosTipsMatterCallback;
import com.gingersoft.gsa.cloud.common.loadsir.pos.PosVoidMatterCallback;
import com.gingersoft.gsa.cloud.order.R;
import com.gingersoft.gsa.cloud.order.R2;
import com.gingersoft.gsa.cloud.pay.PayStep;
import com.gingersoft.gsa.cloud.pay.RequestParms;
import com.gingersoft.gsa.cloud.pay.device.pos.hyweb.constant.HywebActionStatusCode;
import com.jess.arms.base.BaseDialogFragment;
import com.jess.arms.mvp.BasePresenter;
import com.jess.arms.mvp.IView;
import com.jess.arms.utils.ArmsUtils;
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 butterknife.BindView;
import butterknife.OnClick;

import static com.jess.arms.utils.Preconditions.checkNotNull;

/**
 * @作者: bin
 * @創建時間: 2020-12-30 10:37
 * @更新時間: 2020-12-30 10:37
 * @描述:POS事项異常查询頁面
 */
public abstract class PosMatterFragment<P extends BasePresenter> extends BaseDialogFragment<P> 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;
    protected RequestParms requestParms;

    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";

    protected abstract void retrievalStatus();

    @Override
    public View initView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        getDialog().requestWindowFeature(Window.FEATURE_NO_TITLE);
        getDialog().setCancelable(false);
        return inflater.inflate(R.layout.fragment_pos_matter, container, false);
    }

    @Override
    public void onStart() {
        super.onStart();
        mWindow.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        WindowManager.LayoutParams lp = mWindow.getAttributes();
        lp.width = WindowManager.LayoutParams.MATCH_PARENT;
        lp.height = WindowManager.LayoutParams.MATCH_PARENT;
        lp.gravity = Gravity.BOTTOM;
        lp.windowAnimations = android.R.style.Animation_InputMethod;
        mWindow.setAttributes(lp);
    }

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

        initOrderDetail();
        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 (requestParms.getAction()) {
            case SALE:
                posCallback = new PosPayMatterCallback();
                break;
            case REFUND:
                posCallback = new PosRefundMatterCallback();
                break;
            case VOID:
                posCallback = new PosVoidMatterCallback();
                break;
            case TIP:
                posCallback = new PosTipsMatterCallback();
                break;
            case SETTLEMENT:
                posCallback = new PosSettlementMatterCallback();
                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("單號：" + requestParms.getOrderId());
            tv_amount.setText(AppConstans.CARSH_STR + requestParms.getPayMoney());
            tv_pay_method.setText(requestParms.getPayMethodName());
        }
    }

    private void initOrderDetail() {
        tvOrderNum.setText("單號：" + requestParms.getOrderId());
        tvAmount.setText(AppConstans.CARSH_STR + requestParms.getPayMoney());
        tvPaymethod.setText(requestParms.getPayMethodName());
    }

    protected void setMatterStatus(boolean success, String name) {
        Drawable drawable = null;
        if (success) {
            drawable = getResources().getDrawable(R.mipmap.pay_status_success);
        } 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(name);
    }

//    {
//        PaymentCommand.newInstance().retrieval(requestParms);
//        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(HywebPosResponse response,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) {
        checkNotNull(message);
        ArmsUtils.makeText(mContext, message);
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

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

}
