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.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.LinearLayout;

import androidx.annotation.NonNull;
import androidx.annotation.StringRes;
import androidx.appcompat.widget.SwitchCompat;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.gingersoft.gsa.cloud.common.utils.inputFilter.InputFilterUtils;
import com.gingersoft.gsa.cloud.common.utils.other.TextUtil;
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.R2;
import com.gingersoft.supply_chain.mvp.bean.ConsumeReasonBean;
import com.gingersoft.supply_chain.mvp.ui.adapter.ConsumptionReasonAdapter;
import com.qmuiteam.qmui.alpha.QMUIAlphaTextView;

import java.util.List;

import javax.annotation.Resource;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * @author 宇航.
 * User: admin
 * Date: 2021/3/18
 * Time: 18:00
 * Use: 庫存消耗
 */
public class InventoryConsumptionView extends FrameLayout {

    private final double maxConsumption;
    @BindView(R2.id.et_input)
    EditText edInput;
    @BindView(R2.id.switch_multi_boolean_state)
    SwitchCompat switchMultiBooleanState;
    @BindView(R2.id.rv_inventory_consumption_reason)
    RecyclerView rvConsumptionReason;
    @BindView(R2.id.ed_inventory_consumption_remark)
    EditText edRemarks;
    @BindView(R2.id.tv_confirm)
    QMUIAlphaTextView tvConfirm;
    @BindView(R2.id.tv_cancel)
    QMUIAlphaTextView tvCancel;
    @BindView(R2.id.layout_inventory_btn)
    LinearLayout layoutBtn;
    private OnConfirmClickListener onConfirmClickListener;
    private ScanSnView.OnCancelListener onCancelListener;
    private ConsumptionReasonAdapter consumptionReasonAdapter;
    private OnNumberChangeListener onNumberChangeListener;


    public InventoryConsumptionView(@NonNull Context context, List<ConsumeReasonBean> consumeReasonBeans, double maxConsumption) {
        super(context);
        View rootView = LayoutInflater.from(context).inflate(R.layout.layout_inventory_consumption, null, false);
        ButterKnife.bind(this, rootView);
        addView(rootView);
        this.maxConsumption = maxConsumption;
        edRemarks.setFilters(new InputFilter[]{InputFilterUtils.getLengthFilter(getContext(), RemarkProvider.REMARK_TEXT_LENGTH), InputFilterUtils.getChAndEnNumPtWrapInputFilter(getContext())});
        consumptionReasonAdapter = new ConsumptionReasonAdapter(consumeReasonBeans);
        consumptionReasonAdapter.setOnItemChildClickListener((adapter, view, position) -> consumptionReasonAdapter.setSelectIndex(position));
        rvConsumptionReason.setLayoutManager(new GridLayoutManager(getContext(), 3));
        rvConsumptionReason.setAdapter(consumptionReasonAdapter);
        tvCancel.setOnClickListener(v -> onCancelListener.onCancel());
        tvConfirm.setOnClickListener(v -> {
            if (onConfirmClickListener != null) {
                String s = edInput.getText().toString();
                try {
                    int i = Integer.parseInt(s);
                    if (i > 0) {
                        if (i > maxConsumption) {
                            edInput.setError(String.format(getString(R.string.str_format_can_not_exceed_inventory_quantity), maxConsumption));
                        } else {
                            onConfirmClickListener.onConfirm(i, consumptionReasonAdapter.getSelectIndex(), TextUtil.getNotNullStrAndTrim(edRemarks.getText().toString()));
                        }
                    } else {
                        ToastUtils.show(getContext(), getString(R.string.str_please_input_consume_quantity));
                        edInput.setError(getString(R.string.str_please_input_consume_quantity));
                    }
                } catch (NumberFormatException e) {
                    e.printStackTrace();
                    ToastUtils.show(getContext(), getString(R.string.str_please_input_consume_quantity));
                    edInput.setError(getString(R.string.str_please_input_consume_quantity));
                }
            }
        });
        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(String.format(getString(R.string.str_format_can_not_exceed_inventory_quantity), maxConsumption));
                    }
                    if (onNumberChangeListener != null) {
                        onNumberChangeListener.onNumberChange(i);
                    }
                } catch (NumberFormatException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    public InventoryConsumptionView setEdit(boolean enabled) {
        edInput.setEnabled(enabled);
        return this;
    }

    public InventoryConsumptionView setHint(String hint) {
        edInput.setHint(hint);
        return this;
    }

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

    public InventoryConsumptionView setOnCancelListener(ScanSnView.OnCancelListener onCancelListener) {
        this.onCancelListener = onCancelListener;
        return this;
    }

    public InventoryConsumptionView setShowBtn() {
        layoutBtn.setVisibility(VISIBLE);
        return this;
    }

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

    public String getRemark() {
        return edRemarks.getText().toString();
    }

    /**
     * 獲取選中的原因下標
     *
     * @return 原因下標
     */
    public int getReasonIndex() {
        return consumptionReasonAdapter.getSelectIndex();
    }

    public boolean getIsPrint() {
        return switchMultiBooleanState.isChecked();
    }

    /**
     * 獲取消耗數量並提示
     *
     * @return 輸入的數量
     */
    public int getConsumptionNumAndTip() {
        String s = edInput.getText().toString();
        try {
            int i = Integer.parseInt(s);
            if (i > 0) {
                if (i > maxConsumption) {
                    String errMsg = String.format(getString(R.string.str_format_can_not_exceed_inventory_quantity), maxConsumption);
                    edInput.setError(errMsg);
                    ToastUtils.show(getContext(), errMsg);
                    return -1;
                } else {
                    return i;
                }
            } else {
                String errMsg = getString(R.string.str_please_input_consume_quantity);
                ToastUtils.show(getContext(), errMsg);
                edInput.setError(errMsg);
                return -1;
            }
        } catch (NumberFormatException e) {
            e.printStackTrace();
            String errMsg = getString(R.string.str_please_input_consume_quantity);
            ToastUtils.show(getContext(), errMsg);
            edInput.setError(errMsg);
            return -1;
        }
    }

    /**
     * 獲取消耗數量
     *
     * @return 輸入的數量
     */
    public int getConsumptionNum() {
        String s = edInput.getText().toString();
        try {
            return Integer.parseInt(s);
        } catch (NumberFormatException e) {
            return -1;
        }
    }

    public void setConsumptionNumber(int consumptionNumber) {
        edInput.setError(null);
        edInput.setText(String.valueOf(consumptionNumber));
    }

    private String getString(@StringRes int strId) {
        return getContext().getString(strId);
    }

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

    public interface OnNumberChangeListener {
        void onNumberChange(int num);
    }
}
