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.core.content.ContextCompat;
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.PurchaseFoodListVosBean;

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<PurchaseFoodListVosBean>, BaseViewHolder> {
    private Context context;
    private List<PurchaseFoodListVosBean> selectFoods;

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

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

    @Override
    protected void convert(@NotNull BaseViewHolder viewHolder, List<PurchaseFoodListVosBean> purchaseFoodListVosBeans) {
        RecyclerView rvFoods = viewHolder.getView(R.id.rv_shopping_cart_food);
        if (purchaseFoodListVosBeans != null && purchaseFoodListVosBeans.size() > 0) {
            //先判斷是否滿足最低採購金額
            double minimumAmount = purchaseFoodListVosBeans.get(0).getMinimumAmount();
            double totalAmount = getTotalAmount(purchaseFoodListVosBeans);
            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, purchaseFoodListVosBeans.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, purchaseFoodListVosBeans, 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(), purchaseFoodListVosBeans.get(position));
                        }
                    });
                }
            });
            Map<Integer, PurchaseFoodListVosBean> integerMap = foodListAdapter.getIntegerMap();
            for (PurchaseFoodListVosBean purchaseFoodListVosBean : purchaseFoodListVosBeans) {
                integerMap.put(purchaseFoodListVosBean.getId(), purchaseFoodListVosBean);
            }
            rvFoods.addItemDecoration(new DividerItemDecoration(context, DividerItemDecoration.VERTICAL_LIST));
            rvFoods.setAdapter(foodListAdapter);

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

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

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

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

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

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

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

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