package com.gingersoft.gsa.cloud.bean.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.util.Log;
import android.view.View;
import android.widget.TextView;

import com.billy.cc.core.component.CC;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.gingersoft.gsa.cloud.base.application.GsaCloudApplication;
import com.gingersoft.gsa.cloud.base.common.bean.MemberInfo;
import com.gingersoft.gsa.cloud.base.common.bean.PayMethod;
import com.gingersoft.gsa.cloud.base.order.bean.mealManger.MyOrderManage;
import com.gingersoft.gsa.cloud.base.order.bean.mealManger.OpenTableManage;
import com.gingersoft.gsa.cloud.base.utils.BigDecimalUtils;
import com.gingersoft.gsa.cloud.base.utils.LanguageUtils;
import com.gingersoft.gsa.cloud.base.utils.MoneyUtil;
import com.gingersoft.gsa.cloud.base.utils.VibratorUtils;
import com.gingersoft.gsa.cloud.constans.PrintConstans;
import com.gingersoft.gsa.cloud.print.PrinterUtils;
import com.gingersoft.gsa.cloud.bean.R;
import com.gingersoft.gsa.cloud.bean.R2;
import com.gingersoft.gsa.cloud.bean.app.payment.bean.RefundRespose;
import com.gingersoft.gsa.cloud.bean.app.payment.bean.SaleRespose;
import com.gingersoft.gsa.cloud.bean.di.component.DaggerOrderPayComponent;
import com.gingersoft.gsa.cloud.bean.mvp.contract.OrderPayContract;
import com.gingersoft.gsa.cloud.bean.mvp.model.bean.event.InitTableEvent;
import com.gingersoft.gsa.cloud.bean.mvp.presenter.OrderPayPresenter;
import com.gingersoft.gsa.cloud.ui.view.OrderPayView;
import com.gingersoft.gsa.cloud.ui.view.PayKeypadDialog;
import com.gingersoft.gsa.cloud.ui.widget.dialog.LoadingDialog;
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.widget.dialog.QMUIDialog;
import com.qmuiteam.qmui.widget.dialog.QMUIDialogAction;

import org.simple.eventbus.EventBus;

import java.util.Date;
import java.util.List;

import javax.inject.Inject;

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

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, View.OnLongClickListener {

    @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_member_info)
    TextView tv_member_info;

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

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

    @BindView(R2.id.gsa_pay_view)
    OrderPayView gsaPayView;

    /**
     * 會員積分數
     */
    private double memberIntegral = 0;
    /**
     * 額外食品加分
     */
    private double pointsAdd;
    /**
     * 換購食品所需積分
     */
    private double pointsRedeem;
    /**
     * 積分兌換現金比例（MemberPointRedeemCash=2 （理解為每2分=1元）
     */
    private double memberPointRedeemCash = 0;
    /**
     * 積分規則
     */
    private int pointRule;

    private int mWhetherFreeService = 0;

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

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


    @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();
        mPresenter.getPayMethods();
        initOrderPayView();
        initTopInfo();
        initOrderDetail();
        initMemberInfo();
    }

    private void initOrderPayView() {
        gsaPayView.setOnSelectPayClickLisenter(new OrderPayView.OnSelectPayClickLisenter() {
            @Override
            public void addClick(PayMethod method) {
                if (method.getPayType() == PayMethod.PAY_TYPE_INTEGRAL) {
                    updateMemberInfo();
                }
            }

            @Override
            public void delClick(PayMethod method) {
                if (method.getPayType() == PayMethod.PAY_TYPE_INTEGRAL) {
                    updateMemberInfo();
                }
            }

            @Override
            public void updateIntergralInfo() {
                updateMemberInfo();
            }
        });
        gsaPayView.setOnFreeServiceStatusChangeLisenter(new OrderPayView.OnFreeServiceStatusChangeLisenter() {
            @Override
            public void onFreeServiceStautsChange(boolean isUseFreeServicePayMethod) {
                mPresenter.setFreeServiceStauts(isUseFreeServicePayMethod);
            }
        });
        gsaPayView.setServiceCharge(mPresenter.getServiceCharge());
    }

    private void initTopInfo() {

        Date dd = MyOrderManage.getInstance().getOpenTableTime();
        String openTime = String.format("%tH:%tM", dd, dd);

        String tableno = "";
        if (!OpenTableManage.getDefault().isSplite()) {
            if (OpenTableManage.getDefault().getTableBean() != null) {
                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(GsaCloudApplication.getMemberName());

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


    public void initOrderDetail() {
        double wholeAmount = mPresenter.getFoodTotal();
        tv_whole.setText("合計  $" + wholeAmount);

        MyOrderManage.getInstance().setWholeAmount(wholeAmount);
    }

    private void initMemberInfo() {
        //会员信息
        MemberInfo memberInfo = MyOrderManage.getInstance().getMemberInfo();
        if (memberInfo != null) {
            tv_member_info.setVisibility(View.VISIBLE);
            tv_member_info.setText(getMemberInfo());
            gsaPayView.setMemberInfo(memberInfo);
        } else {
            tv_member_info.setVisibility(View.GONE);
        }
    }

    public void updateMemberInfo() {
        tv_member_info.setText(getMemberInfo());
    }

    private String getMemberInfo() {
        MemberInfo memberBean = MyOrderManage.getInstance().getMemberInfo();
        String memberInfo;
        String memberName = memberBean.getMemberName();
        String LevelName1 = memberBean.getLevelName1();
//        if (!TextUtils.isEmpty(LevelName1)) {
//            memberInfo = LanguageUtils.get_language_system(this, "meal.info.member.name", "會員名稱:")
//                    + memberName
//                    + "(" + LevelName1 + ")";
//        } else {
        memberInfo = LanguageUtils.get_language_system(this, "meal.info.member.name", "會員:") + memberName;
//        }
//        boolean showPoints = false;
//        if (mPresenter.getPointsAdd() != 0 && mPresenter.getPointsRedeem() != 0) {
//            memberInfo = memberInfo + ":" + memberBean.getMemberPoint() + "  +" + mPresenter.getPointsAdd() + "     -" + mPresenter.getPointsRedeem();
//            showPoints = true;
//        } else {
//            if (mPresenter.getPointsAdd() != 0) {
//                memberInfo = memberInfo + ":" + memberBean.getMemberPoint() + "  +" + mPresenter.getPointsAdd();
//                showPoints = true;
//            }
//            if (mPresenter.getPointsRedeem() != 0) {
//                memberInfo = memberInfo + ":" + memberBean.getMemberPoint() + "  -" + mPresenter.getPointsRedeem();
//                showPoints = true;
//            }
//        }
//        if (!showPoints) {
//            memberInfo = memberInfo + ":" + memberBean.getMemberPoint();
//        }
        memberIntegral = memberBean.getMemberPoint();
        memberPointRedeemCash = memberBean.getPointRedeemCash();
        //獲取積分支付抵扣金額
        double consumptionPoints = gsaPayView.getPayForConsumptionPoints(null,memberPointRedeemCash);
        //本次積分消耗（積分支付 + 食品獲得積分 + 食品消費積分）
        double thisTimePoints = BigDecimalUtils.add(BigDecimalUtils.add(consumptionPoints, mPresenter.getPointsAdd()), mPresenter.getPointsRedeem());
        if (thisTimePoints > 0) {
            memberInfo = memberInfo + ": " + BigDecimalUtils.format(memberIntegral) + "     " + "-" + BigDecimalUtils.format(thisTimePoints);
        } else {
            memberInfo = memberInfo + ": " + BigDecimalUtils.format(memberIntegral);
        }
        return memberInfo;
    }

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

        recordOperat(true);

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

    @Override
    @OnLongClick({R2.id.btn_sure_pay})
    public boolean onLongClick(View v) {
        if (v.getId() == R.id.btn_sure_pay) {
            PrinterUtils.switchPrintMethod(mContext, null, null);
        }
        return false;
    }

    private void backPressed() {
        killMyself();
    }

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

    @Override
    public void initIntent() {
    }

    @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(OrderPayActivity.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) {
    }

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

                }
            });
        }
        if (btnCancelInfo.length() == 0)
            btnCancelInfo = " cancel ";
        dialogBuilder.addAction(btnCancelInfo, 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() {
        //修改結賬方式數據
        setBillMoney();
        if (!MyOrderManage.getInstance().isModifyOrder() && OpenTableManage.getDefault() != null && OpenTableManage.getDefault().getTableBean() != null) {
            //通知更新餐台状态
            EventBus.getDefault().post(new InitTableEvent(OpenTableManage.getDefault().getTableBean().getId(), OpenTableManage.getDefault().getTableBean().getTableNumber()), "initTable_status_event");
        }
        showMessage("支付成功");

        //開錢箱
        boolean openInstruction = false;
        List<PayMethod> payMethods = gsaPayView.getBillMoneyList();
        for (PayMethod payMethod : payMethods) {
            if (payMethod.getWhetherOpenBox() == 1) {
                openInstruction = true;
                break;
            }
        }
        if (openInstruction) {
            printBill();
            CC.obtainBuilder("Component.Print")
                    .setActionName("printActivity")
                    .addParam(PrintConstans.PRINT_TYPE, PrintConstans.PRINT_INSTRUCTION)
                    .build();
        } else {
            printBill();
        }
    }

    private void printBill() {
        //打印結賬單
        CC.obtainBuilder("Component.Print")
                .setActionName("printActivity")
                .addParam(PrintConstans.PRINT_TYPE, PrintConstans.PRINT_BILL)
                .build()
                .callAsyncCallbackOnMainThread((cc, result) -> {
                    Log.e("error", "是否成功打印：" + result.isSuccess());
//                    if (result.isSuccess()) {
//                        //打印成功
//                    }
                    //清空賬單數據
                    MyOrderManage.getInstance().clear();
                    //清空開檯數據
                    OpenTableManage.getDefault().clear();
                    setResult(Activity.RESULT_OK, null);
                    killMyself();
                });
    }

    private void setBillMoney() {
        List<PayMethod> billMoneyList = mPresenter.getBillMoneyList();
        if (mPresenter.getTipsPrice() != 0) {
            //打印添加找零或貼士行
//            String linePayType = tv_difference_name.getText().toString();
            PayMethod payMethod = new PayMethod();
            //這裡打印退一格
            payMethod.setPayName("     " + (mPresenter.getLinePayType() == 1 ? "找零" : "貼士"));
            payMethod.setPayMoney(mPresenter.getTipsPrice());
            billMoneyList.add(payMethod);
        }
        MyOrderManage.getInstance().setBillMoney(billMoneyList);
    }

    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 null;
    }

    @Override
    public void showSaleStatusDialog(SaleRespose saleRespose) {
        //顯示支付成功提示彈窗
        showStatusDialog(StatusLoadingDialog.SALE_LOADING);
    }

    @Override
    public void showRefundStatusDialog(RefundRespose voidRespose) {

    }

    @Override
    public void onPayFailure(String status) {
    }

    @Override
    public void loadPayMethodsSuccess(List<PayMethod> payMethods) {
        gsaPayView.loadInfo(this, payMethods, mPresenter.getTotalAmount(), mPresenter.getFoodCount());
        gsaPayView.setmOnSureClickLisenter(mBillMoneyList -> {
            mPresenter.setBillMoneyList(mBillMoneyList);
            mPresenter.sendOrderBefore();
        });
    }

    public void returnTableActivityBefore() {
        returnTableServiceAcivity(false);
    }

    public void returnTableServiceAcivity(boolean iskill) {
        if (iskill) {
            killMyself();
        }
    }


    @Override
    public void onPointerCaptureChanged(boolean hasCapture) {

    }

    public OrderPayView getGsaPayView() {
        return gsaPayView;
    }


}
