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.print.PrintManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.RecyclerView;

import com.billy.cc.core.component.CC;
import com.billy.cc.core.component.CCResult;
import com.billy.cc.core.component.IComponentCallback;
import com.gingersoft.gsa.cloud.common.constans.PrintConstans;
import com.gingersoft.gsa.cloud.common.core.member.MemberInfo;
import com.gingersoft.gsa.cloud.common.core.table.TableBean;
import com.gingersoft.gsa.cloud.common.core.user.UserContext;
import com.gingersoft.gsa.cloud.common.logan.LoganManager;
import com.gingersoft.gsa.cloud.common.utils.AppDevices;
import com.gingersoft.gsa.cloud.common.utils.BigDecimalUtils;
import com.gingersoft.gsa.cloud.common.utils.JsonUtils;
import com.gingersoft.gsa.cloud.common.utils.LanguageUtils;
import com.gingersoft.gsa.cloud.common.utils.VibratorUtils;
import com.gingersoft.gsa.cloud.component.ComponentName;
import com.gingersoft.gsa.cloud.database.bean.Discount;
import com.gingersoft.gsa.cloud.database.utils.DiscountDaoUtils;
import com.gingersoft.gsa.cloud.order.bean.request.MealOrderPayRequest;
import com.gingersoft.gsa.cloud.order.billItem.BillItem;
import com.gingersoft.gsa.cloud.order.order.DoshokuOrder;
import com.gingersoft.gsa.cloud.pay.bean.PayMethod;
import com.gingersoft.gsa.cloud.pay.contract.PayTypeContract;
import com.gingersoft.gsa.cloud.pay.pos.OnPosActionListener;
import com.gingersoft.gsa.cloud.pay.pos.PosPay;
import com.gingersoft.gsa.cloud.pay.pos.hywebpos.bean.request.bg.GetTxnIdRequest;
import com.gingersoft.gsa.cloud.pay.pos.hywebpos.bean.request.pos.SaleRequest;
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.pos.hywebpos.constant.PayMethodConstant;
import com.gingersoft.gsa.cloud.pay.util.PayMethodUtils;
import com.gingersoft.gsa.cloud.print.PrinterUtils;
import com.gingersoft.gsa.cloud.print.bean.PrintContent;
import com.gingersoft.gsa.cloud.print.bean.adapter.PrintContentAdapter;
import com.gingersoft.gsa.cloud.table.R;
import com.gingersoft.gsa.cloud.table.R2;
import com.gingersoft.gsa.cloud.table.di.component.DaggerOrderPayComponent;
import com.gingersoft.gsa.cloud.table.mvp.contract.OrderPayContract;
import com.gingersoft.gsa.cloud.table.mvp.model.bean.event.InitTableEvent;
import com.gingersoft.gsa.cloud.table.mvp.presenter.OrderPayPresenter;
import com.gingersoft.gsa.cloud.ui.view.OrderPayView;
import com.gingersoft.gsa.cloud.ui.widget.dialog.LoadingDialog;
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 com.xuexiang.rxutil2.rxjava.RxJavaUtils;
import com.xuexiang.rxutil2.rxjava.RxSchedulerUtils;

import org.simple.eventbus.EventBus;

import java.sql.Time;
import java.util.Date;
import java.util.List;
import java.util.Observer;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.OnClick;
import butterknife.OnLongClick;
import io.reactivex.Observable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

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;
    /**
     * 積分兌換現金比例（MemberPointRedeemCash=2 （理解為每2分=1元）
     */
    private double memberPointRedeemCash = 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);
    }

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

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
    }

    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 updateIntegralInfo() {
                updateMemberInfo();
            }
        });
        gsaPayView.setOnFreeServiceStatusChangeLisenter(new OrderPayView.OnFreeServiceStatusChangeLisenter() {
            @Override
            public void onFreeServiceStautsChange(boolean isUseFreeServicePayMethod) {
                mPresenter.setFreeServiceStauts(isUseFreeServicePayMethod);
            }
        });
        gsaPayView.setServiceCharge(mPresenter.getShoppingCart().getServiceCharge());
    }

    private void initTopInfo() {

        TableBean.DataBean tableInfo = DoshokuOrder.getInstance().getOpenTableInfo();

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

        String tableno = "";
        if (tableInfo.getSplitStatus() != 0) {
            tableno = tableInfo.getTableName().trim() + "-" + tableInfo.getTableNumber().trim();
        } else {
            tableno = tableInfo.getTableName();
        }
        btn_table.setText(tableno);
        tv_time.setText("時間:" + openTime);
        btn_people_num.setText(tableInfo.getPerson() + "");
        tv_server_main.setText(UserContext.newInstance().getMemberName());

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


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

        DoshokuOrder.getInstance().getShoppingCart().setWholeAmount(wholeAmount);
    }

    private void initMemberInfo() {
        //会员信息
        MemberInfo memberInfo = DoshokuOrder.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 = DoshokuOrder.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();
        }
    }

    @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 recordOperat(boolean isPressButtonSound) {
        if (isPressButtonSound) {
            VibratorUtils.pressButtonSound(this);
        }
    }

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

    @Override
    public void paySuccess() {
        //修改結賬方式數據
        setBillMoney();

        TableBean.DataBean tableInfo = DoshokuOrder.getInstance().getOpenTableInfo();
        if (!DoshokuOrder.getInstance().isModifyOrder()) {
            //通知更新餐台状态
            EventBus.getDefault().post(new InitTableEvent(tableInfo.getId(), tableInfo.getTableNumber()), "initTable_status_event");
        }

        //開錢箱
        boolean openInstruction = false;
        List<PayMethod> payMethods = gsaPayView.getBillMoneyList();
        for (PayMethod payMethod : payMethods) {
            if (payMethod.getWhetherOpenBox() == 1) {
                openInstruction = true;
                break;
            }
        }
        if (openInstruction) {
            printOpenInstructionAndBill();
        } else {
            printBill();
        }
    }

    private void printOpenInstructionAndBill() {
        showLoading(null);
        CC.obtainBuilder(ComponentName.COMPONENT_PRINT)
                .setActionName("printActivity")
                .addParam(PrintConstans.PRINT_TYPE, PrintConstans.PRINT_INSTRUCTION)
                .build()
                .callAsyncCallbackOnMainThread(new IComponentCallback() {
                    @Override
                    public void onResult(CC cc, CCResult result) {
                        LoganManager.w_code(TAG, "printOpenInstructionAndBill " + "是否成功：" + result.isSuccess());
                        mAppManager.killActivity("PrintActivity");
                    }
                });
        printBill();
    }

    private void printBill() {
        //打印結賬單
        PrintContent printContent = new PrintContentAdapter().adaptationBillContent(DoshokuOrder.getInstance(), DoshokuOrder.getInstance().getOpenTableInfo());
        CC.obtainBuilder(ComponentName.COMPONENT_PRINT)
                .setActionName("printActivity")
                .addParam(PrintConstans.PRINT_TYPE, PrintConstans.PRINT_BILL)
                .addParam(PrintConstans.PRINT_CONTENT, printContent)
                .build()
                .callAsyncCallbackOnMainThread(new IComponentCallback() {
                    @Override
                    public void onResult(CC cc, CCResult result) {
                        hideLoading();
                        LoganManager.w_code(TAG, "printBill " + "是否成功打印：" + result.isSuccess());
                        mAppManager.killActivity("PrintActivity");
                        mAppManager.killActivity(MealStandActivity.class);
                        mAppManager.killActivity(OrderContentActivity.class);
                        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("     " + (gsaPayView.getLinePayType() == 1 ? "找零" : "貼士"));
            payMethod.setPayMoney(mPresenter.getTipsPrice());
            billMoneyList.add(payMethod);
        }
        DoshokuOrder.getInstance().setBillMoney(billMoneyList);
    }

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

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

            mPresenter.setBillMoneyList(mBillMoneyList);

            if (AppDevices.isHywebPos()) {

                int hywebPayMethodIndex = PayMethodUtils.hasHywebPayMethod(mBillMoneyList);

                if (hywebPayMethodIndex != -1) {
                    PayMethod hywebPayMethod = mBillMoneyList.get(hywebPayMethodIndex);

                    SaleRequest saleRequest = new SaleRequest();
                    if (hywebPayMethod.getPayType() == PayTypeContract.PAY_METHOD_ID_1030) {
                        //卡片支付
                        saleRequest.setPAYMENT_APP_ID(PayMethodConstant.PAY_TYPE_CC);
                    } else {
                        //掃碼支付
                        saleRequest.setPAYMENT_APP_ID(PayMethodConstant.PAY_TYPE_QRC);
                    }
                    saleRequest.setTXN_AMT(DoshokuOrder.getInstance().getShoppingCart().getTotalAmount());
                    saleRequest.setTIPS(0);

                    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.setPayMethodId(hywebPayMethod.getId());
                    txnIdRequest.setAmount(hywebPayMethod.getPayMoney());

                    MealOrderPayRequest orderPayRequest = mPresenter.getOrderPayRequest(gsaPayView);
                    List<BillItem> billItemList = DoshokuOrder.getInstance().getShoppingCart().getBillItemList();

                    PosPay.pay(mContext, OrderPayActivity.this, saleRequest, txnIdRequest, DoshokuOrder.getInstance().getOpenTableInfo(), orderPayRequest, billItemList, mBillMoneyList, new OnPosActionListener<SaleRespose>() {

                        @Override
                        public void onPosSuccess(SaleRespose response) {

                        }

                        @Override
                        public void onPosException(Exception e) {

                        }

                        @Override
                        public void onPosInvalid(String e) {

                        }

                        @Override
                        public void onUpdateStatusSuccess(SaleRespose response) {
                            if (HywebActionStatusCode.withSuccess(response.getSTATUS())) {
                                paySuccess();
                            }
                        }

                        @Override
                        public void onUpdateStatusError(Throwable e) {

                        }
                    });
                } else {
                    mPresenter.sendOrderBefore();
                }
            } else {
                mPresenter.sendOrderBefore();
            }
        });
    }

    @Override
    public void onPointerCaptureChanged(boolean hasCapture) {

    }

    public OrderPayView getGsaPayView() {
        return gsaPayView;
    }


}
