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.EditText;
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.common.utils.time.TimeUtils;
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;

    private String amountUnitStr;
    private String estimateDeliveryTimeStr;

    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);
        amountUnitStr = context.getString(R.string.amount_string);
        estimateDeliveryTimeStr = context.getString(R.string.estimate_delivery_time);
    }

    @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);
        viewHolder.setText(R.id.rv_purchase_shopping_estimate_delivery_time, String.format(estimateDeliveryTimeStr, shoppingCartBean.getInitialShippingTime()));
        setTvMinimumAmount(shoppingCartBean, tvMinMinimumAmount, viewHolder.getView(R.id.rv_purchase_shopping_minimum_tip));
//        viewHolder.setText(R.id.tv_order_item_freight, shoppingCartBean.getFoodList());
        //選中食品的總價
        setTotalAmount(viewHolder, shoppingCartBean.getSelectFoodAmount());
        //運費
        viewHolder.setText(R.id.tv_order_item_freight, String.format(amountUnitStr, shoppingCartBean.getShipping()));
        //實際應付金額
        setActualAmount(viewHolder, 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, tvFoodTypeNumber, cbAllSelect, viewHolder);
        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(), viewHolder, 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(viewHolder, getData().get(viewHolder.getLayoutPosition()), purchaseFoodBean.getUnitPrice(), beforeNumber - number, 0);
                } else {
                    //增加金額
                    addTotalAmount(viewHolder, 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(viewHolder, tvFoodTypeNumber, cartBean, purchaseFoodListVosBean.getUnitPrice(), purchaseFoodListVosBean.getFoodQuantity());
            } else {
                cbAllSelect.setChecked(false);
                cartBean.setAllSelect(false);
                //取消時，減去金額，減去種類
                minusFood(viewHolder, 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);
        //備註
        viewHolder.setText(R.id.ed_purchase_shopping_remarks, shoppingCartBean.getRemarks());
        EditText mEdRemarks = viewHolder.getView(R.id.ed_purchase_shopping_remarks);
        mEdRemarks.setOnFocusChangeListener((v, hasFocus) -> {
            if (!hasFocus) {
                //失去焦點時修改備註
                ShoppingCartBean currentShoppingBean = getData().get(viewHolder.getAdapterPosition());
                currentShoppingBean.setRemarks(mEdRemarks.getText() + "");
            }
        });
        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 setTotalAmount(BaseViewHolder viewHolder, Double totalAmount) {
        viewHolder.setText(R.id.tv_order_item_total_amount, String.format(amountUnitStr, totalAmount));
    }

    /**
     * 修改實際總金額
     *
     * @param totalAmount 加上運費後的總金額
     */
    private void setActualAmount(BaseViewHolder viewHolder, Double totalAmount) {
        viewHolder.setText(R.id.tv_order_item_actual_pay_amount, String.format(amountUnitStr, totalAmount));
    }


    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 tvFoodTypeNumber 顯示食品種類textview
     * @param foodListAdapter  供應商的食品adapter
     * @param beforeNumber     刪除之前的食品數量
     * @param position         需要刪除的食品下標
     * @param purchaseFoodBean 需要刪除的食品對象
     * @return 是否刪除供應商
     */
    private boolean deleteFood(int supplierPosition, BaseViewHolder viewHolder, 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 (onFoodDeleteListener != null) {
                onFoodDeleteListener.onDeleteFood(supplierPosition, purchaseFoodBean);
            }
            //這個供應商還有食品
            //如果這個食品是選中的
            if (purchaseFoodBean.isChecked()) {
                //計算這個供應商 選中食材的價格，減去當前這個食材的價格
                ShoppingCartBean shoppingCartBean1 = getData().get(supplierPosition);
                minusFood(viewHolder, tvFoodTypeNumber, shoppingCartBean1, purchaseFoodBean.getUnitPrice(), beforeNumber);
            }
        }
        return false;
    }

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

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

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

    /**
     * 總價減少 不需要修改種類數量
     *
     * @param cartBean     當前供應商信息
     * @param unitPrice    食品單價
     * @param foodQuantity 食品數量
     * @param species      需要減少的種類數量
     */
    private void minusTotalPrice(BaseViewHolder viewHolder, ShoppingCartBean cartBean, double unitPrice, int foodQuantity, int species) {
        //供應商總價減去-這個食品的總價=等於現價
        double currentPrice = MoneyUtil.sub(cartBean.getSelectFoodAmount(), MoneyUtil.priceCalculation(unitPrice, foodQuantity));
        cartBean.setSelectFoodAmount(currentPrice);
        String amountStr = String.format(amountUnitStr, currentPrice);
        setTotalAmount(viewHolder, currentPrice);
        viewHolder.setText(R.id.tv_order_item_actual_pay_amount, amountStr);
        //傳遞回去
        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 tvNumber         該供應商種類textview
     * @param cbAllSelect      全選複選框
     */
    private void allSelectListener(FoodListAdapter foodListAdapter, ShoppingCartBean shoppingCartBean, TextView tvNumber, CheckBox cbAllSelect, BaseViewHolder viewHolder) {
        //全選
        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));
                String amountStr = String.format(context.getString(R.string.amount_string_s), MoneyUtil.formatDouble(totalAmount));
                setTotalAmount(viewHolder, totalAmount);
                //實際應付金額
                viewHolder.setText(R.id.tv_order_item_actual_pay_amount, amountStr);
                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();
            }
        });
    }

}
