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

import android.animation.AnimatorSet;
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.AnimateUtils;
import com.gingersoft.gsa.cloud.ui.utils.AppDialog;
import com.gingersoft.supply_chain.R;
import com.gingersoft.supply_chain.mvp.bean.PurchaseFoodBean;
import com.gingersoft.supply_chain.mvp.bean.ShoppingCartBean;
import com.google.android.material.internal.ViewUtils;
import com.xuexiang.rxutil2.rxjava.RxJavaUtils;

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

import java.util.List;

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<ShoppingCartBean, BaseViewHolder> {
    private Context context;
    private DividerItemDecoration dividerItemDecoration;

    public ShoppingCartAdapter(Context context, @Nullable List<ShoppingCartBean> data) {
        super(R.layout.item_shopping_cart, data);
        this.context = context;
        dividerItemDecoration = new DividerItemDecoration(context, DividerItemDecoration.VERTICAL_LIST);
    }

    @Override
    protected void convert(@NotNull BaseViewHolder viewHolder, ShoppingCartBean shoppingCartBean) {
        RecyclerView rvFoods = viewHolder.getView(R.id.rv_shopping_cart_food);
        //先判斷是否滿足最低採購金額
        TextView tvMinMinimumAmount = viewHolder.getView(R.id.tv_minimumAmount);
        setTvMinimumAmount(shoppingCartBean, tvMinMinimumAmount, viewHolder.getView(R.id.rv_purchase_shopping_minimum_tip));
        //選中食品的總價
        TextView tvPrice = viewHolder.getView(R.id.tv_order_item_total_amount);
        tvPrice.setText(String.format(context.getString(R.string.amount_string), shoppingCartBean.getSelectFoodAmount()));
        //選中食品的種類
        TextView tvFoodTypeNumber = viewHolder.getView(R.id.tv_order_item_food_type_total);
        tvFoodTypeNumber.setText(String.valueOf(shoppingCartBean.getSelectSpeciesNum()));
        //供應商下的食品
        rvFoods.removeItemDecoration(dividerItemDecoration);
        FoodListAdapter foodListAdapter = new FoodListAdapter(R.layout.item_shopping_cart_food, context, shoppingCartBean.getFoodList(), ORDER_TYPE);
        rvFoods.addItemDecoration(dividerItemDecoration);
        rvFoods.setAdapter(foodListAdapter);
        //全選按鈕，顯示供應商名字
        CheckBox cbAllSelect = viewHolder.getView(R.id.cb_order_item_all_select);
        cbAllSelect.setText(shoppingCartBean.getSupplierName());
        //全選按鈕的事件監聽
        allSelectListener(foodListAdapter, shoppingCartBean, tvPrice, tvFoodTypeNumber, cbAllSelect);
        cbAllSelect.setChecked(shoppingCartBean.isAllSelect());
        //單個食品的數量修改
        foodListAdapter.setOnNumberChangeListener(((beforeNumber, number, position) -> {
            List<PurchaseFoodBean> foodList = getData().get(viewHolder.getLayoutPosition()).getFoodList();
            //拿到需要操作的食品信息
            PurchaseFoodBean purchaseFoodBean = foodList.get(position);
            if (number <= 0) {
                //如果數量小於等於0，需要詢問是否刪除
                //彈窗顯示 是否刪除
                new AppDialog().showWaringDialog(context, "是否刪除食品？", (view, dialog) -> {
                    dialog.dismiss();
                    boolean isDeleteSupplier = deleteFood(viewHolder.getAdapterPosition(), tvPrice, tvFoodTypeNumber, foodListAdapter, beforeNumber, position, purchaseFoodBean);
                    //如果這個供應商被刪除了，就不用判斷採購金額了
                    if (!isDeleteSupplier) {
                        //判斷當前總價是否滿足最低採購金額
                        setTvMinimumAmount(getData().get(viewHolder.getAdapterPosition()), tvMinMinimumAmount, viewHolder.getView(R.id.rv_purchase_shopping_minimum_tip));
                    }
                }, (view, dialog) -> {
                    //不刪除這個食品
                    dialog.dismiss();
                    if (purchaseFoodBean.getFoodQuantity() <= 0) {
                        purchaseFoodBean.setFoodQuantity(1);
                    }
                    foodListAdapter.notifyItemChanged(position);
                });
            } else {
                //當數量發生改變時，重新計算價格。
                if (beforeNumber > number) {
                    //減少金額
                    minusTotalPrice(tvPrice, getData().get(viewHolder.getLayoutPosition()), purchaseFoodBean.getUnitPrice(), beforeNumber - number, 0);
                } else {
                    //增加金額
                    addTotalAmount(tvPrice, getData().get(viewHolder.getLayoutPosition()), purchaseFoodBean.getUnitPrice(), number - beforeNumber, 0);
                }
                //判斷當前總價是否滿足最低採購金額
                setTvMinimumAmount(getData().get(viewHolder.getAdapterPosition()), tvMinMinimumAmount, viewHolder.getView(R.id.rv_purchase_shopping_minimum_tip));
            }
        }));
        //食品的刪除按鈕點擊事件
        foodListAdapter.setOnItemChildClickListener((adapter, view, position) -> {
            if (view.getId() == R.id.iv_order_food_delete) {
                PurchaseFoodBean purchaseFoodBean = foodListAdapter.getData().get(position);
                foodListAdapter.getOnNumberChangeListener().onChanged(purchaseFoodBean.getFoodQuantity(), 0, position);
            }
        });
        //單個食品選中狀態切換
        foodListAdapter.setOnCheckedChangeListener((isChecked, purchaseFoodListVosBean) -> {
            //修改選擇狀態
            purchaseFoodListVosBean.setChecked(isChecked);
            ShoppingCartBean cartBean = getData().get(viewHolder.getLayoutPosition());
            if (isChecked) {
                boolean isAllSelected = true;
                //判斷是否所有食品已選中
                for (PurchaseFoodBean purchaseFoodBean : cartBean.getFoodList()) {
                    if (!purchaseFoodBean.isChecked()) {
                        isAllSelected = false;
                        break;
                    }
                }
                cbAllSelect.setChecked(isAllSelected);
                cartBean.setAllSelect(isAllSelected);
                //選中時，增加金額，增加種類
                addFood(tvPrice, tvFoodTypeNumber, cartBean, purchaseFoodListVosBean.getUnitPrice(), purchaseFoodListVosBean.getFoodQuantity());
            } else {
                cbAllSelect.setChecked(false);
                cartBean.setAllSelect(false);
                //取消時，減去金額，減去種類
                minusFood(tvPrice, tvFoodTypeNumber, cartBean, purchaseFoodListVosBean.getUnitPrice(), purchaseFoodListVosBean.getFoodQuantity());
            }
            //判斷當前總價是否滿足最低採購金額
            setTvMinimumAmount(getData().get(viewHolder.getAdapterPosition()), tvMinMinimumAmount, viewHolder.getView(R.id.rv_purchase_shopping_minimum_tip));
        });
        rvFoods.setVisibility(View.VISIBLE);
        if (shoppingCartBean.isFlashing()) {
            //閃爍
            viewHolder.setGone(R.id.item_purchase_shopping_parent_layout, false);
            AnimatorSet animatorSet = AnimateUtils.flashAnimation(viewHolder.getView(R.id.item_purchase_shopping_parent_layout));
            RxJavaUtils.delay(2, aLong -> {
                //停止閃爍
                animatorSet.end();
                shoppingCartBean.setFlashing(false);
                viewHolder.setGone(R.id.item_purchase_shopping_parent_layout, true);
            });
        }
    }

    private void setTvMinimumAmount(ShoppingCartBean shoppingCartBean, TextView tvMinMinimumAmount, TextView tipTv) {
        if (MoneyUtil.compareTo(shoppingCartBean.getSelectFoodAmount(), shoppingCartBean.getMinimumAmount()) < 0) {
            //小於最低採購金額
            tvMinMinimumAmount.setText(String.format(context.getString(R.string.minimumAmount), shoppingCartBean.getMinimumAmount()));
            tvMinMinimumAmount.setTextColor(ContextCompat.getColor(context, R.color.required_color));
            tipTv.setVisibility(View.VISIBLE);
        } else {
            tvMinMinimumAmount.setText(shoppingCartBean.getAddress());
            tvMinMinimumAmount.setTextColor(ContextCompat.getColor(context, R.color.color_3c));
            tipTv.setVisibility(View.GONE);
        }
    }

    /**
     * 刪除食品
     *
     * @param supplierPosition 供應商的下標
     * @param tvPrice          顯示供應商總價的textview
     * @param tvFoodTypeNumber 顯示食品種類textview
     * @param foodListAdapter  供應商的食品adapter
     * @param beforeNumber     刪除之前的食品數量
     * @param position         需要刪除的食品下標
     * @param purchaseFoodBean 需要刪除的食品對象
     * @return 是否刪除供應商
     */
    private boolean deleteFood(int supplierPosition, TextView tvPrice, TextView tvFoodTypeNumber, FoodListAdapter foodListAdapter, int beforeNumber, int position, PurchaseFoodBean purchaseFoodBean) {
        foodListAdapter.removeAt(position);
        //如果這個供應商沒有食品了，需要當前adapter刪除掉這個供應商
        if (foodListAdapter.getItemCount() == 0) {
            if (onFoodDeleteListener != null) {
                onFoodDeleteListener.onDeleteFood(supplierPosition, purchaseFoodBean);
            }
            return true;
        } else {
            //這個供應商還有食品
            //如果這個食品是選中的
            if (purchaseFoodBean.isChecked()) {
                //計算這個供應商 選中食材的價格，減去當前這個食材的價格
                ShoppingCartBean shoppingCartBean1 = getData().get(supplierPosition);
                minusFood(tvPrice, tvFoodTypeNumber, shoppingCartBean1, purchaseFoodBean.getUnitPrice(), beforeNumber);
            }
        }
        return false;
    }

    /**
     * 取消選中或刪除食品 需要對種類進行操作
     *
     * @param tvPrice          價格textview
     * @param tvFoodTypeNumber 種類textview
     * @param cartBean         當前供應商信息
     * @param unitPrice        食品單價
     * @param foodQuantity     食品數量
     */
    private void minusFood(TextView tvPrice, TextView tvFoodTypeNumber, ShoppingCartBean cartBean, double unitPrice, int foodQuantity) {
        int species = cartBean.getSelectSpeciesNum() - 1;
        cartBean.setSelectSpeciesNum(species);
        tvFoodTypeNumber.setText(String.valueOf(species));
        minusTotalPrice(tvPrice, cartBean, unitPrice, foodQuantity, -1);
    }

    /**
     * 選中食品 需要對種類進行操作
     *
     * @param tvPrice          價格textview
     * @param tvFoodTypeNumber 種類textview
     * @param cartBean         當前供應商信息
     * @param unitPrice        食品單價
     * @param foodQuantity     食品數量
     */
    private void addFood(TextView tvPrice, TextView tvFoodTypeNumber, ShoppingCartBean cartBean, double unitPrice, int foodQuantity) {
        int species = cartBean.getSelectSpeciesNum() + 1;
        cartBean.setSelectSpeciesNum(species);
        tvFoodTypeNumber.setText(String.valueOf(species));
        addTotalAmount(tvPrice, cartBean, unitPrice, foodQuantity, 1);
    }

    /**
     * 總價格增加 不需要修改種類數量
     *
     * @param tvPrice      價格textview
     * @param cartBean     當前供應商信息
     * @param unitPrice    食品單價
     * @param foodQuantity 食品數量
     * @param species      需要增加的種類數量
     */
    private void addTotalAmount(TextView tvPrice, ShoppingCartBean cartBean, double unitPrice, int foodQuantity, int species) {
        //供應商總價減去-這個食品的總價=等於現價
        double currentPrice = MoneyUtil.sum(cartBean.getSelectFoodAmount(), MoneyUtil.priceCalculation(unitPrice, foodQuantity));
        cartBean.setSelectFoodAmount(currentPrice);
        tvPrice.setText(String.format(context.getString(R.string.amount_string), currentPrice));
        //傳遞回去
        if (onInfoChangeListener != null) {
            onInfoChangeListener.onInfoChange(MoneyUtil.priceCalculation(unitPrice, foodQuantity), species);
        }
    }

    /**
     * 總價減少 不需要修改種類數量
     *
     * @param tvPrice      價格textview
     * @param cartBean     當前供應商信息
     * @param unitPrice    食品單價
     * @param foodQuantity 食品數量
     * @param species      需要減少的種類數量
     */
    private void minusTotalPrice(TextView tvPrice, ShoppingCartBean cartBean, double unitPrice, int foodQuantity, int species) {
        //供應商總價減去-這個食品的總價=等於現價
        double currentPrice = MoneyUtil.sub(cartBean.getSelectFoodAmount(), MoneyUtil.priceCalculation(unitPrice, foodQuantity));
        cartBean.setSelectFoodAmount(currentPrice);
        tvPrice.setText(String.format(context.getString(R.string.amount_string), currentPrice));
        //傳遞回去
        if (onInfoChangeListener != null) {
            onInfoChangeListener.onInfoChange(-MoneyUtil.priceCalculation(unitPrice, foodQuantity), species);
        }
    }

    private OnInfoChangeListener onInfoChangeListener;
    private OnFoodDeleteListener onFoodDeleteListener;

    public interface OnInfoChangeListener {
        /**
         * 當選中或者數量發生變化時，通知外部修改
         *
         * @param changeAmount  該供應商數據發生改變的總金額
         * @param changeSpecies 該供應商數據發生改變的食材類型數量
         */
        void onInfoChange(double changeAmount, int changeSpecies);
    }

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

    public interface OnFoodDeleteListener {
        /**
         * 刪除回調接口：只在此供應商下沒有食品時調用
         *
         * @param supplierIndex   供應商下標
         * @param foodListVosBean 這個供應商信息
         */
        void onDeleteFood(int supplierIndex, PurchaseFoodBean foodListVosBean);
    }

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

    /**
     * 全選按鈕的狀態切換
     *
     * @param foodListAdapter  顯示所有食品的adapter
     * @param shoppingCartBean 單個供應商和供應商食品信息
     * @param tvPrice          該供應商總價textview
     * @param tvNumber         該供應商種類textview
     * @param cbAllSelect      全選複選框
     */
    private void allSelectListener(FoodListAdapter foodListAdapter, ShoppingCartBean shoppingCartBean, TextView tvPrice, TextView tvNumber, CheckBox cbAllSelect) {
        //全選
        cbAllSelect.setOnCheckedChangeListener((buttonView, isChecked) -> {
            if (buttonView.isPressed()) {
                int speciesNum = 0;
                double totalAmount = 0;
                shoppingCartBean.setAllSelect(isChecked);
                if (isChecked) {
                    for (PurchaseFoodBean purchaseFoodBean : foodListAdapter.getData()) {
                        purchaseFoodBean.setChecked(true);
                        totalAmount = MoneyUtil.sum(totalAmount, MoneyUtil.priceCalculation(purchaseFoodBean.getUnitPrice(), purchaseFoodBean.getFoodQuantity()));
                    }
                    speciesNum = shoppingCartBean.getFoodList().size();
                } else {
                    for (PurchaseFoodBean purchaseFoodBean : foodListAdapter.getData()) {
                        purchaseFoodBean.setChecked(false);
                    }
                }
                tvNumber.setText(String.valueOf(speciesNum));
                tvPrice.setText(String.format(context.getString(R.string.amount_string_s), MoneyUtil.formatDouble(totalAmount)));
                if (onInfoChangeListener != null) {
                    if (isChecked) {
                        //總價和種類都增加
                        onInfoChangeListener.onInfoChange(MoneyUtil.sub(totalAmount, shoppingCartBean.getSelectFoodAmount()), speciesNum - shoppingCartBean.getSelectSpeciesNum());
                    } else {
                        //總價和種類都減少
                        onInfoChangeListener.onInfoChange(-shoppingCartBean.getSelectFoodAmount(), -shoppingCartBean.getSelectSpeciesNum());
                    }
                }
                shoppingCartBean.setSelectSpeciesNum(speciesNum);
                shoppingCartBean.setSelectFoodAmount(totalAmount);
                foodListAdapter.notifyDataSetChanged();
            }
        });
    }

}
