package com.gingersoft.gsa.cloud.ui.view;

import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.gingersoft.gsa.cloud.base.R;
import com.gingersoft.gsa.cloud.base.common.bean.PayMethod;
import com.gingersoft.gsa.cloud.base.utils.MoneyUtil;
import com.gingersoft.gsa.cloud.base.utils.VibratorUtils;
import com.gingersoft.gsa.cloud.base.utils.toast.ToastUtils;
import com.gingersoft.gsa.cloud.ui.adapter.BillMethodAdapter;
import com.gingersoft.gsa.cloud.ui.adapter.BillMoneyAdapter;
import com.gingersoft.gsa.cloud.ui.recylcler.decorator.GridDividerItemDecoration;
import com.jess.arms.utils.ArmsUtils;
import com.qmuiteam.qmui.util.QMUIDisplayHelper;
import com.qmuiteam.qmui.widget.dialog.QMUITipDialog;

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

public class OrderPayView extends LinearLayout {

    private double totalAmount;
    private List<PayMethod> mBillMoneyList;//用戶已選中的支付方式
    private BillMoneyAdapter mBillMoneyAdapter;
    private BillMethodAdapter mBillMethodAdapter;
    private int foodCount;
    private OnSureClickLisenter mOnSureClickLisenter;

    private TextView tvDifferenceName;
    private TextView tvDifferenceMoney;
    private TextView btn_order_count;
    private TextView tv_total;

    public OrderPayView(Context context) {
        this(context, null);
    }

    public OrderPayView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public OrderPayView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    public void loadInfo(Context context, List<PayMethod> mBillMethodList, double totalAmount, int foodCount) {
        this.totalAmount = totalAmount;
        this.mBillMoneyList = new ArrayList<>();
        this.foodCount = foodCount;
        init(context, mBillMethodList);
    }

    public void init(Context context, List<PayMethod> mBillMethodList) {
        View view = LayoutInflater.from(context).inflate(R.layout.layout_order_pay, null);

        MaxHeightRecyclerView rv_bill_money = view.findViewById(R.id.rv_bill_money);
        mBillMoneyAdapter = new BillMoneyAdapter(mBillMoneyList);
        rv_bill_money.setAdapter(mBillMoneyAdapter);

        tvDifferenceName = view.findViewById(R.id.tv_difference_name);
        tvDifferenceMoney = view.findViewById(R.id.tv_difference_money);
        btn_order_count = view.findViewById(R.id.btn_order_count);
        tv_total = view.findViewById(R.id.tv_total);
        initOrderDetail();
        setDifferenceText(context);

        MaxHeightRecyclerView rv_bill_method = view.findViewById(R.id.rv_bill_method);

        mBillMethodAdapter = new BillMethodAdapter(mBillMethodList);
        mBillMethodAdapter.setOnItemClickListener((adapter, view1, position) -> {
            recordOperat(context);
            PayMethod method = (PayMethod) adapter.getItem(position);
//                if (!isCashPayMethod(method)) {
//                    PayMethod N5PayMethod = getSelectN5PayMethod();
//                    if (N5PayMethod != null) {
//                        //最多選擇2中支付方式（現金+其他）
//                        mBillMoneyList.remove(N5PayMethod);
//                        mBillMoneyAdapter.notifyDataSetChanged();
//                    }
//                }
            mBillMoneyList.clear();
//                if (!mBillMoneyList.contains(method)) {
            double differenceMoney = getDifferenceMoney();
            if (differenceMoney > -1) {
                //補足差額
                method.setPayMoney(differenceMoney);
            }
            //添加選中支付方式
            mBillMoneyList.add(method);
            mBillMoneyAdapter.setSelect_position(mBillMoneyList.size() - 1);
            mBillMoneyAdapter.notifyDataSetChanged();
            rv_bill_money.scrollToPosition(mBillMoneyList.size() - 1);
            //設置差額狀態
            setDifferenceText(context);
//                }
        });

        mBillMoneyAdapter.setOnItemClickListener(new BillMoneyAdapter.OnItemClickListener() {

            @Override
            public void onItemClick(PayMethod datasBean, int position) {
                recordOperat(context);
                mBillMoneyAdapter.setSelect_position(position);
                mBillMoneyAdapter.notifyDataSetChanged();
            }

            @Override
            public void onItemDeleteClick(PayMethod datasBean, int position) {
                recordOperat(context);
                //刪除當前付款方式
                mBillMoneyList.remove(position);
                mBillMoneyAdapter.setSelect_position(mBillMoneyList.size() - 1);
                mBillMoneyAdapter.notifyDataSetChanged();
                //設置差額狀態
                setDifferenceText(context);
            }
        });


        rv_bill_method.setAdapter(mBillMethodAdapter);
//        rv_bill_method.addItemDecoration(new GridDividerItemDecoration(QMUIDisplayHelper.dpToPx(1), ArmsUtils.getColor(context, R.color.theme_hint_color)));

        //Exact
        view.findViewById(R.id.btn_exact).setOnClickListener(v -> {
            if (getSelectBillMoney() == null) {
                ToastUtils.show(context, "請選擇支付方式");
                return;
            }
            pressExact();
            setDifferenceText(context);
        });

        //sure
        view.findViewById(R.id.btn_sure_pay).setOnClickListener(v -> {
            if (mBillMoneyList.size() == 0) {
                ToastUtils.show(context, "請選擇支付方式");
                return;
            }
            if (!canPay()) {
                tipMoneyInsufficient(context);
                return;
            }
            if (mOnSureClickLisenter != null) {
                mOnSureClickLisenter.onClick(mBillMoneyList);
            }

        });

        //Keypad
        view.findViewById(R.id.layout_keypad).setOnClickListener(v -> {
            if (getSelectBillMoney() == null) {
                ToastUtils.show(context, "請選擇支付方式");
                return;
            }
            showPayKeypadDialog(context);
        });
        this.addView(view);
    }

    public void notifyBillMethodAdapter(List<PayMethod> mBillMethodList) {
        if (mBillMethodAdapter != null)
            mBillMethodAdapter.setNewData(mBillMethodList);
    }

    private void recordOperat(Context context) {
        VibratorUtils.pressButtonSound(context);
    }

    private void tipMoneyInsufficient(Context context) {
        QMUITipDialog tipDialog = new QMUITipDialog.Builder(context)
                .setIconType(QMUITipDialog.Builder.ICON_TYPE_INFO)
                .setTipWord("金額不足!")
                .create();
        tipDialog.show();
        this.postDelayed(tipDialog::dismiss, 1500);
    }

    /**
     * Exact
     */
    public void pressExact() {
        double differenceMoney = getDifferenceMoney();
        PayMethod billMoneyBean = getSelectBillMoney();
        if (billMoneyBean != null && differenceMoney > 0) {
            billMoneyBean.setPayMoney(billMoneyBean.getPayMoney() + differenceMoney);
            mBillMoneyAdapter.notifyDataSetChanged();
        }
    }

    /**
     * 是否滿足支付條件
     *
     * @return
     */
    public boolean canPay() {
        double difference = getDifferenceMoney();
        if (difference <= 0) {
            return true;
        }
        return false;
    }

    /**
     * 獲取當前選中的支付方式
     *
     * @return
     */
    public PayMethod getSelectBillMoney() {
        for (int i = 0; i < mBillMoneyList.size(); i++) {
            if (i == mBillMoneyAdapter.getSelect_position())
                return mBillMoneyList.get(i);
        }
        return null;
    }

    /**
     * 獲取支付差額
     *
     * @return
     */
    public double getDifferenceMoney() {
        double differenceMoney = MoneyUtil.sub(totalAmount, getBillMoney());
        return MoneyUtil.get_ItemDecimals_money(differenceMoney);
    }


    /**
     * 獲取支付總額
     *
     * @return
     */
    private double getBillMoney() {
        double totalMoney = 0.0;
        for (PayMethod method : mBillMoneyList) {
            totalMoney = MoneyUtil.sum(totalMoney, method.getPayMoney());
        }
        return totalMoney;
    }

    public void showPayKeypadDialog(Context context) {
        PayMethod method = getSelectBillMoney();
        new PayKeypadDialog(context)
                .setPayMethod(method.getPayName())
                .builder()
                .setComfirmListener(money -> {
                    PayMethod billMoneyBean = getSelectBillMoney();
                    billMoneyBean.setPayMoney(Double.parseDouble(money));
                    mBillMoneyAdapter.notifyDataSetChanged();
                    setDifferenceText(context);
                })
                .show();
    }

    /**
     * 獲取超出的金額為找零還是貼士: linePayType 1 tipsPrice 为找零  2 tipsPrice为贴上
     * 現金，掃碼QR = 找零
     * 信用卡 = 貼士
     *
     * @return 第一階段默認為找零
     */
    public int getLinePayType() {
        return 1;
    }


    public void setDifferenceText(Context context) {
        double difference = getDifferenceMoney();
        if (difference < 0) {
            //貼士
            if (getLinePayType() == 1) {
                tvDifferenceName.setText("找零");
                tvDifferenceMoney.setTextColor(ArmsUtils.getColor(context, R.color.red));
            } else {
                tvDifferenceName.setText("貼士");
                tvDifferenceMoney.setTextColor(ArmsUtils.getColor(context, R.color.Grass_green));
            }
            tvDifferenceMoney.setText("$" + Math.abs(difference));
        } else {
            //尚欠
            tvDifferenceName.setText("尚欠金額");
            tvDifferenceMoney.setTextColor(ArmsUtils.getColor(context, R.color.red));
            if (difference == 0)
                tvDifferenceMoney.setText("$" + Math.abs(difference));
            else
                tvDifferenceMoney.setText("-$" + Math.abs(difference));
        }
    }

    public void initOrderDetail() {
        if (foodCount > 0) {
            btn_order_count.setText(String.valueOf(foodCount));
            btn_order_count.setVisibility(View.VISIBLE);
        } else {
            btn_order_count.setVisibility(View.INVISIBLE);
        }
        tv_total.setText("$" + totalAmount);
    }

    public interface OnSureClickLisenter {
        void onClick(List<PayMethod> mBillMoneyList);
    }

    public void setmOnSureClickLisenter(OnSureClickLisenter mOnSureClickLisenter) {
        this.mOnSureClickLisenter = mOnSureClickLisenter;
    }
}
