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

import android.content.Context;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

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.glide.GlideUtils;
import com.gingersoft.gsa.cloud.common.utils.other.TextUtil;
import com.gingersoft.supply_chain.R;
import com.gingersoft.supply_chain.mvp.bean.PurchaseFoodBean;
import com.gingersoft.supply_chain.mvp.ui.fragment.food.FoodIngredientsFragment;
import com.google.android.material.textfield.TextInputEditText;

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

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.gingersoft.supply_chain.mvp.content.Constant.PURCHASE_FOOD_MAX;
import static com.gingersoft.supply_chain.mvp.ui.fragment.food.FoodIngredientsFragment.FOOD_INGREDIENTS;
import static com.gingersoft.supply_chain.mvp.ui.fragment.food.FoodIngredientsFragment.ORDER_TYPE;

/**
 * @author 宇航.
 * User: admin
 * Date: 2020/12/2
 * Time: 10:05
 * Use: 供應鏈食品列表
 */
public class FoodListAdapter extends BaseQuickAdapter<PurchaseFoodBean, BaseViewHolder> {
    private Context context;
    /**
     * 編輯或者下單
     * FOOD_INGREDIENTS
     * ADD_ORDER
     * ORDER_TYPE
     */
    private int adapterType;
    /**
     * key 為foodId
     * value 為 food信息
     * 保存著用戶選擇的數量大於0的食品
     * <p>
     * 注：採購頁面、編輯頁面和購物車頁面共用，採購和購物車頁面都需要對數量進行操作
     * 所以增加一個map，裝用戶採購的食材，相當於購物車，不然採購完後去到結算頁面之前
     * 需要拿到用戶選了哪些食品，需要遍歷所有食品，太費時，就用這個map裝著用戶所有數量大於0的食材
     */
    private Map<Integer, PurchaseFoodBean> integerMap;

    private String moneyString;

    public FoodListAdapter(Context context, @Nullable List<PurchaseFoodBean> data, int adapterType) {
        super(R.layout.item_food_ingredient, data);
        addChildClickViewIds(R.id.iv_supplier_edit, R.id.iv_supplier_delete);
        this.context = context;
        this.adapterType = adapterType;
        integerMap = new HashMap<>(8);
        moneyString = context.getString(R.string.amount_string_s);
    }

    public FoodListAdapter(int layoutId, Context context, @Nullable List<PurchaseFoodBean> data, int adapterType) {
        super(layoutId, data);
        addChildClickViewIds(R.id.iv_supplier_edit, R.id.iv_supplier_delete, R.id.iv_order_food_delete);
        this.context = context;
        this.adapterType = adapterType;
        integerMap = new HashMap<>(8);
        moneyString = context.getString(R.string.amount_string_s);
    }

    @Override
    protected void convert(@NotNull BaseViewHolder viewHolder, PurchaseFoodBean foodInfoBean) {
        viewHolder.setText(R.id.tv_food_item_supplier_name, foodInfoBean.getSupplierName());
        ImageView foodImg = viewHolder.getView(R.id.iv_food_ingredient_img);
        foodImg.setImageResource(R.drawable.img_small_default);
        if (TextUtil.isNotEmptyOrNullOrUndefined(foodInfoBean.getImages())) {
            GlideUtils.display(context, foodImg, foodInfoBean.getImages());
        }
        viewHolder.setText(R.id.tv_food_item_no, foodInfoBean.getFoodNo());
        viewHolder.setText(R.id.tv_food_item_name, foodInfoBean.getName());
        //如果有包裝描述就顯示包裝描述，沒有包裝描述顯示基本單位
        if (TextUtil.isNotEmptyOrNullOrUndefined(foodInfoBean.getPackingDescription())) {
            viewHolder.setText(R.id.tv_food_item_unit, foodInfoBean.getPackingDescription());
        } else {
            viewHolder.setText(R.id.tv_food_item_unit, foodInfoBean.getBasicUnitName());
        }
        viewHolder.setText(R.id.tv_food_item_price, String.format(context.getString(R.string.amount_string), foodInfoBean.getUnitPrice()));
        if (adapterType == FOOD_INGREDIENTS) {
            viewHolder.setGone(R.id.iv_supplier_edit, false);
            viewHolder.setGone(R.id.iv_supplier_delete, false);
            viewHolder.setGone(R.id.layout_operation_food_num, true);
            viewHolder.setGone(R.id.cb_order_item_all_select, true);
            viewHolder.setGone(R.id.line_supplier_info, false);
        } else if (adapterType == ORDER_TYPE) {
            viewHolder.setGone(R.id.iv_supplier_edit, false);
            viewHolder.setGone(R.id.iv_supplier_delete, false);
            viewHolder.setGone(R.id.layout_operation_food_num, false);
            viewHolder.setGone(R.id.cb_order_item_all_select, false);
//            viewHolder.setGone(R.id.line_supplier_info, true);
            setEdit(viewHolder, foodInfoBean);
            CheckBox checkBox = viewHolder.getView(R.id.cb_order_item_all_select);
            checkBox.setChecked(foodInfoBean.isChecked());
            checkBox.setOnCheckedChangeListener((buttonView, isChecked) -> {
                if (onCheckedChangeListener != null && buttonView.isPressed()) {
                    onCheckedChangeListener.onChanged(isChecked, getData().get(viewHolder.getAdapterPosition()));
                }
            });
        } else {
            viewHolder.setGone(R.id.iv_supplier_edit, true);
            viewHolder.setGone(R.id.iv_supplier_delete, true);
            viewHolder.setGone(R.id.layout_operation_food_num, false);
            viewHolder.setGone(R.id.cb_order_item_all_select, true);
            viewHolder.setGone(R.id.line_supplier_info, false);
            setEdit(viewHolder, foodInfoBean);
        }
    }

    private OnCheckedChangeListener onCheckedChangeListener;
    private OnNumberChangeListener onNumberChangeListener;

    public interface OnCheckedChangeListener {
        /**
         * 選中按鈕狀態切換時，將食品信息傳遞出去
         *
         * @param isChecked
         * @param purchaseFoodBean
         */
        void onChanged(boolean isChecked, PurchaseFoodBean purchaseFoodBean);
    }


    public interface OnNumberChangeListener {
        /**
         * 當食品數量發生變化時調用
         *
         * @param beforeNumber 修改前的食品數量
         * @param number       修改後的食品數量
         * @param position     操作的食品下標
         */
        void onChanged(int beforeNumber, int number, int position);
    }

    public void setOnCheckedChangeListener(OnCheckedChangeListener onCheckedChangeListener) {
        this.onCheckedChangeListener = onCheckedChangeListener;
    }

    /***
     * 配置編輯功能
     * @param viewHolder
     * @param foodInfoBean
     */
    private void setEdit(@NotNull BaseViewHolder viewHolder, PurchaseFoodBean foodInfoBean) {
        //食品數量
        TextInputEditText editText = viewHolder.getView(R.id.ed_food_ingredient_number);
        //當前食品總價
        TextView mTvTotalAmount = viewHolder.getViewOrNull(R.id.tv_food_item_total_amount);
        //從緩存中取出這個食品信息，如果沒有對應的食品信息，說明沒操作過這個食品
        //這裡是採購頁面和購物車頁面共用
        PurchaseFoodBean food = integerMap.get(foodInfoBean.getId());
        if (food == null) {
            food = foodInfoBean;
            if (food.getFoodQuantity() > 0) {
                integerMap.put(foodInfoBean.getId(), foodInfoBean);
            }
        }
        if (mTvTotalAmount != null) {
            mTvTotalAmount.setText(String.format(moneyString, MoneyUtil.formatDouble(MoneyUtil.priceCalculation(food.getUnitPrice(), food.getFoodQuantity()))));
        }
        editText.setText(String.valueOf(food.getFoodQuantity()));
        //食材減少按鈕監聽
        viewHolder.getView(R.id.btn_food_operation_sub).setOnClickListener(v -> {
            if (onNumberChangeListener != null) {
                onNumberChangeListener.onChanged(foodInfoBean.getFoodQuantity(), foodInfoBean.getFoodQuantity() - 1, viewHolder.getAdapterPosition());
            }
            subNumber(editText, foodInfoBean);
            if (mTvTotalAmount != null) {
                mTvTotalAmount.setText(String.format(moneyString, MoneyUtil.formatDouble(MoneyUtil.priceCalculation(foodInfoBean.getUnitPrice(), foodInfoBean.getFoodQuantity()))));
            }
        });
        //食材增加按鈕監聽
        viewHolder.getView(R.id.btn_food_operation_add).setOnClickListener(v -> {
            if (onNumberChangeListener != null) {
                onNumberChangeListener.onChanged(foodInfoBean.getFoodQuantity(), foodInfoBean.getFoodQuantity() + 1, viewHolder.getAdapterPosition());
            }
            addNumber(editText, foodInfoBean);
            if (mTvTotalAmount != null) {
                mTvTotalAmount.setText(String.format(moneyString, MoneyUtil.formatDouble(MoneyUtil.priceCalculation(foodInfoBean.getUnitPrice(), foodInfoBean.getFoodQuantity()))));
            }
        });
        //食材減少按鈕長按
        viewHolder.getView(R.id.btn_food_operation_sub).setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                return false;
            }
        });
        //食材增加按鈕長按
        viewHolder.getView(R.id.btn_food_operation_add).setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
//                Log.e("eee", "長按：" + System.currentTimeMillis());
                return false;
            }
        });

        //手動輸入食材數量變化監聽
        TextWatcher foodNumTextWatcher = new TextWatcher() {
            @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) {
                PurchaseFoodBean purchaseFoodBean = getData().get(viewHolder.getAdapterPosition());
                if (s == null || TextUtil.isEmptyOrNullOrUndefined(s.toString())) {

                } else {
                    //修改食品本身的數量，上面那裡不修改是因為在購物車裡面
                    //購物車裡面如果數量等於0，需要讓用戶手動確認是否刪除，用戶選擇不刪除，需要變回1的
                    if (onNumberChangeListener != null) {
                        onNumberChangeListener.onChanged(purchaseFoodBean.getFoodQuantity(), Integer.parseInt(s.toString()), viewHolder.getAdapterPosition());
                    }
                    purchaseFoodBean.setFoodQuantity(Integer.parseInt(s.toString()));
                    if (purchaseFoodBean.getFoodQuantity() > 0) {
                        integerMap.put(purchaseFoodBean.getId(), purchaseFoodBean);
                    }
                    //當前食品總價修改
                    if (mTvTotalAmount != null) {
                        mTvTotalAmount.setText(String.format(moneyString, MoneyUtil.formatDouble(MoneyUtil.priceCalculation(purchaseFoodBean.getUnitPrice(), purchaseFoodBean.getFoodQuantity()))));
                    }
                }
            }
        };
        editText.setOnFocusChangeListener((v, hasFocus) -> {
            if (hasFocus) {
//                if ("0".equals(editText.getText() + "")) {
//                    editText.setText("");
//                }
                editText.addTextChangedListener(foodNumTextWatcher);
            } else {
                //當失去焦點時，輸入框沒有值，詢問是否刪除食材
                if (TextUtil.isEmptyOrNullOrUndefined(editText)) {
                    PurchaseFoodBean purchaseFoodBean = getData().get(viewHolder.getAdapterPosition());
                    if (adapterType == FoodIngredientsFragment.ORDER_TYPE) {
                        //購物車走這個方法
                        onNumberChangeListener.onChanged(purchaseFoodBean.getFoodQuantity(), 0, viewHolder.getAdapterPosition());
                    } else {
                        //選擇食材頁面走這個方法
                        purchaseFoodBean.setFoodQuantity(0);
                        editText.setText("0");
                    }
                }
                editText.removeTextChangedListener(foodNumTextWatcher);
            }
        });
    }

    public void setOnNumberChangeListener(OnNumberChangeListener onNumberChangeListener) {
        this.onNumberChangeListener = onNumberChangeListener;
    }

    public OnNumberChangeListener getOnNumberChangeListener() {
        return onNumberChangeListener;
    }

    private void addNumber(EditText editText, PurchaseFoodBean foodInfoBean) {
        PurchaseFoodBean purchaseFoodBean = integerMap.get(foodInfoBean.getId());
        if (purchaseFoodBean != null) {
            if (purchaseFoodBean.getFoodQuantity() < PURCHASE_FOOD_MAX) {
                purchaseFoodBean.setFoodQuantity(purchaseFoodBean.getFoodQuantity() + 1);
            }
        } else {
            purchaseFoodBean = foodInfoBean;
            purchaseFoodBean.setFoodQuantity(purchaseFoodBean.getFoodQuantity() + 1);
            integerMap.put(foodInfoBean.getId(), purchaseFoodBean);
        }
        editText.setText(String.valueOf(purchaseFoodBean.getFoodQuantity()));
        editText.setSelection(editText.getText().length());
    }

    private void subNumber(EditText editText, PurchaseFoodBean foodInfoBean) {
        PurchaseFoodBean purchaseFoodBean = integerMap.get(foodInfoBean.getId());
        if (purchaseFoodBean != null) {
            purchaseFoodBean.setFoodQuantity(Math.max(purchaseFoodBean.getFoodQuantity() - 1, 0));
            if (purchaseFoodBean.getFoodQuantity() <= 0) {
                integerMap.remove(foodInfoBean.getId());
            }
            editText.setText(String.valueOf(purchaseFoodBean.getFoodQuantity()));
            editText.setSelection(editText.getText().length());
        } else {
            integerMap.remove(foodInfoBean.getId());
        }
    }

    public Map<Integer, PurchaseFoodBean> getIntegerMap() {
        return integerMap;
    }

}
