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.base.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.PurchaseFoodListVosBean;

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.ui.fragment.FoodIngredientsFragment.ADD_ORDER;
import static com.gingersoft.supply_chain.mvp.ui.fragment.FoodIngredientsFragment.FOOD_INGREDIENTS;

/**
 * @author 宇航.
 * User: admin
 * Date: 2020/12/2
 * Time: 10:05
 * Use: 供應鏈食品列表
 */
public class FoodListAdapter extends BaseQuickAdapter<PurchaseFoodListVosBean, FoodListAdapter.ViewHolder> {
    private Context context;
    /**
     * 編輯或者下單
     * FOOD_INGREDIENTS
     * ADD_ORDER
     * ORDER_TYPE
     */
    private int adapterType;
    public final static int ORDER_TYPE = 3;

    /**
     * key 為foodId
     * value 為 food信息
     */
    private Map<Integer, PurchaseFoodListVosBean> integerMap;

    public FoodListAdapter(Context context, @Nullable List<PurchaseFoodListVosBean> 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<PurchaseFoodListVosBean> 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, PurchaseFoodListVosBean 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.setVisibility(View.INVISIBLE);
        }
        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.getUnitContent());
        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 == ADD_ORDER) {
            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);
        } 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()));
                }
            });
        }
    }

    private OnCheckedChangeListener onCheckedChangeListener;
    private OnNumberChangeListener onNumberChangeListener;

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


    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, PurchaseFoodListVosBean foodInfoBean) {
        EditText editText = viewHolder.getView(R.id.ed_food_ingredient_number);
        PurchaseFoodListVosBean 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.getFoodCount()));
        }
        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) {
                PurchaseFoodListVosBean purchaseFoodListVosBean = 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(purchaseFoodListVosBean.getId(), 0, viewHolder.getAdapterPosition());
                    }
                } else {
                    purchaseFoodListVosBean.setFoodCount(Integer.parseInt(s.toString()));
                    if (purchaseFoodListVosBean.getFoodCount() > 0) {
                        integerMap.put(purchaseFoodListVosBean.getId(), purchaseFoodListVosBean);
                    }
                    if (onNumberChangeListener != null) {
                        onNumberChangeListener.onChanged(purchaseFoodListVosBean.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, PurchaseFoodListVosBean foodInfoBean) {
        PurchaseFoodListVosBean purchaseFoodListVosBean = integerMap.get(foodInfoBean.getId());
        if (purchaseFoodListVosBean != null) {
            if (purchaseFoodListVosBean.getFoodCount() < 9999) {
                purchaseFoodListVosBean.setFoodCount(purchaseFoodListVosBean.getFoodCount() + 1);
            }
        } else {
            foodInfoBean.setFoodCount(1);
            purchaseFoodListVosBean = foodInfoBean;
            integerMap.put(foodInfoBean.getId(), purchaseFoodListVosBean);
        }
        editText.setText(String.valueOf(purchaseFoodListVosBean.getFoodCount()));
        editText.setSelection(editText.getText().length());
    }

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

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

    public static class ViewHolder extends BaseViewHolder {
        public TextWatcher textWatcher;

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