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

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.gingersoft.gsa.cloud.base.application.GsaCloudApplication;
import com.gingersoft.gsa.cloud.base.common.bean.mealManage.OpenTableManage;
import com.billy.cc.core.component.CC;
import com.gingersoft.gsa.cloud.base.common.bean.mealManage.MyOrderManage;
import com.gingersoft.gsa.cloud.base.utils.VibratorUtils;
import com.gingersoft.gsa.cloud.base.utils.gson.GsonUtils;
import com.gingersoft.gsa.cloud.base.utils.log.LogUtil;
import com.gingersoft.gsa.cloud.base.utils.view.ViewUtils;
import com.gingersoft.gsa.cloud.table.R;
import com.gingersoft.gsa.cloud.table.R2;
import com.gingersoft.gsa.cloud.table.app.payment.PayConstant;
import com.gingersoft.gsa.cloud.table.app.payment.bean.AdjustTipRespose;
import com.gingersoft.gsa.cloud.table.app.payment.bean.RefundRespose;
import com.gingersoft.gsa.cloud.table.app.payment.bean.RetrievalRespose;
import com.gingersoft.gsa.cloud.table.app.payment.bean.SaleRespose;
import com.gingersoft.gsa.cloud.table.app.payment.bean.SettlementRespose;
import com.gingersoft.gsa.cloud.table.app.payment.bean.VoidRespose;
import com.gingersoft.gsa.cloud.table.app.payment.contract.IN5Callback;
import com.gingersoft.gsa.cloud.table.di.component.DaggerOrderPayComponent;
import com.gingersoft.gsa.cloud.table.mvp.contract.OrderPayContract;
import com.gingersoft.gsa.cloud.base.common.bean.PayMethod;
import com.gingersoft.gsa.cloud.table.mvp.presenter.OrderPayPresenter;
import com.gingersoft.gsa.cloud.table.mvp.ui.widget.PayKeypadDialog;
import com.gingersoft.gsa.cloud.ui.recylcler.decorator.GridDividerItemDecoration;
import com.gingersoft.gsa.cloud.ui.widget.dialog.LoadingDialog;
import com.gingersoft.gsa.cloud.ui.view.MaxHeightRecyclerView;
import com.gingersoft.gsa.cloud.ui.widget.dialog.StatusLoadingDialog;
import com.jess.arms.base.BaseActivity;
import com.jess.arms.base.DefaultAdapter;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.integration.AppManager;
import com.jess.arms.utils.ArmsUtils;
import com.qmuiteam.qmui.alpha.QMUIAlphaButton;
import com.qmuiteam.qmui.util.QMUIDisplayHelper;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;
import com.qmuiteam.qmui.widget.dialog.QMUIDialogAction;
import com.qmuiteam.qmui.widget.dialog.QMUITipDialog;

import org.simple.eventbus.EventBus;

import java.util.Date;

import javax.inject.Inject;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.RecyclerView;
import butterknife.BindView;
import butterknife.OnClick;

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


/**
 * ================================================
 * Description:
 * <p>
 * Created by MVPArmsTemplate on 01/09/2020 19:25
 * <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 OrderPayActivity extends BaseActivity<OrderPayPresenter> implements OrderPayContract.View {

    @Inject
    AppManager mAppManager;

    @BindView(R2.id.btn_table)
    QMUIAlphaButton btn_table;
    @BindView(R2.id.tv_action_name)
    TextView tv_action_name;
    @BindView(R2.id.btn_people_num)
    QMUIAlphaButton btn_people_num;
    @BindView(R2.id.tv_server_main)
    TextView tv_server_main;
    @BindView(R2.id.tv_time)
    TextView tv_time;

    @BindView(R2.id.tv_difference_name)
    TextView tv_difference_name;
    @BindView(R2.id.tv_difference_money)
    TextView tv_difference_money;

    @BindView(R2.id.rv_food)
    RecyclerView rv_food;
    @BindView(R2.id.rv_order_detail)
    RecyclerView rv_order_detail;

    @BindView(R2.id.rv_bill_method)
    MaxHeightRecyclerView rv_bill_method;
    @BindView(R2.id.rv_bill_money)
    MaxHeightRecyclerView rv_bill_money;

    //    @BindView(R.id.tv_whole)
//    TextView tv_whole;
    @BindView(R2.id.tv_total)
    TextView tv_total;

    @BindView(R2.id.btn_order_count)
    Button btn_order_count;

    //支付狀態Dialog
    private StatusLoadingDialog mStatusLoadingDialog;
    private QMUITipDialog tipDialog;

    /**
     * N5相关
     */
    private String N5_RESP;
    //支付回调数据
    private SaleRespose saleRespose;
    //退款回调数据
    private RefundRespose refundRespose;


    public static void startOrderPayActivityFormSale(Context context, String response) {
        Intent intent = new Intent(context, OrderPayActivity.class);
        intent.setAction("SALE_RESP");
        intent.putExtra("SALE_DATA", response);
        context.startActivity(intent);
    }

    public static void startOrderPayActivityFormRefund(Context context, String response) {
        Intent intent = new Intent(context, OrderPayActivity.class);
        intent.setAction("REFUND_RESP");
        intent.putExtra("REFUND_DATA", response);
        context.startActivity(intent);
    }

//    private List<BillMethodBean> billMoney = new ArrayList<>();
//    private BillMoneyAdapter billMoneyAdapter;

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

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        Intent intent = getIntent();
//        N5CallbackManage.getInstance().register(this, in5Callback);
        super.onCreate(savedInstanceState);
        if (savedInstanceState == null) {
//            mPresenter.getPayMethods();
        }
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
//        outState.putSerializable(PRE_BILL_DATA, mPresenter.getPreBillData());
//        outState.putSerializable(PAY_METHOD, mPresenter.getBillMethodList());
        super.onSaveInstanceState(outState);
    }

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

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

        mPresenter.initAdapter();
        mPresenter.initBillListener();
        initTopInfo();
        initOrderDetail();
        initN5RespCallBack();

        mPresenter.getPayMethods();
    }

    private void initTopInfo() {

        Date dd = new Date(OpenTableManage.getDefault().getTableBean().getCreateTime());
        String openTime = String.format("%tH:%tM", dd, dd);

        String tableno = "";
        if (!OpenTableManage.getDefault().isSplite()) {
            tableno = OpenTableManage.getDefault().getTableBean().getTableName();
        } else {
            tableno = OpenTableManage.getDefault().getTableBean().getTableName().trim() + "-" + OpenTableManage.getDefault().getSplitNo().trim();
        }
        btn_table.setText(tableno);

        tv_time.setText("開檯時間" + openTime);
        btn_people_num.setText(OpenTableManage.getDefault().getPeopleNumber() + "");
        tv_server_main.setText("waiter:" + GsaCloudApplication.getMemberName(this));

        tv_action_name.setBackgroundColor(Color.parseColor("#C50000"));
        tv_action_name.setText("結賬");
    }

    public void initOrderDetail() {

        int foodCount = mPresenter.getFoodCount();
        if (foodCount > 0) {
            btn_order_count.setText(String.valueOf(foodCount));
            btn_order_count.setVisibility(View.VISIBLE);
        } else {
            btn_order_count.setVisibility(View.INVISIBLE);
        }

        double total = mPresenter.getTotalMoney();
        tv_total.setText("$" + total);

        setDifferenceText();
    }

    @Override
    public void setDifferenceText() {
        double difference = mPresenter.getDifferenceMoney();
        if (difference < 0) {
            //貼士
            tv_difference_name.setText("貼士");
            tv_difference_money.setTextColor(ArmsUtils.getColor(this, R.color.Grass_green));
            tv_difference_money.setText("$" + Math.abs(difference));
        } else {
            //尚欠
            tv_difference_name.setText("尚欠金額");
            tv_difference_money.setTextColor(ArmsUtils.getColor(this, R.color.red));
            if (difference == 0)
                tv_difference_money.setText("$" + Math.abs(difference));
            else
                tv_difference_money.setText("$-" + Math.abs(difference));
        }
    }

//    public void initBillMethod() {
//        rvPay.setLayoutManager(new GridLayoutManager(mContext, 4));
//        //每一種結賬方式的金額
//        //結賬方式
//        List<BillMethodBean> data = new ArrayList<>();
//        data.add(new BillMethodBean(1, "現金"));
//        BillMethodAdapter adapter = new BillMethodAdapter(data);
//        rvPay.setAdapter(adapter);
//
//        billMoneyAdapter = new BillMoneyAdapter(billMoney);
//        rvSelectedPay.setLayoutManager(new LinearLayoutManager(mContext));
//        rvSelectedPay.setAdapter(billMoneyAdapter);
//
//        adapter.setOnItemClickListener((adapter13, view, position) -> {
//            if (!billMoney.containsAll(data)) {
//                billMoney.add(data.get(position));
//                billMoneyAdapter.notifyDataSetChanged();
//            }
//        });
//
//        billMoneyAdapter.setOnItemChildClickListener((adapter12, view, position) -> {
//            if (view.getId() == R.id.iv_bill_delete) {
//                //刪除當前付款方式
//                ownMoney = MoneyUtil.sum(ownMoney, billMoney.get(position).getMoney());//還原尚欠金額;
//                billMoney.get(position).setMoney(0);
//                billMoney.remove(position);
//                billMoneyAdapter.notifyDataSetChanged();
//                setOwnMoney(ownMoney);
//            }
//        });
//    }

    @OnClick({R2.id.btn_people_num, R2.id.btn_table, R2.id.btn_sure_pay, R2.id.btn_exact, R2.id.btn_keypad})
    public void onClick(View v) {

        recordOperat(true);

        if (!ViewUtils.isFastClick2()) {
            return;
        }

        int id = v.getId();

        if (id == R.id.btn_table) {
            backPressed();
        } else if (id == R.id.btn_sure_pay) {
            if (mPresenter.getBillMoneyList().size() == 0) {
                showMessage("請選擇支付方式");
                return;
            }
            if (!mPresenter.canPay()) {
                tipMoneyInsufficient();
                return;
            }
            mPresenter.updateOrderState("4");
        } else if (id == R.id.btn_exact) {
            if (mPresenter.getSelectBillMoney() == null) {
                showMessage("請選擇支付方式");
                return;
            }
            mPresenter.pressExact();
            setDifferenceText();
        } else if (id == R.id.btn_keypad) {
            if (mPresenter.getSelectBillMoney() == null) {
                showMessage("請選擇支付方式");
                return;
            }
            showPayKeypadDialog();
        }
    }

    private void backPressed() {
//        if (isPrepay) {
//            //恢復預結賬前的食品
//            mPresenter.restorePrepayBeaforeOrderFoodList();
//        }
        killMyself();
    }

    @Override
    public void onBackPressed() {
        backPressed();
    }

    private void tipMoneyInsufficient() {
        if (tipDialog == null) {
            tipDialog = new QMUITipDialog.Builder(this)
                    .setIconType(QMUITipDialog.Builder.ICON_TYPE_INFO)
                    .setTipWord("金額不足!")
                    .create();
        }
        tipDialog.show();
        btn_order_count.postDelayed(new Runnable() {
            @Override
            public void run() {
                tipDialog.dismiss();
            }
        }, 1500);
    }

    @Override
    public void initIntent() {
        Intent intent = getIntent();
        N5_RESP = intent.getAction();
        LogUtil.d(TAG, "initIntent N5_RESP: " + N5_RESP);
        if (!TextUtils.isEmpty(N5_RESP)) {
            if (N5_RESP.equals("SALE_RESP")) {
                //N5支付回調数据
                String saleDataJson = intent.getStringExtra("SALE_DATA");
                saleRespose = GsonUtils.GsonToBean(saleDataJson, SaleRespose.class);
            } else if (N5_RESP.equals("REFUND_RESP")) {
                //N5退款回調数据
                String refundDataJson = intent.getStringExtra("REFUND_DATA");
                refundRespose = GsonUtils.GsonToBean(refundDataJson, RefundRespose.class);
            }
        }
    }

    @Override
    public void initTopBar() {

    }

    @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 showStatusDialog(int operatType) {
        if (mStatusLoadingDialog == null) {
            mStatusLoadingDialog = new StatusLoadingDialog(this);
        }
        switch (operatType) {
            case StatusLoadingDialog.SALE_LOADING:
                mStatusLoadingDialog.setOpeatType(StatusLoadingDialog.VOID_LOADING);
                mStatusLoadingDialog.setLoadingText("支付");
                mStatusLoadingDialog.setStatusText("支付中...");
                break;
            case StatusLoadingDialog.REFUND_LOADING:
                mStatusLoadingDialog.setOpeatType(StatusLoadingDialog.VOID_LOADING);
                mStatusLoadingDialog.setLoadingText("退款");
                mStatusLoadingDialog.setStatusText("退款中...");
                break;
            case StatusLoadingDialog.VOID_LOADING:
                mStatusLoadingDialog.setOpeatType(StatusLoadingDialog.VOID_LOADING);
                mStatusLoadingDialog.setLoadingText("取消");
                mStatusLoadingDialog.setStatusText("取消...");
                break;
        }
        mStatusLoadingDialog.show();
    }

    @Override
    public void showTipDialog(String msg, String btnCancelInfo, String btnOkInfo) {
        QMUIDialog.MessageDialogBuilder dialogBuilder = new QMUIDialog.MessageDialogBuilder(this);
        dialogBuilder.setTitle(" order ");
        dialogBuilder.setMessage(msg);
        dialogBuilder.setCancelable(false);
        if (btnCancelInfo.length() == 0)
            btnCancelInfo = " cancel ";
        dialogBuilder.addAction(btnCancelInfo, new QMUIDialogAction.ActionListener() {

            @Override
            public void onClick(QMUIDialog dialog, int index) {
                dialog.dismiss();
                recordOperat(true);

            }
        });
        if (!TextUtils.isEmpty(btnOkInfo)) {
            dialogBuilder.addAction(0, btnOkInfo, QMUIDialogAction.ACTION_PROP_NEGATIVE, new QMUIDialogAction.ActionListener() {

                @Override
                public void onClick(QMUIDialog dialog, int index) {
                    dialog.dismiss();
                    recordOperat(true);

                }
            });
        }
        dialogBuilder.create(R.style.QMUI_Dialog).show();
    }

    @Override
    public void showPayKeypadDialog() {
        PayMethod method = mPresenter.getSelectBillMoney();
        new PayKeypadDialog(this)
                .setPayMethod(method.getPayName())
                .builder()
                .setComfirmListener(new PayKeypadDialog.OnComfirmListener() {

                    @Override
                    public void onComfirm(String money) {
                        PayMethod billMoneyBean = mPresenter.getSelectBillMoney();
                        billMoneyBean.setPayMoney(Double.parseDouble(money));
                        mPresenter.getBillMoneyAdapter().notifyDataSetChanged();

                        setDifferenceText();
                    }
                })
                .show();
    }

    @Override
    public void recordOperat(boolean isPressButtonSound) {
        if (isPressButtonSound)
            VibratorUtils.pressButtonSound(this);
    }

    @Override
    public void setFoodAdapter(DefaultAdapter adapter) {
        rv_food.setAdapter(adapter);
    }

    @Override
    public void paySuccess() {
        //修改結賬方式數據
        MyOrderManage.getInstance().setBillMoney(mPresenter.getBillMoneyList());
        if (OpenTableManage.getDefault() != null) {
            //通知更新餐台状态
            EventBus.getDefault().post(OpenTableManage.getDefault().getTableBean().getId(), "initTable_status_event");
        }
        showMessage("支付成功");
        //打印結賬單
        CC.obtainBuilder("Component.Print")
                .setActionName("printActivity")
                .addParam("type", 2)
                .build()
                .callAsync((cc, result) -> {
                    if (result.isSuccess()) {
                        //打印成功

                    }
                });
        setResult(Activity.RESULT_OK, null);
        killMyself();
    }

    public void setBillMethodAdapter(BaseQuickAdapter adapter) {
        rv_bill_method.setAdapter(adapter);
        rv_bill_method.addItemDecoration(new GridDividerItemDecoration(QMUIDisplayHelper.dpToPx(1), ArmsUtils.getColor(this, R.color.theme_hint_color)));
    }

    @Override
    public void setBillMoneyAdapter(BaseQuickAdapter adapter) {
        rv_bill_money.setAdapter(adapter);
    }

    @Override
    public void setOrderDetailAdapter(DefaultAdapter adapter) {
        rv_order_detail.setAdapter(adapter);
    }

    @Override
    public void setBillMoneyRvScrollToPosition(int position) {
        rv_bill_money.scrollToPosition(position);
    }

    @Override
    public StatusLoadingDialog getStatusLoadingDialog() {
        return mStatusLoadingDialog;
    }

    @Override
    public void showSaleStatusDialog(SaleRespose saleRespose) {
        //顯示支付成功提示彈窗
        showStatusDialog(StatusLoadingDialog.SALE_LOADING);
//        switch (saleRespose.getSTATUS()) {
//            case PayConstant.PAY_STATUS_00:
//                boolean useExternalPrint = GSAApplication.deviceType != GSAApplication.DEVICE_PHONE && !AndroidSettingUtils.isUseExternalPrint();
//                if (PayVariableManage.getInstance().isModifyOrderOperat()) {
//                    if (useExternalPrint) {
//                        //支付回传数据（手持設備打印結賬單）
//                        mPresenter.sumitOrder(SendOrderConstant.send_style_7);
//                    } else {
//                        //支付回传数据（外部打印結賬單）
//                        mPresenter.sumitOrder(SendOrderConstant.send_style_8);
//                    }
//                } else {
//                    if (useExternalPrint) {
//                        //支付回传数据（外部打印結賬單）
//                        mPresenter.sumitOrder(SendOrderConstant.send_style_6);
//                    } else {
//                        //支付回传数据（手持設備打印結賬單）
//                        mPresenter.sumitOrder(SendOrderConstant.send_style_5);
//                    }
//                }
//                break;
//            default:
//                onPayFailure(saleRespose.getSTATUS());
//                break;
//        }
    }

    @Override
    public void showRefundStatusDialog(RefundRespose voidRespose) {

    }

    @Override
    public void onPayFailure(String status) {
        mStatusLoadingDialog.loadFailure(status);
        mStatusLoadingDialog.setOnLoadStautsListener(new StatusLoadingDialog.OnLoadStautsListener() {

            @Override
            public void loadSuccessEnd() {

//                //只有支付成功才返回到原有页面
//                EventBus.getDefault().postSticky(true, EventTagConstant.UPDATE_ORDER_LIST);
//
//                mAppManager.killActivity(OrderContentActivity.class);
//                mAppManager.killActivity(MealStandActivity.class);
//                mAppManager.killActivity(OrderDetailActivity.class);
//                mAppManager.killActivity(OrderPayActivity.class);
////                if (variableManage.isModifyOrderOperat()) {
////                    mAppManager.killActivity(TableServiceActivity.class);
////                } else {
//                mAppManager.killActivity(OrderManagementActivity.class);
////                }
            }

            @Override
            public void loadFailureEnd() {
                if (status.equals(PayConstant.PAY_STATUS_00)) {
                    returnTableActivityBefore();
                }
            }
        });
    }

    public void returnTableActivityBefore() {
//        mPresenter.setTablesStatus(GSAApplication.tableContract.getTableTNID(), GSAApplication.tableContract.getIsSplite(), GSAApplication.tableContract.getTableno_split());
//        GSAApplication.tableContract.init();
        returnTableServiceAcivity(false);
    }

    public void returnTableServiceAcivity(boolean iskill) {
//        GSAApplication.tableContract.setIsSplite(false);
//        GSAApplication.tableContract.setTableno_split("");
        if (iskill) {
            killMyself();
        }
    }

    public SaleRespose getSaleRespose() {
        return saleRespose;
    }

    public void setSaleRespose(SaleRespose saleRespose) {
        this.saleRespose = saleRespose;
    }

//    public boolean isPrepay() {
//        return isPrepay;
//    }

    public void initN5RespCallBack() {
        if (!TextUtils.isEmpty(N5_RESP)) {
            if (N5_RESP.equals("SALE_RESP") && saleRespose != null) {
                LogUtil.d(TAG, "initN5RespCallBack: " + N5_RESP + "  " + saleRespose.toString());
                showSaleStatusDialog(saleRespose);
            } else if (N5_RESP.equals("REFUND_RESP") && refundRespose != null) {
                showRefundStatusDialog(refundRespose);
            }
        }
    }

    private IN5Callback in5Callback = new IN5Callback() {

        @Override
        public void onSaleCall(SaleRespose response) {

            saleRespose = response;
            showMessage("onSaleCall: " + response.toString());
//            showSaleStatusDialog(response);
        }

        @Override
        public void onVoidCall(VoidRespose response) {

//            showVoidStatusDialog(response);
        }

        @Override
        public void onRefundCall(RefundRespose response) {

//            showRefundStatusDialog(response);
        }

        @Override
        public void onRetrievalCall(RetrievalRespose response) {

            SaleRespose saleRespose = new SaleRespose();
            saleRespose.setSTATUS(response.getSTATUS());
//            showSaleStatusDialog(saleRespose);
        }

        @Override
        public void onAdjustCall(AdjustTipRespose response) {

        }

        @Override
        public void onSettleCall(SettlementRespose response) {

        }

        @Override
        public void onPrinterCall(String response) {

        }
    };

    @Override
    public void onPointerCaptureChanged(boolean hasCapture) {

    }
}
