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

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.billy.cc.core.component.CC;
import com.gingersoft.gsa.cloud.base.common.bean.mealManage.MyOrderManage;
import com.gingersoft.gsa.cloud.base.common.bean.mealManage.OpenTableContract;
import com.gingersoft.gsa.cloud.base.utils.MoneyUtil;
import com.gingersoft.gsa.cloud.base.utils.PrintUtils;
import com.gingersoft.gsa.cloud.base.utils.VibratorUtils;
import com.gingersoft.gsa.cloud.base.utils.toast.ToastUtils;
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.di.component.DaggerOrderPayComponent;
import com.gingersoft.gsa.cloud.table.mvp.contract.OrderPayContract;
import com.gingersoft.gsa.cloud.base.common.bean.BillMethodBean;
import com.gingersoft.gsa.cloud.table.mvp.presenter.OrderPayPresenter;
import com.gingersoft.gsa.cloud.table.mvp.ui.adapter.BillMethodAdapter;
import com.gingersoft.gsa.cloud.table.mvp.ui.adapter.BillMoneyAdapter;
import com.gingersoft.gsa.cloud.ui.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.utils.ArmsUtils;
import com.qmuiteam.qmui.alpha.QMUIAlphaButton;
import com.qmuiteam.qmui.util.QMUIDisplayHelper;

import org.simple.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
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 {


    @BindView(R2.id.btn_table)
    QMUIAlphaButton btn_table;
    @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.rv_food)
    RecyclerView rv_food;

    @BindView(R2.id.tv_whole)
    TextView tv_whole;
    @BindView(R2.id.tv_total)
    TextView tv_total;
    @BindView(R2.id.tv_owe_money)
    TextView mTvOwnMoney;
    @BindView(R2.id.btn_order_count)
    Button btn_order_count;
    @BindView(R2.id.rv_select_pay)
    RecyclerView rvSelectedPay;
    @BindView(R2.id.rv_pay)
    RecyclerView rvPay;
    @BindView(R2.id.btn_exact)
    QMUIAlphaButton btn_exact;
    @BindView(R2.id.btn_keypad)
    QMUIAlphaButton btn_keypad;

    //尚欠金額
    private double ownMoney;

    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
    public int initView(@Nullable Bundle savedInstanceState) {
        return R.layout.activity_order_pay; //如果你不需要框架帮你设置 setContentView(id) 需要自行设置,请返回 0
    }

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

        QMUIDisplayHelper.cancelFullScreen(this);
        mPresenter.initAdapter();
        initOrderDetail();
        initBillMethod();
    }

    public void initOrderDetail() {

        int foodCount = mPresenter.getFoodCout();
        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.getTotal();
        tv_whole.setText("合計 $" + total);
        tv_total.setText("$" + total);
        ownMoney = total;
        setOwnMoney(ownMoney);
        //        setTvWhole(total);
//        setTvTotal(total);
    }

    /**
     * @param money 尚欠金額
     */
    private void setOwnMoney(double money) {
        if (money != 0) {
            mTvOwnMoney.setText("-$" + money);
        } else {
            mTvOwnMoney.setText("$" + money);
        }
    }

    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_pay, 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_pay) {

        } else if (id == R.id.btn_table) {
            killMyself();
        } else if (id == R.id.btn_sure_pay) {
            //確認結賬，修改訂單狀態為已結賬
            if (ownMoney <= 0) {
                mPresenter.updateOrderState("4");
            } else {
                ToastUtils.show(mContext, "尚欠" + ownMoney + "未選擇支付方式");
            }
        } else if (id == R.id.btn_exact) {
            if (billMoney.size() > 0) {
                billMoney.get(billMoney.size() - 1).setMoney(ownMoney);
                ownMoney = 0;
                billMoneyAdapter.notifyDataSetChanged();
                setOwnMoney(MoneyUtil.sub(mPresenter.getTotal(), billMoney.get(billMoney.size() - 1).getMoney()));
            }
        } else if (id == R.id.btn_keypad) {
            //顯示鍵盤

        }
    }

    @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);
        ToastUtils.show(mContext, message);
//        ArmsUtils.snackbarText(message);
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {
        finish();
    }

    @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(billMoney);
        if (OpenTableContract.getDefault() != null) {
            //通知更新餐台状态
            EventBus.getDefault().post(OpenTableContract.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();
    }
}
