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

import android.content.Context;
import android.view.MotionEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

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.gsa.cloud.common.utils.threadPool.ThreadPoolManager;
import com.gingersoft.supply_chain.R;
import com.gingersoft.supply_chain.mvp.bean.BuyIngredientsBean;
import com.gingersoft.supply_chain.mvp.bean.PurchaseFoodBean;
import com.gingersoft.supply_chain.mvp.ui.fragment.food.BuyIngredientsFragment;

import java.util.List;

/**
 * @author 宇航.
 * User: admin
 * Date: 2021/3/11
 * Time: 16:18
 * Use: 食材列表
 */
public class BuyIngredientsAdapter extends GroupedRecyclerViewAdapter<BuyIngredientsBean> {
    /**
     * 編輯或者下單
     * FOOD_INGREDIENTS
     * ADD_ORDER
     * ORDER_TYPE
     */
//    private int adapterType = BuyIngredientsFragment.ADD_ORDER;
    /**
     * 是否顯示編輯和刪除按鈕
     */
    private boolean isEdit = false;
    /**
     * 是否顯示數量和+-
     */
    private boolean isShowNumber = true;

    /**
     * 是否是顯示單列
     */
    private boolean isSinger = true;
    private OnFoodNumberChangeListener onFoodNumberChangeListener;
    private boolean longClick = false;
    private int delayTime = 500;

    public BuyIngredientsAdapter(Context context, List<BuyIngredientsBean> buyIngredientsBeans) {
        super(context, buyIngredientsBeans);
        addChildClickViewIds(R.id.iv_commodity_edit, R.id.iv_commodity_delete);
    }

    public BuyIngredientsAdapter setEdit(boolean edit) {
        isEdit = edit;
        return this;
    }

    public BuyIngredientsAdapter setShowNumber(boolean showNumber) {
        isShowNumber = showNumber;
        return this;
    }

    public void setShowSingerRow(boolean showType) {
        isSinger = showType;
    }

    @Override
    public int getGroupCount() {
        return getData() == null ? 0 : getData().size();
    }

    @Override
    public int getChildrenCount(int groupPosition) {
        BuyIngredientsBean buyIngredientsBean = getData().get(groupPosition);
        return buyIngredientsBean == null ? 0 : (buyIngredientsBean.purchaseFoodList == null ? 0 : buyIngredientsBean.purchaseFoodList.size());
    }

    @Override
    public boolean hasHeader(int groupPosition) {
        return true;
    }

    @Override
    public boolean hasFooter(int groupPosition) {
        return false;
    }

    @Override
    public int getHeaderLayout(int viewType) {
        return R.layout.item_buy_food_ingredient_header;
    }

    @Override
    public int getFooterLayout(int viewType) {
        return 0;
    }

    @Override
    public int getChildLayout(int viewType) {
        return getLayoutId();
    }

    @Override
    public void onBindHeaderViewHolder(BaseViewHolder holder, int groupPosition, BuyIngredientsBean data) {
        holder.setText(R.id.tv_buy_food_header, data.categoryName + "");
    }

    @Override
    public void onBindFooterViewHolder(BaseViewHolder holder, int groupPosition, BuyIngredientsBean data) {

    }

    @Override
    public void onBindChildViewHolder(BaseViewHolder itemViewHolder, int groupPosition, int childPosition, BuyIngredientsBean data) {
        PurchaseFoodBean purchaseFoodBean = data.purchaseFoodList.get(childPosition);
        itemViewHolder.setText(R.id.tv_food_item_supplier_name, purchaseFoodBean.getSupplierName());
        itemViewHolder.setImageResource(R.id.iv_food_ingredient_img, R.drawable.img_small_default);
        if (TextUtil.isNotEmptyOrNullOrUndefined(purchaseFoodBean.getImages())) {
            GlideUtils.display(mContext, itemViewHolder.getView(R.id.iv_food_ingredient_img), purchaseFoodBean.getImages());
        }
        itemViewHolder.setText(R.id.tv_food_item_no, purchaseFoodBean.getFoodNo());
        itemViewHolder.setText(R.id.tv_food_item_name, purchaseFoodBean.getName());
        //如果有包裝描述就顯示包裝描述，沒有包裝描述顯示基本單位
        if (TextUtil.isNotEmptyOrNullOrUndefined(purchaseFoodBean.getPackingDescription())) {
            itemViewHolder.setText(R.id.tv_food_item_unit, purchaseFoodBean.getPackingDescription());
        } else {
            itemViewHolder.setText(R.id.tv_food_item_unit, purchaseFoodBean.getBasicUnitName());
        }
        itemViewHolder.setText(R.id.tv_food_item_price, String.format(mContext.getString(R.string.amount_string_s), MoneyUtil.formatDouble(purchaseFoodBean.getUnitPrice())));
        EditText edNumberInput = itemViewHolder.getView(R.id.ed_food_ingredient_number);
        edNumberInput.setText(String.valueOf(purchaseFoodBean.getFoodQuantity()), TextView.BufferType.EDITABLE);
        //如果數量小於等於0，就不顯示減號和數量
        setSubAndNumShow(itemViewHolder, purchaseFoodBean.getFoodQuantity() <= 0);
        //編輯數量
        itemViewHolder.setOnClickListener(R.id.btn_food_operation_sub, v -> {
            //食材數量減少
            if (purchaseFoodBean.getFoodQuantity() > 0) {
                foodNumberChange(itemViewHolder, purchaseFoodBean, groupPosition, childPosition, -1);
            }
        }).setOnClickListener(R.id.btn_food_operation_add, v -> {
            //食材數量增加
            foodNumberChange(itemViewHolder, purchaseFoodBean, groupPosition, childPosition, 1);
        }).setOnTouchListener(R.id.btn_food_operation_sub, onBtnTouchListener).setOnLongClickListener(R.id.btn_food_operation_sub, v -> {
            //長按減號
            setLongClick(itemViewHolder, groupPosition, childPosition, purchaseFoodBean, false);
            return true;
        }).setOnTouchListener(R.id.btn_food_operation_add, onBtnTouchListener).setOnLongClickListener(R.id.btn_food_operation_add, v -> {
            //長按加號
            setLongClick(itemViewHolder, groupPosition, childPosition, purchaseFoodBean, true);
            return true;
        }).setOnFocusChangeListener(R.id.ed_food_ingredient_number, (v, hasFocus) -> {
            //當失去焦點時，需要判斷數量
            if (!hasFocus) {
                if (TextUtil.isEmptyOrNullOrUndefined(edNumberInput)) {
                    foodNumberChange(itemViewHolder, purchaseFoodBean, groupPosition, childPosition, -purchaseFoodBean.getFoodQuantity());
                } else {
                    int editTextQuantity = Integer.parseInt(edNumberInput.getText().toString());
                    foodNumberChange(itemViewHolder, purchaseFoodBean, groupPosition, childPosition, editTextQuantity - purchaseFoodBean.getFoodQuantity());
                }
            }
        });
//        if (adapterType == BuyIngredientsFragment.FOOD_INGREDIENTS) {
//            //編輯食材頁面，顯示編輯和刪除，隱藏加減和數量
//            setDisplayStateByType(itemViewHolder, true, false, false);
//        } else if (adapterType == BuyIngredientsFragment.ADD_ORDER) {
//            //創建採購單頁面,隱藏編輯和刪除，顯示加減和數量
//            setDisplayStateByType(itemViewHolder, false, purchaseFoodBean.getFoodQuantity() > 0, true);
//        } else if (adapterType == BuyIngredientsFragment.GET_FOOD_BY_SUPPLIER) {
//            //供應商商品列表，編輯和數量都顯示
//            setDisplayStateByType(itemViewHolder, true, purchaseFoodBean.getFoodQuantity() > 0, true);
//        }
        setDisplayStateByType(itemViewHolder, isEdit, isShowNumber && purchaseFoodBean.getFoodQuantity() > 0, isShowNumber);
        //輸入框焦點監聽
//        itemViewHolder.setOnFocusChangeListener(R.id.ed_food_ingredient_number, (v, hasFocus) -> {
//            CharSequence text = itemViewHolder.getText(R.id.ed_food_ingredient_number);
//            if (!hasFocus) {
//                //當失去焦點時，如果沒有食品數量了，就隱藏減號和輸入框
//                if (TextUtil.isEmptyOrNullOrUndefined(text) || Integer.parseInt(text.toString()) == 0) {
//                    setSubAndNumShow(itemViewHolder, false);
//                }
//            }
//        });
    }

    private void setDisplayStateByType(BaseViewHolder itemViewHolder, boolean b, boolean b2, boolean b3) {
        //編輯和刪除
        itemViewHolder.setGone(R.id.iv_commodity_edit, !b);
        itemViewHolder.setGone(R.id.iv_commodity_delete, !b);
        //減號和數量
        itemViewHolder.setGone(R.id.btn_food_operation_sub, !b2);
        itemViewHolder.setGone(R.id.ed_food_ingredient_number, !b2);
        //加號
        itemViewHolder.setGone(R.id.btn_food_operation_add, !b3);
    }

    /**
     * 設置減少按鈕和輸入框的顯示或隱藏
     *
     * @param showOrHide 顯示或隱藏 true隱藏，false顯示
     */
    private void setSubAndNumShow(BaseViewHolder viewHolder, boolean showOrHide) {
        viewHolder.setGone(R.id.btn_food_operation_sub, showOrHide);
        viewHolder.setGone(R.id.ed_food_ingredient_number, showOrHide);
    }

    /**
     * + - 按鈕觸摸事件
     */
    private View.OnTouchListener onBtnTouchListener = (v, event) -> {
        if (event.getAction() == MotionEvent.ACTION_DOWN) {
            longClick = true;
        } else if (event.getAction() == MotionEvent.ACTION_UP) {
            longClick = false;
        }
        return false;
    };

    /**
     * 按鈕長按事件
     *
     * @param purchaseFoodBean 商品信息
     * @param addOrSub         是+ or -
     */
    public void setLongClick(BaseViewHolder itemViewHolder, int groupPosition, int childPosition, PurchaseFoodBean purchaseFoodBean, boolean addOrSub) {
        //開啟線程
        EditText edNumberInput = itemViewHolder.getView(R.id.ed_food_ingredient_number);
        ThreadPoolManager.getInstence().putExecutableTasks(() -> {
            int number = 0;
            if (TextUtil.isNotEmptyOrNullOrUndefined(edNumberInput)) {
                number = Integer.parseInt(edNumberInput.getText().toString());
            }
            delayTime = 500;
            if (addOrSub) {
                //+
                if (number == 0) {
                    //如果數量為0，先把減號和數量顯示出來
                    edNumberInput.post(() -> setSubAndNumShow(itemViewHolder, false));
                }
                while (longClick) {
                    if (number < 9999) {
                        try {
                            Thread.sleep(delayTime);
                            number++;
                            if (delayTime > 100) {
                                delayTime -= 100;
                            }
                            edNumberInput.post(() -> foodNumberChange(itemViewHolder, purchaseFoodBean, groupPosition, childPosition, 1));
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    } else {
                        longClick = false;
                    }
                }
            } else {
                //-
                while (longClick) {
                    if (number > 0) {
                        try {
                            Thread.sleep(delayTime);
                            number--;
                            if (delayTime > 100) {
                                delayTime -= 100;
                            }
                            edNumberInput.post(() -> foodNumberChange(itemViewHolder, purchaseFoodBean, groupPosition, childPosition, -1));
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    } else {
                        longClick = false;
                        edNumberInput.post(() -> setSubAndNumShow(itemViewHolder, true));
                    }
                }
            }
        });
    }

    private void foodNumberChange(BaseViewHolder itemViewHolder, PurchaseFoodBean purchaseFoodBean, int groupPosition, int childPosition, int changeNum) {
        purchaseFoodBean.setFoodQuantity(purchaseFoodBean.getFoodQuantity() + changeNum);
        itemViewHolder.setText(R.id.ed_food_ingredient_number, String.valueOf(purchaseFoodBean.getFoodQuantity()));
        setSubAndNumShow(itemViewHolder, purchaseFoodBean.getFoodQuantity() <= 0);
        if (onFoodNumberChangeListener != null) {
            onFoodNumberChangeListener.onChange(purchaseFoodBean, groupPosition, childPosition, purchaseFoodBean.getFoodQuantity() - changeNum, purchaseFoodBean.getFoodQuantity());
        }
    }


    public interface OnFoodNumberChangeListener {
        /**
         * 數量改變
         *
         * @param purchaseFoodBean    商品信息
         * @param parentCategoryIndex 所屬分類下標
         * @param categoryIndex       食材在分類中的下標
         * @param beforeNum           之前的數量
         * @param currentNum          現在的數量
         */
        void onChange(PurchaseFoodBean purchaseFoodBean, int parentCategoryIndex, int categoryIndex, int beforeNum, int currentNum);
    }

    public void setOnFoodNumberChangeListener(OnFoodNumberChangeListener onFoodNumberChangeListener) {
        this.onFoodNumberChangeListener = onFoodNumberChangeListener;
    }

    public int getLayoutId() {
        if (isSinger) {
            return R.layout.item_buy_food_ingredient;
        }
        return R.layout.item_buy_food_ingredient_double_row;
    }
}
