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

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

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
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 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, FoodListAdapter.ViewHolder> {
    private Context context;
    /**
     * 編輯或者下單
     * FOOD_INGREDIENTS
     * ADD_ORDER
     * ORDER_TYPE
     */
    private int adapterType;
    /**
     * key 為foodId
     * value 為 food信息
     */
    private Map<Integer, PurchaseFoodBean> integerMap;

    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);
    }

    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);
    }

    @Override
    protected void convert(@NotNull ViewHolder viewHolder, PurchaseFoodBean foodInfoBean) {
        viewHolder.setText(R.id.tv_food_item_supplier_name, foodInfoBean.getSupplierName());
        ImageView foodImg = viewHolder.getView(R.id.iv_food_ingredient_img);
        if (TextUtil.isNotEmptyOrNullOrUndefined(foodInfoBean.getImages())) {
            GlideUtils.display(context, foodImg, foodInfoBean.getImages());
        } else {
            foodImg.setImageResource(R.drawable.img_small_default);
        }
        viewHolder.setText(R.id.tv_food_item_no, foodInfoBean.getFoodNo());
        viewHolder.setText(R.id.tv_food_item_name, foodInfoBean.getName());
        viewHolder.setText(R.id.tv_food_item_unit, foodInfoBean.getPackingDescription());
        viewHolder.setText(R.id.tv_food_item_price, "$" + 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 foodId   食品ID
         * @param number   食品數量
         * @param position 操作的食品下標
         */
        void onChanged(int foodId, int number, int position);
    }

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

    /***
     * 配置編輯功能
     * @param viewHolder
     * @param foodInfoBean
     */
    private void setEdit(@NotNull ViewHolder viewHolder, PurchaseFoodBean foodInfoBean) {
        EditText editText = viewHolder.getView(R.id.ed_food_ingredient_number);
        PurchaseFoodBean food = integerMap.get(foodInfoBean.getId());
        if (viewHolder.textWatcher != null) {
            editText.removeTextChangedListener(viewHolder.textWatcher);
        }
        if (food == null) {
            editText.setText(String.valueOf(0));
        } else {
            editText.setText(String.valueOf(food.getFoodQuantity()));
        }
        viewHolder.getView(R.id.btn_food_operation_sub).setOnClickListener(v -> subNumber(editText, foodInfoBean));

        viewHolder.getView(R.id.btn_food_operation_add).setOnClickListener(v -> addNumber(editText, foodInfoBean));
//            viewHolder.getView(R.id.btn_food_operation_sub).setOnLongClickListener(v -> {
//                ThreadFactory namedThreadFactory = r -> null;
//                ScheduledExecutorService scheduledExecutorService = new ScheduledThreadPoolExecutor(1, namedThreadFactory);
//                scheduledExecutorService.scheduleAtFixedRate(new Runnable() {
//                    @Override
//                    public void run() {
//
//                    }
//                }, 0, 1, TimeUnit.SECONDS);
//                subNumber(editText, foodInfoBean);
//                return true;
//            });
//            viewHolder.getView(R.id.btn_food_operation_add).setOnLongClickListener(v -> {
//                addNumber(editText, foodInfoBean);
//                return true;
//            });
        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())) {
                    editText.setText(String.valueOf(0));
                    editText.setSelection(editText.getText().length());
                    if (onNumberChangeListener != null) {
                        onNumberChangeListener.onChanged(purchaseFoodBean.getId(), 0, viewHolder.getAdapterPosition());
                    }
                } else {
                    purchaseFoodBean.setFoodQuantity(Integer.parseInt(s.toString()));
                    if (purchaseFoodBean.getFoodQuantity() > 0) {
                        integerMap.put(purchaseFoodBean.getId(), purchaseFoodBean);
                    }
                    if (onNumberChangeListener != null) {
                        onNumberChangeListener.onChanged(purchaseFoodBean.getId(), Integer.parseInt(s.toString()), viewHolder.getAdapterPosition());
                    }
                }
            }
        };
        editText.addTextChangedListener(foodNumTextWatcher);
        viewHolder.textWatcher = foodNumTextWatcher;
    }

    public void setOnNumberChangeListener(OnNumberChangeListener onNumberChangeListener) {
        this.onNumberChangeListener = 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 {
            foodInfoBean.setFoodQuantity(1);
            purchaseFoodBean = foodInfoBean;
            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;
    }

    public static class ViewHolder extends BaseViewHolder {
        public TextWatcher textWatcher;

        public ViewHolder(@NotNull View view) {
            super(view);
        }
    }
}
