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

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

import androidx.annotation.NonNull;
import androidx.appcompat.widget.AppCompatCheckBox;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.gingersoft.gsa.cloud.common.utils.inputFilter.InputFilterUtils;
import com.gingersoft.gsa.cloud.common.utils.toast.ToastUtils;
import com.gingersoft.gsa.cloud.ui.adapter.multi.RemarkProvider;
import com.gingersoft.supply_chain.R;
import com.gingersoft.supply_chain.mvp.bean.ConsumeReasonBean;
import com.lxj.xpopup.impl.ConfirmPopupView;
import com.lxj.xpopup.impl.InputConfirmPopupView;

import org.jetbrains.annotations.NotNull;

import java.util.List;

/**
 * @author 宇航.
 * User: admin
 * Date: 2021/1/22
 * Time: 10:47
 * Use: 庫存消耗彈窗
 */
public class InventoryConsumptionPopup extends ConfirmPopupView {
    /**
     * 庫存損耗原因
     */
    private List<ConsumeReasonBean> consumptionReasons;
    private EditText edRemarks;
    private EditText edInput;
    private RecyclerView rvConsumptionReason;
    private OnConfirmClickListener onConfirmClickListener;
    private int maxConsumption;

    /**
     * @param context
     * @param consumeReasonBeans 庫存消耗原因
     * @param maxConsumption     最大消耗數
     */
    public InventoryConsumptionPopup(@NonNull Context context, List<ConsumeReasonBean> consumeReasonBeans, int maxConsumption) {
        super(context, R.layout.popup_inventory_consumption);
        this.consumptionReasons = consumeReasonBeans;
        this.maxConsumption = maxConsumption;
    }

    public void setOnConfirmClickListener(OnConfirmClickListener onConfirmClickListener) {
        this.onConfirmClickListener = onConfirmClickListener;
    }

    @Override
    protected void onCreate() {
        super.onCreate();
        edRemarks = findViewById(R.id.ed_inventory_consumption_remark);
        edRemarks.setFilters(new InputFilter[]{InputFilterUtils.getLengthFilter(getContext(), RemarkProvider.REMARK_TEXT_LENGTH), InputFilterUtils.getChAndEnAndNumAndPtInputFilter(getContext())});
        edInput = findViewById(R.id.et_input);
        rvConsumptionReason = findViewById(R.id.rv_inventory_consumption_reason);
        ConsumptionReasonAdapter consumptionReasonAdapter = new ConsumptionReasonAdapter();
        consumptionReasonAdapter.setOnItemChildClickListener((adapter, view, position) -> consumptionReasonAdapter.setSelectIndex(position));
        rvConsumptionReason.setLayoutManager(new GridLayoutManager(getContext(), 2));
        rvConsumptionReason.setAdapter(consumptionReasonAdapter);
        findViewById(R.id.tv_confirm).setOnClickListener(v -> {
            if (onConfirmClickListener != null) {
                String s = edInput.getText().toString();
                try {
                    int i = Integer.parseInt(s);
                    if (i > 0) {
                        if (i > maxConsumption) {
                            edInput.setError("不能超過當前庫存數量:" + maxConsumption);
                        } else {
                            onConfirmClickListener.onConfirm(i, consumptionReasonAdapter.getSelectIndex(), edRemarks.getText().toString());
                        }
                    } else {
                        ToastUtils.show(getContext(), "請輸入消耗庫存數");
                        edInput.setError("請輸入消耗庫存數");
                    }
                } catch (NumberFormatException e) {
                    e.printStackTrace();
                    ToastUtils.show(getContext(), "請輸入消耗庫存數");
                    edInput.setError("請輸入消耗庫存數");
                }
            }
        });
        edInput.addTextChangedListener(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) {
                try {
                    int i = Integer.parseInt(s.toString());
                    if (i > maxConsumption) {
                        edInput.setError("不能超過當前庫存數量:" + maxConsumption);
                    }
                } catch (NumberFormatException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    public interface OnConfirmClickListener {
        /**
         * 確認時，將消耗的庫存，原因，備註傳遞回去
         *
         * @param consumptionNum 消耗的庫存數量
         * @param reasonIndex    原因下標
         * @param remarks        備註
         */
        void onConfirm(int consumptionNum, int reasonIndex, String remarks);
    }

    private class ConsumptionReasonAdapter extends BaseQuickAdapter<ConsumeReasonBean, BaseViewHolder> {
        private int selectIndex = 0;

        public ConsumptionReasonAdapter() {
            super(R.layout.item_consumption_reason, consumptionReasons);
            addChildClickViewIds(R.id.cb_consumption_reason);
        }

        @Override
        protected void convert(@NotNull BaseViewHolder viewHolder, ConsumeReasonBean consumeReasonBean) {
            AppCompatCheckBox compatCheckBox = viewHolder.getView(R.id.cb_consumption_reason);
            compatCheckBox.setText(consumeReasonBean.getDescription());
            compatCheckBox.setChecked(viewHolder.getAdapterPosition() == selectIndex);
        }

        public int getSelectIndex() {
            return selectIndex;
        }

        public void setSelectIndex(int selectIndex) {
            int lastSelect = this.selectIndex;
            this.selectIndex = selectIndex;
            if (lastSelect < getData().size()) {
                notifyItemChanged(lastSelect);
            }
            if (this.selectIndex < getData().size()) {
                notifyItemChanged(this.selectIndex);
            }
        }
    }


}
