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

import android.animation.AnimatorSet;
import android.content.Context;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextWatcher;
import android.view.LayoutInflater;
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.inputFilter.InputFilterUtils;
import com.gingersoft.gsa.cloud.common.utils.other.TextUtil;
import com.gingersoft.gsa.cloud.common.utils.time.TimeUtils;
import com.gingersoft.gsa.cloud.ui.adapter.multi.RemarkProvider;
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.google.android.material.textfield.TextInputEditText;
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, ShoppingCartAdapter.ViewHolder> {
    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 ViewHolder viewHolder, ShoppingCartBean shoppingCartBean) {
        viewHolder.setText(R.id.rv_purchase_shopping_estimate_delivery_time, String.format(estimateDeliveryTimeStr, shoppingCartBean.getInitialShippingTime()));
        //最低採購金額
        setTvMinimumAmount(viewHolder);
        //選中食品的總價
        setTotalAmount(viewHolder, shoppingCartBean.getSelectFoodAmount());
        //實際應付金額
        setActualAmount(viewHolder, MoneyUtil.sum(shoppingCartBean.getSelectFoodAmount(), shoppingCartBean.getShipping()));
        //運費
        TextInputEditText etShipping = viewHolder.getView(R.id.tv_order_item_freight);
        etShipping.removeTextChangedListener(viewHolder.textWatcher);
        viewHolder.textWatcher.setViewHolder(viewHolder).setTvActualPayAmount(viewHolder.getView(R.id.tv_order_item_actual_pay_amount));
        viewHolder.setText(R.id.tv_order_item_freight, MoneyUtil.formatDouble(shoppingCartBean.getShipping()));
        etShipping.addTextChangedListener(viewHolder.textWatcher);
        //選中食品的種類
        viewHolder.setText(R.id.tv_order_item_food_type_total, String.valueOf(shoppingCartBean.getSelectSpeciesNum()));
        //供應商下的食品
        initFoods(viewHolder, shoppingCartBean);
        //備註
        viewHolder.setText(R.id.ed_purchase_shopping_remarks, shoppingCartBean.getRemarks());
        EditText mEdRemarks = viewHolder.getView(R.id.ed_purchase_shopping_remarks);
        mEdRemarks.setFilters(new InputFilter[]{InputFilterUtils.getLengthFilter(getContext(), RemarkProvider.REMARK_TEXT_LENGTH), InputFilterUtils.getChAndEnNumPtWrapInputFilter(getContext())});
        mEdRemarks.setOnFocusChangeListener((v, hasFocus) -> {
            if (!hasFocus) {
                //失去焦點時修改備註
                ShoppingCartBean currentShoppingBean = getData().get(viewHolder.getAdapterPosition());
                if (TextUtil.isNotEmptyOrNullOrUndefined(mEdRemarks)) {
                    currentShoppingBean.setRemarks("");
                } else {
                    currentShoppingBean.setRemarks(TextUtil.getNotNullStrAndTrim(mEdRemarks.getText().toString()));
                }
            }
        });
        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);
            });
        }
    }

    public class ViewHolder extends BaseViewHolder {
        ShippingTextWatcher textWatcher = new ShippingTextWatcher();
        private TextInputEditText etShipping;

        public ViewHolder(@NotNull View view) {
            super(view);
            etShipping = view.findViewById(R.id.tv_order_item_freight);
            etShipping.addTextChangedListener(textWatcher);
        }
    }


    private void initFoods(@NotNull BaseViewHolder viewHolder, ShoppingCartBean shoppingCartBean) {
        RecyclerView rvFoods = viewHolder.getView(R.id.rv_shopping_cart_food);
        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, viewHolder.getView(R.id.tv_order_item_food_type_total), 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，需要詢問是否刪除
                //彈窗顯示 是否刪除
                AppDialog.getInstance().showWaringDialog(context, "是否刪除食品？", true, () -> {
                    boolean isDeleteSupplier = deleteFood(viewHolder.getAdapterPosition(), viewHolder, viewHolder.getView(R.id.tv_order_item_food_type_total), foodListAdapter, beforeNumber, position, purchaseFoodBean);
                    //如果這個供應商被刪除了，就不用判斷採購金額了
                    if (!isDeleteSupplier) {
                        //判斷當前總價是否滿足最低採購金額
                        setTvMinimumAmount(viewHolder);
                    }
                }, () -> {
                    //不刪除這個食品
                    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(viewHolder);
            }
        }));
        //食品的刪除按鈕點擊事件
        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, cartBean, purchaseFoodListVosBean.getUnitPrice(), purchaseFoodListVosBean.getFoodQuantity());
            } else {
                cbAllSelect.setChecked(false);
                cartBean.setAllSelect(false);
                //取消時，減去金額，減去種類
                minusFood(viewHolder, cartBean, purchaseFoodListVosBean.getUnitPrice(), purchaseFoodListVosBean.getFoodQuantity());
            }
            //判斷當前總價是否滿足最低採購金額
            setTvMinimumAmount(viewHolder);
        });
        rvFoods.setVisibility(View.VISIBLE);
    }

    /**
     * 運費的輸入監聽
     */
    private class ShippingTextWatcher implements TextWatcher {
        BaseViewHolder viewHolder;
        TextView tvActualPayAmount;

        public ShippingTextWatcher setViewHolder(BaseViewHolder viewHolder) {
            this.viewHolder = viewHolder;
            return this;
        }

        public ShippingTextWatcher setTvActualPayAmount(TextView tvActualPayAmount) {
            this.tvActualPayAmount = tvActualPayAmount;
            return this;
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            if (viewHolder != null) {
                //需要修改實際應付金額和activity的總金額
                //拿到現在的金額，減去之前的金額
                double nowShipping = 0;
                if (TextUtil.isNotEmptyOrNullOrUndefined(s)) {
                    nowShipping = Double.parseDouble(s.toString());
                }
                ShoppingCartBean shoppingCartBean = getData().get(viewHolder.getAdapterPosition());
                //通知activity修改
                if (onInfoChangeListener != null) {
                    onInfoChangeListener.onInfoChange(MoneyUtil.sub(nowShipping, shoppingCartBean.getShipping()), 0);
                }
                shoppingCartBean.setShipping(nowShipping);
                //修改實際應付金額
                tvActualPayAmount.setText(String.format(amountUnitStr, MoneyUtil.sum(shoppingCartBean.getSelectFoodAmount(), shoppingCartBean.getShipping())));
            }
        }
    }


    /**
     * 修改總金額
     */
    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));
    }

    /**
     * 最低採購金額
     *
     * @param viewHolder
     */
    private void setTvMinimumAmount(BaseViewHolder viewHolder) {
        ShoppingCartBean shoppingCartBean = getData().get(viewHolder.getAdapterPosition());
        if (MoneyUtil.compareTo(shoppingCartBean.getSelectFoodAmount(), shoppingCartBean.getMinimumAmount()) < 0) {
            //小於最低採購金額
            viewHolder.setText(R.id.tv_minimumAmount, String.format(context.getString(R.string.minimumAmount), shoppingCartBean.getMinimumAmount()));
            viewHolder.setTextColor(R.id.tv_minimumAmount, ContextCompat.getColor(context, R.color.required_color));
            viewHolder.setGone(R.id.rv_purchase_shopping_minimum_tip, false);
        } else {
            viewHolder.setText(R.id.tv_minimumAmount, shoppingCartBean.getAddress());
            viewHolder.setTextColor(R.id.tv_minimumAmount, ContextCompat.getColor(context, R.color.color_3c));
            viewHolder.setGone(R.id.rv_purchase_shopping_minimum_tip, true);
        }
    }

    /**
     * 刪除食品
     *
     * @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, shoppingCartBean1, purchaseFoodBean.getUnitPrice(), beforeNumber);
            }
        }
        return false;
    }

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

    /**
     * 選中食品 需要對種類進行操作
     *
     * @param cartBean     當前供應商信息
     * @param unitPrice    食品單價
     * @param foodQuantity 食品數量
     */
    private void addFood(BaseViewHolder viewHolder, ShoppingCartBean cartBean, double unitPrice, int foodQuantity) {
        int species = cartBean.getSelectSpeciesNum() + 1;
        cartBean.setSelectSpeciesNum(species);
        viewHolder.setText(R.id.tv_order_item_food_type_total, 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, MoneyUtil.sum(currentPrice, cartBean.getShipping()));
        //傳遞回去
        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);
        //修改顯示總金額
        setTotalAmount(viewHolder, currentPrice);
        //修改實際應付金額
        setActualAmount(viewHolder, MoneyUtil.sum(currentPrice, cartBean.getShipping()));
        //傳遞回去，由於是減少食品，所以金額為負
        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();
            }
        });
    }

}
