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.ScrollView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.RecyclerView;

import com.billy.cc.core.component.CC;
import com.gingersoft.gsa.cloud.common.loadsir.ErrorCallback;
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.MealPayResultEvent;
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.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.mvp.ui.adapter.ResultBillItemAdapter;
import com.gingersoft.gsa.cloud.pay.pos.OnPosActionListener;
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.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.BaseActivity;
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.widget.QMUITopBar;
import com.qmuiteam.qmui.widget.roundwidget.QMUIRoundButton;

import org.simple.eventbus.Subscriber;

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 BaseActivity<PayResultPresenter> implements PayResultContract.View {

    @BindView(R2.id.topbar)
    QMUITopBar topbar;

    @BindView(R2.id.scrollView)
    ScrollView scrollView;
    @BindView(R2.id.tv_table_name)
    TextView tvTableName;
    @BindView(R2.id.tv_order_num)
    TextView tvOrderNum;
    @BindView(R2.id.rv_bill_and_paymethod)
    RecyclerView rvBillAndPaymethod;
    @BindView(R2.id.btn_tips)
    QMUIRoundButton btnTips;
    @BindView(R2.id.btn_printer)
    QMUIRoundButton btnPrinter;
    @BindView(R2.id.btn_complate)
    QMUIRoundButton btnComplate;
    @BindView(R2.id.ll_container)
    LinearLayout llContainer;

    @BindView(R2.id.tv_paymethod)
    TextView tv_paymethod;

    private LoadService loadService;

    private MealPayResultEvent mPayResultEvent;

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

    @Subscriber(tag = "onIntentPayStatusSuccess")
    private void onIntentPayStatusSuccess(MealPayResultEvent payResultEvent) {
        this.mPayResultEvent = payResultEvent;
        if (payResultEvent.getSaleRespose().getSTATUS().equals(PayStatusCode.PAY_STATUS_00)) {

            ResultBillItemAdapter adapter = new ResultBillItemAdapter(payResultEvent.getBillItemList());
            rvBillAndPaymethod.setAdapter(adapter);

            tv_paymethod.setText(getPayMehodStr(payResultEvent.getPayMethodList()));
            tvTableName.setText("檯號: " + payResultEvent.getTableBean().getTableName());
            tvOrderNum.setText("單號: " + payResultEvent.getMealOrderPayRequest().getOrderId());
            loadService.showSuccess();
        } else {
            loadService.showCallback(ErrorCallback.class);
        }
    }

    @Subscriber(tag = "onIntentPayStatusError")
    private void onIntentPayStatusError(MealPayResultEvent payResultEvent) {
        this.mPayResultEvent = payResultEvent;
        loadService.showCallback(ErrorCallback.class);
    }

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

    /**
     * 重新調起Hyweb重新獲取支付狀態
     */
    private void onRetrievalRequest(String txnId) {
        RetrievalRequest retrievalRequest = new RetrievalRequest();
        retrievalRequest.setTXN_ID(txnId);
        DoshokuOrder.getInstance().retrieval(mContext, PayResultActivity.this, retrievalRequest, new OnPosActionListener() {
            @Override
            public void onSuccess(HywebPosResponse response) {
                loadService.showSuccess();
            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onResponseNull() {

            }

        });
    }

    @Override
    public void initIntent() {

    }

    @Override
    public void initTopBar() {
        topbar.setTitle("支付結果");
        topbar.setBackgroundColor(ContextCompat.getColor(this, R.color.theme_color));
//        topbar.addLeftBackImageButton().setOnClickListener(new View.OnClickListener() {
//
//            @Override
//            public void onClick(View v) {
//                killMyself();
//            }
//        });
    }

    @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();
    }

    @OnClick({R2.id.btn_tips, R2.id.btn_printer, R2.id.btn_complate})
    public void onViewClicked(View view) {
        if (view.getId() == R.id.btn_tips) {
            showKeyboardDialog();
        } else if (view.getId() == R.id.btn_printer) {

        } else if (view.getId() == R.id.btn_complate) {
            //返回餐檯頁面
            CC.obtainBuilder(ComponentName.COMPONENT_TABLE)
                    .setActionName(ComponentAction.Table.KILL_MEAL_ORDER_PAY)
                    .build()
                    .call();
        }
    }

    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());

                            DoshokuOrder.getInstance().tip(mContext, PayResultActivity.this, txnIdRequest, getTipsRequest(mPayResultEvent.getSaleRespose(), Double.parseDouble(number)), new OnPosActionListener() {
                                @Override
                                public void onSuccess(HywebPosResponse response) {
                                    //刷新賬單頁面

                                }

                                @Override
                                public void onError(Throwable e) {

                                }

                                @Override
                                public void onResponseNull() {
                                    onRetrievalRequest(mPayResultEvent.getTxnId());
                                }
                            });
                        }
                    }
                })
                .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;
    }
}
