package com.gingersoft.supply_chain.mvp.ui.adapter;

import android.content.Context;
import android.view.View;
import android.widget.CheckBox;
import android.widget.TextView;

import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.gingersoft.gsa.cloud.common.utils.MoneyUtil;
import com.gingersoft.gsa.cloud.ui.recylcler.decorator.DividerItemDecoration;
import com.gingersoft.gsa.cloud.ui.utils.AppDialog;
import com.gingersoft.supply_chain.R;
import com.gingersoft.supply_chain.mvp.bean.PurchaseFoodBean;

import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

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

import static com.gingersoft.supply_chain.mvp.ui.fragment.food.FoodIngredientsFragment.ORDER_TYPE;

/**
 * @author 宇航.
 * User: admin
 * Date: 2020/12/3
 * Time: 18:11
 * Use:
 */
public class ShoppingCartAdapter extends BaseQuickAdapter<List<PurchaseFoodBean>, BaseViewHolder> {
    private Context context;
    private List<PurchaseFoodBean> selectFoods;

    public ShoppingCartAdapter(Context context, @Nullable List<List<PurchaseFoodBean>> data) {
        super(R.layout.item_shopping_cart, data);
        this.context = context;
        selectFoods = new ArrayList<>();
        addChecked(data);
    }

    /**
     * 將集合中已選中的食品添加到 用於操作的集合中
     *
     * @param data
     */
    public void addChecked(@Nullable List<List<PurchaseFoodBean>> data) {
        if (data != null) {
            selectFoods.clear();
            for (List<PurchaseFoodBean> datum : data) {
                for (PurchaseFoodBean purchaseFoodBean : datum) {
                    if (purchaseFoodBean.isChecked()) {
                        selectFoods.add(purchaseFoodBean);
                    }
                }
            }
        }
    }

    @Override
    protected void convert(@NotNull BaseViewHolder viewHolder, List<PurchaseFoodBean> purchaseFoodBeans) {
        RecyclerView rvFoods = viewHolder.getView(R.id.rv_shopping_cart_food);
        if (purchaseFoodBeans != null && purchaseFoodBeans.size() > 0) {
            //先判斷是否滿足最低採購金額
            double minimumAmount = purchaseFoodBeans.get(0).getMinimumAmount();
            double totalAmount = getTotalAmount(purchaseFoodBeans);
            if (MoneyUtil.compareTo(totalAmount, minimumAmount) < 0) {
                //小於最低採購金額
                viewHolder.setText(R.id.tv_minimumAmount, String.format(context.getString(R.string.minimumAmount), minimumAmount));
            } else {
                viewHolder.setText(R.id.tv_minimumAmount, purchaseFoodBeans.get(0).getAddress());
            }
            TextView tvPrice = viewHolder.getView(R.id.tv_order_item_total_amount);
            TextView tvFoodTypeNumber = viewHolder.getView(R.id.tv_order_item_food_type_total);

            FoodListAdapter foodListAdapter = new FoodListAdapter(R.layout.item_shopping_cart_food, context, purchaseFoodBeans, ORDER_TYPE);
            foodListAdapter.setOnItemChildClickListener((adapter, view, position) -> {
                if (view.getId() == R.id.iv_order_food_delete) {
                    new AppDialog().showWaringDialog(context, "是否刪除食品？", (v, dialog) -> {
                        dialog.dismiss();
                        if (onFoodDeleteListener != null) {
                            onFoodDeleteListener.onDeleteFood(viewHolder.getAdapterPosition(), purchaseFoodBeans.get(position));
                        }
                    });
                }
            });
            Map<Integer, PurchaseFoodBean> integerMap = foodListAdapter.getIntegerMap();
            for (PurchaseFoodBean purchaseFoodBean : purchaseFoodBeans) {
                integerMap.put(purchaseFoodBean.getId(), purchaseFoodBean);
            }
            rvFoods.addItemDecoration(new DividerItemDecoration(context, DividerItemDecoration.VERTICAL_LIST));
            rvFoods.setAdapter(foodListAdapter);

            CheckBox cbAllSelect = viewHolder.getView(R.id.cb_order_item_all_select);
            cbAllSelect.setText(purchaseFoodBeans.get(0).getSupplierName());
            //全選按鈕的事件監聽
            allSelectListener(foodListAdapter, tvPrice, tvFoodTypeNumber, cbAllSelect);

            //單個食品的數量修改
            foodListAdapter.setOnNumberChangeListener((foodId, number, position) -> {
                if (number <= 0) {
                    for (PurchaseFoodBean purchaseFoodBean : purchaseFoodBeans) {
                        if (purchaseFoodBean.getId() == foodId) {
                            new AppDialog().showWaringDialog(context, "數量小於1時將會刪除，是否刪除？", (view, dialog) -> {
                                dialog.dismiss();
                                if (onFoodDeleteListener != null && position < purchaseFoodBeans.size()) {
                                    onFoodDeleteListener.onDeleteFood(viewHolder.getAdapterPosition(), purchaseFoodBeans.get(position));
                                }
                            }, (view, dialog) -> {
                                //取消，設置數量為1
                                dialog.dismiss();
                                purchaseFoodBean.setFoodQuantity(1);
                                foodListAdapter.getIntegerMap().put(purchaseFoodBean.getId(), purchaseFoodBean);
                                foodListAdapter.notifyItemChanged(position);
                            });
                            break;
                        }
                    }
                } else {
                    //當數量發生改變時，重新計算價格。
                    calculateTotalPrice(purchaseFoodBeans, tvPrice, tvFoodTypeNumber, cbAllSelect);
                }
            });
            //單個食品選中狀態切換
            foodListAdapter.setOnCheckedChangeListener((isChecked, purchaseFoodListVosBean) -> {
                foodCheckedChanged(isChecked, purchaseFoodListVosBean);
                calculateTotalPrice(foodListAdapter.getData(), tvPrice, tvFoodTypeNumber, cbAllSelect);
            });
            //計算總價，類型數量
            calculateTotalPrice(purchaseFoodBeans, tvPrice, tvFoodTypeNumber, cbAllSelect);
            rvFoods.setVisibility(View.VISIBLE);
        } else {
            viewHolder.setText(R.id.tv_order_item_food_type_total, String.valueOf(0));
            viewHolder.setText(R.id.tv_order_item_total_amount, "$0");
            viewHolder.setText(R.id.cb_order_item_all_select, "");
            rvFoods.setVisibility(View.GONE);
        }
    }

    private OnInfoChangeListener onInfoChangeListener;
    private OnFoodDeleteListener onFoodDeleteListener;

    public interface OnInfoChangeListener {
        /**
         * 當選中或者數量發生變化時，通知外部修改
         */
        void onInfoChange();
    }

    public void setOnInfoChangeListener(OnInfoChangeListener onInfoChangeListener) {
        this.onInfoChangeListener = onInfoChangeListener;
    }

    public interface OnFoodDeleteListener {
        void onDeleteFood(int supplierIndex, PurchaseFoodBean foodListVosBean);
    }

    public void setOnFoodDeleteListener(OnFoodDeleteListener onFoodDeleteListener) {
        this.onFoodDeleteListener = onFoodDeleteListener;
    }

    /**
     * 食品的選中狀態發生改變
     *
     * @param isChecked               是否選中
     * @param purchaseFoodBean 所修改的食品
     */
    private void foodCheckedChanged(boolean isChecked, PurchaseFoodBean purchaseFoodBean) {
        purchaseFoodBean.setChecked(isChecked);
        if (isChecked) {
            //添加到已選中食品的集合中，下單時候用
            if (!selectFoods.contains(purchaseFoodBean)) {
                selectFoods.add(purchaseFoodBean);
            }
        } else {
            selectFoods.remove(purchaseFoodBean);
        }
    }

    /**
     * 全選按鈕的狀態切換
     *
     * @param foodListAdapter 顯示所有食品的adapter
     * @param cbAllSelect     複選框
     */
    private void allSelectListener(FoodListAdapter foodListAdapter, TextView tvPrice, TextView tvNumber, CheckBox cbAllSelect) {
        //全選
        cbAllSelect.setOnCheckedChangeListener((buttonView, isChecked) -> {
            if (buttonView.isPressed()) {
                for (PurchaseFoodBean purchaseFoodBean : foodListAdapter.getData()) {
                    if (!selectFoods.contains(purchaseFoodBean)) {
                        selectFoods.add(purchaseFoodBean);
                    }
                    purchaseFoodBean.setChecked(isChecked);
                }
                calculateTotalPrice(foodListAdapter.getData(), tvPrice, tvNumber, cbAllSelect);
                foodListAdapter.notifyDataSetChanged();
            }
        });
    }

    /**
     * 計算出已選中食品的總價
     *
     * @param purchaseFoodBeans 所有食品
     * @param tvPrice                  顯示價格的textview
     * @param tvNumber                 顯示數量的textview
     */
    public void calculateTotalPrice(List<PurchaseFoodBean> purchaseFoodBeans, TextView tvPrice, TextView tvNumber, CheckBox cbAllSelect) {
        double totalAmount = 0;
        int totalTypeFood = 0;
        for (PurchaseFoodBean purchaseFoodBean : purchaseFoodBeans) {
            if (purchaseFoodBean.isChecked()) {
                totalTypeFood++;
                totalAmount = MoneyUtil.sum(totalAmount, MoneyUtil.priceCalculation(purchaseFoodBean.getUnitPrice(), purchaseFoodBean.getFoodQuantity()));
            }
        }
        tvPrice.setText("$" + totalAmount);
        tvNumber.setText(String.valueOf(totalTypeFood));
        cbAllSelect.setChecked(totalTypeFood == purchaseFoodBeans.size());
        if (onInfoChangeListener != null) {
            onInfoChangeListener.onInfoChange();
        }
    }

    /**
     * 獲取所有食品的總金額
     *
     * @param purchaseFoodBeans
     * @return
     */
    private double getTotalAmount(List<PurchaseFoodBean> purchaseFoodBeans) {
        double totalAmount = 0;
        for (PurchaseFoodBean purchaseFoodBean : purchaseFoodBeans) {
            totalAmount = MoneyUtil.sum(totalAmount, MoneyUtil.priceCalculation(purchaseFoodBean.getUnitPrice(), purchaseFoodBean.getFoodQuantity()));
        }
        return totalAmount;
    }

    public List<PurchaseFoodBean> getPurchaseFoodListVosBeans() {
        return selectFoods;
    }
}
