package com.gingersoft.gsa.cloud.pay.mvp.ui.activity;

import android.app.Activity;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;

import com.billy.cc.core.component.CC;
import com.billy.cc.core.component.CCUtil;
import com.gingersoft.gsa.cloud.common.constans.AppConstans;
import com.gingersoft.gsa.cloud.common.constans.PrintConstans;
import com.gingersoft.gsa.cloud.common.core.table.TableBean;
import com.gingersoft.gsa.cloud.common.loadsir.pos.BasePosCallback;
import com.gingersoft.gsa.cloud.common.loadsir.pos.PosPayStatusExceptionCallback;
import com.gingersoft.gsa.cloud.common.utils.MoneyUtil;
import com.gingersoft.gsa.cloud.component.ComponentAction;
import com.gingersoft.gsa.cloud.component.ComponentName;
import com.gingersoft.gsa.cloud.order.bean.event.MealPayResultParam;
import com.gingersoft.gsa.cloud.order.order.DoshokuOrder;
import com.gingersoft.gsa.cloud.pay.R;
import com.gingersoft.gsa.cloud.pay.R2;
import com.gingersoft.gsa.cloud.pay.bean.PayMethod;
import com.gingersoft.gsa.cloud.pay.bean.PosActionStatusExceptionParam;
import com.gingersoft.gsa.cloud.pay.di.component.DaggerPayResultComponent;
import com.gingersoft.gsa.cloud.pay.mvp.contract.PayResultContract;
import com.gingersoft.gsa.cloud.pay.mvp.presenter.PayResultPresenter;
import com.gingersoft.gsa.cloud.pay.pos.OnPosActionListener;
import com.gingersoft.gsa.cloud.pay.pos.PosAction;
import com.gingersoft.gsa.cloud.pay.pos.PosPay;
import com.gingersoft.gsa.cloud.pay.pos.fragment.PosActionStatusExceptionFragment;
import com.gingersoft.gsa.cloud.pay.pos.hywebpos.bean.request.bg.GetTxnIdRequest;
import com.gingersoft.gsa.cloud.pay.pos.hywebpos.bean.request.pos.AdjustTipRequest;
import com.gingersoft.gsa.cloud.pay.pos.hywebpos.bean.request.pos.RetrievalRequest;
import com.gingersoft.gsa.cloud.pay.pos.hywebpos.bean.response.pos.AdjustTipRespose;
import com.gingersoft.gsa.cloud.pay.pos.hywebpos.bean.response.pos.HywebPosResponse;
import com.gingersoft.gsa.cloud.pay.pos.hywebpos.bean.response.pos.SaleRespose;
import com.gingersoft.gsa.cloud.pay.pos.hywebpos.constant.HywebActionStatusCode;
import com.gingersoft.gsa.cloud.pay.util.PayMethodUtils;
import com.gingersoft.gsa.cloud.print.bean.PrintContent;
import com.gingersoft.gsa.cloud.print.bean.adapter.PrintContentAdapter;
import com.gingersoft.gsa.cloud.ui.widget.dialog.KeyboardDialog;
import com.gingersoft.gsa.cloud.ui.widget.dialog.LoadingDialog;
import com.jess.arms.base.BaseFragmentActivity;
import com.jess.arms.di.component.AppComponent;
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.qmuiteam.qmui.alpha.QMUIAlphaButton;
import com.qmuiteam.qmui.widget.QMUITopBar;

import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

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


/**
 * ================================================
 * Description:
 * <p>
 * Created by MVPArmsTemplate on 12/28/2020 15:53
 * <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>
 * ================================================
 */
public class PayResultActivity extends BaseFragmentActivity<PayResultPresenter> implements PayResultContract.View {


    @BindView(R2.id.topbar)
    QMUITopBar topbar;
    @BindView(R2.id.tv_table_name)
    TextView tvTableName;
    @BindView(R2.id.tv_order_num)
    TextView tvOrderNum;
    @BindView(R2.id.tv_pay_status)
    TextView tvPayStatus;
    @BindView(R2.id.tv_amount)
    TextView tvAmount;
    @BindView(R2.id.tv_paymethod)
    TextView tvPaymethod;
    @BindView(R2.id.ll_content)
    LinearLayout llContent;
    @BindView(R2.id.tv_tips)
    TextView tvTips;
    @BindView(R2.id.tv_printer)
    TextView tvPrinter;
    //    @BindView(R2.id.tv_complate)
//    TextView tvComplate;
    @BindView(R2.id.ll_bottom)
    LinearLayout llBottom;
    @BindView(R2.id.rl_container)
    RelativeLayout rlContainer;
//    @BindView(R2.id.pro_pay_status)
//    ProgressBar proPayStatus;
//    @BindView(R2.id.tv_loading_text)
//    TextView tvLoadingText;

    @BindView(R2.id.btn_refresh_status)
    QMUIAlphaButton btnRefreshStatus;
    @BindView(R2.id.btn_complate)
    QMUIAlphaButton btnComplate;

    private LoadService loadService;
    private MealPayResultParam mMealPayResultParam;
    private SaleRespose mSaleRespose;

    private String mPayMehodNames;

    /**
     * 異常情況下 嘗試查詢多少次 顯示提示
     */
    private int retryCount = 3;

    @Override
    public void setupActivityComponent(@NonNull AppComponent appComponent) {
        DaggerPayResultComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .view(this)
                .build()
                .inject(this);
    }

    @Override
    public int initView(@Nullable Bundle savedInstanceState) {
        return R.layout.activity_pay_result; //如果你不需要框架帮你设置 setContentView(id) 需要自行设置,请返回 0
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {

        loadService = LoadSir.getDefault().register(llContent, new Callback.OnReloadListener() {
            @Override
            public void onReload(View v) {
                if (retryCount == 0) {
                    Class<BasePosCallback> callback = loadService.getCurrentCallback();
                    BasePosCallback callback1 = callback.cast(BasePosCallback.class);
                    callback1.showFinalStrategy(true);
                }
                //支付状态异常 重试查询
                retrievalStatus(PosAction.SALE);
                retryCount--;
            }
        });
        showPaymentStatus();
    }

    @Override
    public void initIntent() {
        MealPayResultParam payResultParam = CCUtil.getNavigateParam(this, "payResultParam", null);
        if (payResultParam != null) {
            mMealPayResultParam = payResultParam;
            mSaleRespose = mMealPayResultParam.getSaleRespose();
            initMealPayResultParam();
            printPaymentStub(payResultParam.getTxnId());
        }
    }

    private void initMealPayResultParam() {
        mPayMehodNames = getPayMehodStr(mMealPayResultParam.getPayMethodList());
        tvAmount.setText(getPayAmount());
        tvPaymethod.setText(mPayMehodNames);
        tvTableName.setText("檯號: " + mMealPayResultParam.getTableBean().getTableName());
        tvOrderNum.setText("單號: " + mMealPayResultParam.getMealOrderPayRequest().getOrderId());

        PayMethod payMethod = PayMethodUtils.filterPaymentMethodById(mMealPayResultParam.getPayMethodList(), PayMethod.HYWEB_POS_TYPE_CC);
        if (payMethod != null) {
            //只有卡片支付才支持補小費
            tvTips.setVisibility(View.VISIBLE);
        } else {
            tvTips.setVisibility(View.GONE);
        }
    }

    private void showPaymentStatus() {
        if (HywebActionStatusCode.withSuccess(mSaleRespose.getSTATUS())) {
            loadService.showSuccess();
            llBottom.setVisibility(View.VISIBLE);
            btnComplate.setVisibility(View.VISIBLE);
        } else if (HywebActionStatusCode.withException(mSaleRespose.getSTATUS())) {
            loadService.showCallback(PosPayStatusExceptionCallback.class);
            llBottom.setVisibility(View.INVISIBLE);
            btnComplate.setVisibility(View.INVISIBLE);
        }
        tvPayStatus.setCompoundDrawables(null, getPaymentDrawableByStatus(mSaleRespose.getSTATUS()), null, null);
        tvPayStatus.setText(HywebActionStatusCode.getHywebRequestTextByCode(mSaleRespose.getSTATUS()));
    }

    private Drawable getPaymentDrawableByStatus(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());
        }
        return drawable;
    }

    private void retrievalStatus(PosAction posAction) {
        RetrievalRequest retrievalRequest = new RetrievalRequest();
        retrievalRequest.setTXN_ID(mMealPayResultParam.getTxnId());
        PosPay.retrieval(mContext, this, mMealPayResultParam.getMealOrderPayRequest().getOrderId(), posAction, retrievalRequest, new OnPosActionListener() {

            @Override
            public void onPosSuccess(HywebPosResponse response) {
                mSaleRespose = mMealPayResultParam.getSaleRespose();
                showPaymentStatus();
                printPaymentStub(response.getTXN_ID());
            }

            @Override
            public void onPosException(Exception e) {
                loadService.showCallback(PosPayStatusExceptionCallback.class);
            }

            @Override
            public void onPosInvalid(String e) {

            }

            @Override
            public void onUpdateStatusSuccess(HywebPosResponse response) {

            }

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

    private String getPayAmount() {
        if (mSaleRespose.getTIPS() != 0) {
            return AppConstans.CARSH_STR + MoneyUtil.sum(mSaleRespose.getTXN_AMT(), mSaleRespose.getTIPS()) + "(含小費" + mSaleRespose.getTIPS() + ")";
        } else {
            return AppConstans.CARSH_STR + mSaleRespose.getTXN_AMT();
        }
    }

    private String getPayMehodStr(List<PayMethod> payMethodList) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < payMethodList.size(); i++) {
            PayMethod payMethod = payMethodList.get(i);
            if (i < (payMethodList.size() - 1)) {
                sb.append(payMethod.getPayName() + ",");
            } else {
                sb.append(payMethod.getPayName());
            }
        }
        return sb.toString();
    }

    /**
     * 打印存根单
     * @param txnId
     */
    private void printPaymentStub(String txnId){
        PosPay.printStub(mContext, this,txnId, new OnPosActionListener() {
            @Override
            public void onPosSuccess(HywebPosResponse response) {
                printBill();
            }

            @Override
            public void onPosException(Exception e) {
                printBill();
            }

            @Override
            public void onPosInvalid(String e) {
                printBill();
            }

            @Override
            public void onUpdateStatusSuccess(HywebPosResponse response) {
            }

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

    @Override
    public void initTopBar() {
        topbar.setTitle("支付結果");
        topbar.setBackgroundColor(ContextCompat.getColor(this, R.color.theme_color));
    }

    @Override
    public void initLanguage() {

    }

    @Override
    public void initLayoutParams() {

    }

    @Override
    public void initLayoutVisible() {

    }

    @Override
    public void showLoading(String message) {
        if (message != null)
            LoadingDialog.showDialogForLoading(this, message, true);
        else
            LoadingDialog.showDialogForLoading(this);
    }

    @Override
    public void hideLoading() {
        LoadingDialog.cancelDialogForLoading();
    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        ArmsUtils.makeText(this, message);
    }

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

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

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

    @OnClick({R2.id.tv_tips, R2.id.tv_printer, R2.id.btn_complate})
    public void onViewClicked(View view) {
        if (view.getId() == R.id.tv_tips) {
            showKeyboardDialog();
        } else if (view.getId() == R.id.tv_printer) {
            printPaymentStub(mMealPayResultParam.getTxnId());
        } else if (view.getId() == R.id.btn_complate) {
            //返回餐檯頁面
            CC.obtainBuilder(ComponentName.COMPONENT_TABLE)
                    .setActionName(ComponentAction.Table.KILL_MEAL_ORDER_PAY)
                    .build()
                    .call();
            killMyself();
        }
    }

    private void printBill() {
        PrintContent printContent = new PrintContentAdapter().adaptationBillContent(DoshokuOrder.getInstance(),mMealPayResultParam.getTableBean());
        CC.obtainBuilder(ComponentName.COMPONENT_PRINT)
                .setActionName("printActivity")
                .addParam(PrintConstans.PRINT_TYPE, PrintConstans.PRINT_BILL)
                .addParam(PrintConstans.PRINT_CONTENT, printContent)
                .build()
                .callAsyncCallbackOnMainThread((cc, result) -> {
                    Log.e("error", "是否成功打印：" + result.isSuccess());
                    //清空開檯數據
                    DoshokuOrder.getInstance().initialization();
                    setResult(Activity.RESULT_OK, null);
                    killMyself();
                });
    }

    private void showKeyboardDialog() {
        new KeyboardDialog(this)
                .build()
                .setOnCallBackListener(new KeyboardDialog.OnCallBackListener() {
                    @Override
                    public void onSure(String number) {
                        if (!TextUtils.isEmpty(number)) {
                            GetTxnIdRequest txnIdRequest = new GetTxnIdRequest();
                            TableBean.DataBean tableBean = mMealPayResultParam.getTableBean();
                            txnIdRequest.setOrderId(mMealPayResultParam.getMealOrderPayRequest().getOrderId());
                            if (!TextUtils.isEmpty(tableBean.getTableNumber())) {
                                txnIdRequest.setTableExtId(tableBean.getId());
                            } else {
                                txnIdRequest.setTableId(tableBean.getId());
                            }
                            txnIdRequest.setAmount(mSaleRespose.getTXN_AMT());

                            PosPay.tip(mContext, PayResultActivity.this, txnIdRequest, getTipsRequest(mMealPayResultParam.getSaleRespose(), Double.parseDouble(number)), new OnPosActionListener<AdjustTipRespose>() {

                                @Override
                                public void onPosSuccess(AdjustTipRespose response) {
                                    mSaleRespose.setTIPS(mSaleRespose.getTIPS() + response.getTIPS());
                                    initMealPayResultParam();
                                }

                                @Override
                                public void onPosException(Exception e) {
                                    //POS回调异常，去重试查询
//                                    if (findFragment(PosActionStatusExceptionFragment.class) == null) {
//                                        PosActionStatusExceptionParam statusExceptionParam = new PosActionStatusExceptionParam();
//                                        statusExceptionParam.setTxnId(mMealPayResultParam.getTxnId());
//                                        statusExceptionParam.setAmount(mSaleRespose.getTXN_AMT());
//                                        statusExceptionParam.setOrderId(mMealPayResultParam.getMealOrderPayRequest().getOrderId());
//                                        statusExceptionParam.setPayMethodName(mPayMehodNames);
//                                        statusExceptionParam.setPosAction(PosAction.TIP);
//                                        loadRootFragment(R.id.rl_container, PosActionStatusExceptionFragment.newInstance(statusExceptionParam));
//                                    }
                                }

                                @Override
                                public void onPosInvalid(String e) {

                                }

                                @Override
                                public void onUpdateStatusSuccess(AdjustTipRespose response) {

                                }

                                @Override
                                public void onUpdateStatusError(Throwable e) {
//                                    if (findFragment(PosActionStatusExceptionFragment.class) == null) {
//                                        PosActionStatusExceptionParam statusExceptionParam = new PosActionStatusExceptionParam();
//                                        statusExceptionParam.setTxnId(mMealPayResultParam.getTxnId());
//                                        statusExceptionParam.setAmount(mSaleRespose.getTXN_AMT());
//                                        statusExceptionParam.setOrderId(mMealPayResultParam.getMealOrderPayRequest().getOrderId());
//                                        statusExceptionParam.setPayMethodName(mPayMehodNames);
//                                        statusExceptionParam.setPosAction(PosAction.TIP);
//                                        loadRootFragment(R.id.rl_container, PosActionStatusExceptionFragment.newInstance(statusExceptionParam));
//                                    }
                                }
                            });
                        }
                    }
                })
                .show();
    }

    private AdjustTipRequest getTipsRequest(SaleRespose saleRespose, double tips) {
        AdjustTipRequest tipRequest = new AdjustTipRequest();
        tipRequest.setTXN_ID(saleRespose.getTXN_ID());
        tipRequest.setTOTAL_TXN_AMT(MoneyUtil.sum(saleRespose.getTXN_AMT(), tips));
        return tipRequest;
    }

}
