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

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
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.CCUtil;
import com.gingersoft.gsa.cloud.common.constans.AppConstans;
import com.gingersoft.gsa.cloud.common.utils.MoneyUtil;
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.response.pos.HywebPosResponse;
import com.gingersoft.gsa.cloud.pay.pos.hywebpos.bean.response.pos.SaleRespose;
import com.gingersoft.gsa.cloud.pay.pos.hywebpos.constant.PayStatusCode;
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.core.LoadService;
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;

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

    private String mPayMehodNames;

    @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(rlContainer, new Callback.OnReloadListener() {
//            @Override
//            public void onReload(View v) {
////                onRetrievalRequest(mPayResultEvent.getTxnId());
//            }
//        });
//        loadService.showSuccess();
    }

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

    private void initMealPayResultParam() {
        mSaleRespose = mMealPayResultParam.getSaleRespose();
        if (PayStatusCode.withSuccess(mSaleRespose.getSTATUS())) {

            mPayMehodNames = getPayMehodStr(mMealPayResultParam.getPayMethodList());

            tvAmount.setText(getPayAmount(mSaleRespose.getTXN_AMT()));
            tvPaymethod.setText(mPayMehodNames);
            tvTableName.setText("檯號: " + mMealPayResultParam.getTableBean().getTableName());
            tvOrderNum.setText("單號: " + mMealPayResultParam.getMealOrderPayRequest().getOrderId());
//            loadService.showSuccess();
        } else {
//            loadService.showCallback(ErrorCallback.class);
        }
    }

    private String getPayAmount(double payAmount) {
        return AppConstans.CARSH_STR + payAmount;
    }

    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() && payMethodList.size() != 0) {
                sb.append(payMethod.getPayName() + ",");
            } else {
                sb.append(payMethod.getPayName());
            }
        }
        return sb.toString();
    }

    @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.tv_complate})
    public void onViewClicked(View view) {
        if (view.getId() == R.id.tv_tips) {
            showKeyboardDialog();
        } else if (view.getId() == R.id.tv_printer) {

        } else if (view.getId() == R.id.tv_complate) {
            //返回餐檯頁面
//            CC.obtainBuilder(ComponentName.COMPONENT_TABLE)
//                    .setActionName(ComponentAction.Table.KILL_MEAL_ORDER_PAY)
//                    .build()
//                    .call();
            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();
//                            txnIdRequest.setOrderId(DoshokuOrder.getInstance().getOrderId());
//                            txnIdRequest.setOrderId(DoshokuOrder.getInstance().getOrderId());
//                            txnIdRequest.setOrderId(DoshokuOrder.getInstance().getOrderId());
//                            txnIdRequest.setOrderId(DoshokuOrder.getInstance().getOrderId());
                            GetTxnIdRequest txnIdRequest = new GetTxnIdRequest();
                            txnIdRequest.setOrderId(DoshokuOrder.getInstance().getOrderId());
                            if (!TextUtils.isEmpty(DoshokuOrder.getInstance().getOpenTableInfo().getTableNumber())) {
                                txnIdRequest.setTableExtId(DoshokuOrder.getInstance().getOpenTableInfo().getId());
                            } else {
                                txnIdRequest.setTableId(DoshokuOrder.getInstance().getOpenTableInfo().getId());
                            }
                            txnIdRequest.setAmount(mSaleRespose.getTXN_AMT());

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

                                @Override
                                public void onPosSuccess(HywebPosResponse response) {

                                }

                                @Override
                                public void onPosException(HywebPosResponse response) {
                                    if (findFragment(PosActionStatusExceptionFragment.class) == null) {
                                        PosActionStatusExceptionParam statusExceptionParam = new PosActionStatusExceptionParam();
                                        statusExceptionParam.setTxnId(mMealPayResultParam.getTxnId());
                                        statusExceptionParam.setAmount(mSaleRespose.getTXN_AMT());
                                        statusExceptionParam.setOrderNum(mMealPayResultParam.getMealOrderPayRequest().getOrderId());
                                        statusExceptionParam.setPayMethodName(mPayMehodNames);
                                        statusExceptionParam.setPosAction(PosAction.TIP);
                                        loadRootFragment(R.id.rl_container, PosActionStatusExceptionFragment.newInstance(statusExceptionParam));
                                    }
                                }

                                @Override
                                public void onSuccess(HywebPosResponse response) {

                                }

                                @Override
                                public void onError(Throwable e) {

                                }
                            });
                        }
                    }
                })
                .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;
    }

}
