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

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.Window;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

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.restaurant.RestaurantInfoManager;
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.LanguageUtils;
import com.gingersoft.gsa.cloud.component.ComponentAction;
import com.gingersoft.gsa.cloud.component.ComponentName;
import com.gingersoft.gsa.cloud.order.bean.event.MealPayResultParam;
import com.gingersoft.gsa.cloud.order.bean.request.MealOrderPayRequest;
import com.gingersoft.gsa.cloud.order.billItem.BillItem;
import com.gingersoft.gsa.cloud.order.order.MealOrder;
import com.gingersoft.gsa.cloud.pay.PayAction;
import com.gingersoft.gsa.cloud.pay.PaymentCommand;
import com.gingersoft.gsa.cloud.pay.RequestParms;
import com.gingersoft.gsa.cloud.pay.ResultCallback;
import com.gingersoft.gsa.cloud.pay.bean.PayMethod;
import com.gingersoft.gsa.cloud.pay.device.pos.hyweb.bean.response.pos.HywebPosResponse;
import com.gingersoft.gsa.cloud.pay.device.pos.hyweb.bean.response.pos.SaleRespose;
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.DaggerMealPayComponent;
import com.gingersoft.gsa.cloud.table.mvp.contract.MealPayContract;
import com.gingersoft.gsa.cloud.table.mvp.model.bean.event.InitTableEvent;
import com.gingersoft.gsa.cloud.table.mvp.presenter.mealstand.MealPayPresenter;
import com.gingersoft.gsa.cloud.ui.view.OrderPayView;
import com.gyf.immersionbar.ImmersionBar;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.integration.AppManager;
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 org.simple.eventbus.EventBus;

import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.OnClick;
import butterknife.OnLongClick;
import io.reactivex.functions.Consumer;


/**
 * ================================================
 * 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 MealPayActivity extends BaseMealActivity<MealPayPresenter> implements MealPayContract.View, View.OnLongClickListener, Window.Callback {

    @Inject
    AppManager mAppManager;

    @BindView(R2.id.tv_action_name)
    TextView tvActionName;
    @BindView(R2.id.tv_server_main)
    TextView tvServerMain;
    @BindView(R2.id.tv_time)
    TextView tvTime;
    @BindView(R2.id.btn_people_num)
    QMUIAlphaButton btnPeopleNum;
    @BindView(R2.id.tv_member_info)
    TextView tvMemberInfo;
    @BindView(R2.id.tv_whole)
    TextView tvWhole;
    @BindView(R2.id.gsa_pay_view)
    OrderPayView gsaPayView;

    /**
     * 會員積分數
     */
    private double memberIntegral = 0;
    /**
     * 積分兌換現金比例（MemberPointRedeemCash=2 （理解為每2分=1元）
     */
    private double memberPointRedeemCash = 0;

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

    @Override
    public void configImmersionBar(ImmersionBar immersionBar) {
        immersionBar.fitsSystemWindows(true).statusBarColor("#0E655F").init();
    }

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

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        super.initData(savedInstanceState);

        mPresenter.initAdapter();
        mPresenter.getPayMethods();
        initOrderPayView();
        initTopInfo();
        initOrderDetail();
        initMemberInfo();
    }

    private void initOrderPayView() {
        gsaPayView.setOnSelectPayClickLisenter(new OrderPayView.OnSelectPayClickLisenter() {
            @Override
            public void addClick(PayMethod method) {
                LoganManager.w_pay(TAG, LoganManager.EVENT_ADD, "支付方式=" + method.getPayName());
                if (method.getPayType() == PayMethod.PAY_TYPE_INTEGRAL) {
                    setMemberInfo();
                }
            }

            @Override
            public void delClick(PayMethod method) {
                LoganManager.w_pay(TAG, LoganManager.EVENT_DELETE, "支付方式=" + method.getPayName());
                if (method.getPayType() == PayMethod.PAY_TYPE_INTEGRAL) {
                    setMemberInfo();
                }
            }

            @Override
            public void updateIntegralInfo() {
                setMemberInfo();
            }
        });
        gsaPayView.setOnFreeServiceStatusChangeLisenter(isUseFreeServicePayMethod -> {
            LoganManager.w_pay(TAG, "是否選中免服務費支付方式=" + isUseFreeServicePayMethod);
            mPresenter.setFreeServiceStauts(isUseFreeServicePayMethod);
        });
        gsaPayView.setServiceCharge(mPresenter.getShoppingCart().getServiceCharge());
    }

    private void initTopInfo() {

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

        Date dd = MealOrder.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();
        }
        btnTable.setText(tableno);
        tvTime.setText("時間:" + openTime);
        btnPeopleNum.setText(tableInfo.getPerson() + "");
        tvServerMain.setText(UserContext.newInstance().getMemberName());
        tvActionName.setBackgroundColor(Color.parseColor("#C50000"));
        tvActionName.setText("結賬");
    }

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

        LoganManager.w_pay(TAG, "合計金額=" + wholeAmount);

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

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

    public void setMemberInfo() {
        tvMemberInfo.setText(getMemberInfo());
    }

    private String getMemberInfo() {
        MemberInfo memberBean = MealOrder.getInstance().getMemberInfo();
        String memberInfo = "";
        if (memberBean != null) {
            String memberName = memberBean.getMemberName();
            String LevelName1 = memberBean.getLevelName1();
            memberInfo = LanguageUtils.get_language_system("meal.info.member.name", "會員:") + memberName;
            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) {
        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 onBackPressedSupport() {
        super.onBackPressedSupport();
        backPressed();
    }

    @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 paySuccess() {
        //修改結賬方式數據
        setBillMoney();

        TableBean.DataBean tableInfo = MealOrder.getInstance().getOpenTableInfo();
        if (!MealOrder.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)
                .addParam(PrintConstans.PRINT_ORDER_NO, MealOrder.getInstance().getOrderNo())
                .build()
                .callAsyncCallbackOnMainThread(new IComponentCallback() {
                    @Override
                    public void onResult(CC cc, CCResult result) {
                        LoganManager.w_pay(TAG, "開錢箱結果：" + result.isSuccess());
                        mAppManager.killActivity("PrintActivity");
                    }
                });
        RxJavaUtils.delay(1, TimeUnit.SECONDS)
                .subscribe(new Consumer<Long>() {

                    @Override
                    public void accept(Long aLong) throws Exception {
                        printBill();
                    }
                });
    }

    private void printBill() {
        if (AppDevices.isHywebPos()) {
            printEndBack();
        } else {
            //打印結賬單
            PrintContent printContent = new PrintContentAdapter().adaptationBillContent(MealOrder.getInstance(), MealOrder.getInstance().getOpenTableInfo());
            CC.obtainBuilder(ComponentName.COMPONENT_PRINT)
                    .setActionName("printActivity")
                    .addParam(PrintConstans.PRINT_TYPE, PrintConstans.PRINT_BILL)
                    .addParam(PrintConstans.PRINT_CONTENT, printContent)
                    .addParam(PrintConstans.PRINT_ORDER_NO, MealOrder.getInstance().getOrderNo())
                    .build()
                    .callAsyncCallbackOnMainThread(new IComponentCallback() {
                        @Override
                        public void onResult(CC cc, CCResult result) {
                            LoganManager.w_pay(TAG, "結賬單打印結果：" + result.isSuccess());
                            printEndBack();
                        }
                    });
        }
    }

    private void printEndBack() {
        hideLoading();
        mAppManager.killActivity("PrintActivity");
        mAppManager.killActivity(MealStandActivity.class);
        mAppManager.killActivity(MealBillActivity.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);
        }
        MealOrder.getInstance().setBillMoney(billMoneyList);
    }

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

            mPresenter.setBillMoneyList(mBillMoneyList);

            int hasYedpayMethodIndex = PayMethodUtils.hasYedpayMethod(mBillMoneyList);

            if (hasYedpayMethodIndex != -1) {

//                int hywebPayMethodIndex = PayMethodUtils.hasHywebPayMethod(mBillMoneyList);

                if (hasYedpayMethodIndex != -1) {
                    PayMethod payMethod = mBillMoneyList.get(hasYedpayMethodIndex);
//                    PayMethod hywebPayMethod = mBillMoneyList.get(hasYedpayMethodIndex);
//                    SaleRequest saleRequest = new SaleRequest();
//                    switch (hywebPayMethod.getPayType()) {
//                        case PayMethodContract.PAY_METHOD_ID_1030:
//                            saleRequest.setPAYMENT_APP_ID(HywebMethodConstant.PAY_TYPE_CC);
//                            break;
//                        case PayMethodContract.PAY_METHOD_ID_1031:
//                            saleRequest.setPAYMENT_APP_ID(HywebMethodConstant.PAY_TYPE_QRC);
//                            break;
//                        case PayMethodContract.PAY_METHOD_ID_1032:
//                            saleRequest.setPAYMENT_APP_ID(HywebMethodConstant.PAY_TYPE_OPS);
//                            break;
//                        case PayMethodContract.PAY_METHOD_ID_1033:
//                            saleRequest.setPAYMENT_APP_ID(HywebMethodConstant.PAY_TYPE_AE);
//                            break;
//                        default:
//                            break;
//                    }
//                    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);
//                    txnIdRequest.setContent(GsonUtils.GsonString(orderPayRequest));
//
//                    List<BillItem> billItemList = DoshokuOrder.getInstance().getShoppingCart().getBillItemList();

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

                    RequestParms parms = RequestParms.builder()
                            .action(PayAction.SALE)
                            .orderId(MealOrder.getInstance().getOrderId())
                            .resturantId(RestaurantInfoManager.newInstance().getRestaurantId())
                            .tableId(tableInfo.getId())
                            .tableExtId(tableInfo.getTableNumber())
                            .payMethods(mBillMoneyList)
                            .payType(payMethod.getPayType())
                            .payMoney(payMethod.getPayMoney())
                            .resultCallback(new ResultCallback() {

                                @Override
                                public void onSuccess() {
                                    paySuccess();
                                }

                                @Override
                                public void onFailure(Throwable t) {

                                }

                                @Override
                                public void fakePayment() {
                                    mPresenter.sendOrderBefore();
                                }

                                @Override
                                public void hybridPayment(List<PayMethod> payMethods) {

                                }
                            })
                            .build();
                    PaymentCommand.newInstance().action(getSupportFragmentManager(), parms);

//                    PosPay.builder()
//                            .context(GsaCloudApplication.getAppContext())
//                            .lifecycleView(OrderPayActivity.this)
//                            .payType(hywebPayMethod.getPayType())
//                            .payMoney(hywebPayMethod.getPayMoney())
//                            .posRequest(saleRequest)
//                            .bgRequest(txnIdRequest)
//                            .callback(new PosCallbackListener<SaleRespose>() {
//                                @Override
//                                public void onPosSuccess(SaleRespose response) {
//                                    startPaymentDetailActivity(saleRequest.getTXN_ID(), DoshokuOrder.getInstance().getOpenTableInfo(), orderPayRequest, billItemList, payMethods, response);
//                                }
//
//                                @Override
//                                public void onPosException(SaleRespose response, Exception e) {
//                                    startPaymentDetailActivity(saleRequest.getTXN_ID(), DoshokuOrder.getInstance().getOpenTableInfo(), orderPayRequest, billItemList, payMethods, response);
//                                }
//
//                                @Override
//                                public void onPosInvalid(String e) {
//
//                                }
//
//                                @Override
//                                public void onUpdateStatusSuccess(SaleRespose response) {
//                                    if (HywebActionStatusCode.withSuccess(response.getSTATUS())) {
//                                        paySuccess();
//                                    }
//                                }
//
//                                @Override
//                                public void onUpdateStatusError(Throwable e) {
//
//                                }
//                            })
//                            .yedpayCallback((intent) -> {
//                                startActivityForResult(intent, PayConstans.YEDPAY_START_RESULT_CODE);
//                            })
//                            .build()
//                            .pay();
                } else {
                    mPresenter.sendOrderBefore();
                }
            } else {
                mPresenter.sendOrderBefore();
            }
        });
    }

    private void startPaymentDetailActivity(String txnId, TableBean.DataBean tableBean, MealOrderPayRequest orderPayRequest, List<BillItem> billItemList,
                                            List<PayMethod> payMethodList, HywebPosResponse response) {
        MealPayResultParam payResultParam = new MealPayResultParam();
        payResultParam.setTxnId(txnId);
        payResultParam.setTableBean(tableBean);
        payResultParam.setMealOrderPayRequest(orderPayRequest);
        payResultParam.setBillItemList(billItemList);
        payResultParam.setPayMethodList(payMethodList);
        payResultParam.setSaleRespose((SaleRespose) response);

        //等待Dialog動畫加載完再跳轉支付結果頁面
        RxJavaUtils.delay(2, TimeUnit.SECONDS)
                .subscribe(new Consumer<Long>() {
                    @Override
                    public void accept(Long aLong) throws Exception {
                        //kill orderPayActivity,orderContentActivity,mealActivity
                        CC.obtainBuilder(ComponentName.COMPONENT_TABLE)
                                .setActionName(ComponentAction.Table.KILL_MEAL_ORDER_PAY)
                                .build()
                                .call();
                        CC.obtainBuilder(ComponentName.COMPONENT_PAY)
                                .setActionName(ComponentAction.Pay.OPEN_PAY_RESULT)
                                .addParam("payResultParam", payResultParam)
                                .build()
                                .call();
                    }
                });
    }

    @Override
    public void onPointerCaptureChanged(boolean hasCapture) {
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        LoganManager.w_code(TAG, "onActivityResult->" + "resultCode=" + resultCode + "  requestCode=" + requestCode);
    }

    public OrderPayView getGsaPayView() {
        return gsaPayView;
    }

}
