package com.sybotan.android.demo.view;

import android.content.Context;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import com.sybotan.android.demo.R;


/**
 * created by lihao on 2019/3/6
 * 数字控制器
 */
public class CommonNumberControl extends RelativeLayout {
    private Context context;
    private EditText mNum;
    private ImageView mMinus;
    private ImageView mAdd;
    //可选最小数字，默认0,包含0
    public int minNum = 0;
    //可选最大数字，默认9999，包含9999
    private long maxNum = 99;
    private int defaltNum = 0;
    private InputFilter[] fArray = new InputFilter[1];
    private boolean canEdit = true;
    //是否点击EditText不弹出键盘，弹出可编辑的Dialog
    private boolean isShowPop = false;
    private TextWatcher textWatcher;

    public CommonNumberControl(Context context) {
        this(context, null);
        this.context = context;
    }

    public CommonNumberControl(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
        this.context = context;
    }

    public CommonNumberControl(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        this.context = context;
        initView(context);
    }

    private void initView(Context context) {
        View inflate = LayoutInflater.from(context).inflate(R.layout.common_number_control, this, true);
        mMinus = inflate.findViewById(R.id.number_control_minus);
        mNum = inflate.findViewById(R.id.number_control_num);
        mAdd = inflate.findViewById(R.id.number_control_add);
        mNum.setText(defaltNum + "");
        mNum.setSelection(mNum.getText().length());
        //减
        mMinus.setOnClickListener(v -> {
            long num = 0;
            if (!TextUtils.isEmpty(mNum.getText().toString())) {
                num = Long.parseLong(mNum.getText().toString());
            }
            if (num > minNum) {
                num--;
                mNum.setText(num + "");
                //mNum.setSelection(mNum.getText().length());
            } else {
//                ToastUtils.showMyToast("不能小于" + minNum);
            }
        });
        //加
        mAdd.setOnClickListener(v -> {
            long num = 0;
            if (!TextUtils.isEmpty(mNum.getText().toString())) {
                num = Long.parseLong(mNum.getText().toString());
            }
            if (num < maxNum) {
                num++;
                mNum.setText(num + "");
                //mNum.setSelection(mNum.getText().length());
            } else {
//                ToastUtils.showMyToast("不能大于" + maxNum);
            }
        });
        mNum.setOnFocusChangeListener((v, hasFocus) -> {
            if (!hasFocus) {
                if (TextUtils.isEmpty(mNum.getText().toString())) {
                    mNum.setText(minNum + "");
                }
                if (Double.parseDouble(mNum.getText().toString()) < minNum) {
                    mNum.setText(minNum + "");
                }
            }
        });
        textWatcher = 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) {
                String text = s.toString();
                if (canEdit && !TextUtils.isEmpty(text)) {
                    //不包含小数点，输入的长度大于1，且以0打头，将0截取
                    if (!text.contains(".")) {
                        if (text.length() > 1 && text.startsWith("0")) {
                            text = String.valueOf(Long.parseLong(text));
                            mNum.removeTextChangedListener(this);
                            mNum.setText(text);
                            mNum.addTextChangedListener(textWatcher);
                        }
                    }
                    try {
                        if (Long.parseLong(text) > maxNum) {
                            mNum.setText("" + maxNum);
                        }
                        mNum.setSelection(mNum.getText().length());
                        if (null != mListener) {
                            mListener.setCurrentNum(mNum.getText().toString());
                        }
                        if (Long.parseLong(mNum.getText().toString()) >= maxNum) {
                            mAdd.setImageResource(R.mipmap.plus_unclick);
                            mAdd.setEnabled(false);
                        } else {
                            mAdd.setImageResource(R.mipmap.plus);
                            mAdd.setEnabled(true);
                        }
                        if (Long.parseLong(mNum.getText().toString()) <= minNum) {
                            mMinus.setImageResource(R.mipmap.minus_unclick);
                            mMinus.setEnabled(false);
                        } else {
                            mMinus.setImageResource(R.mipmap.minus);
                            mMinus.setEnabled(true);
                        }
                    } catch (Exception e) {
                        mNum.setText(minNum + "");
                    }

                } else {
                    if (null != mListener) {
                        mListener.setCurrentNum(text);
                    }
                }
            }
        };
        mNum.addTextChangedListener(textWatcher);
    }

    /**
     * 设置最小数字
     *
     * @param minNum 最小数字
     * @return this
     */
    public CommonNumberControl setMinNum(int minNum) {
        this.minNum = minNum;
        mNum.setText(minNum + "");
        return this;
    }

    /**
     * 设置最大数字
     *
     * @param maxNum 最大数字
     * @return this
     */
    public CommonNumberControl setMaxNum(long maxNum) {
        this.maxNum = maxNum;
        return this;
    }

    public CommonNumberControl setMaxLength(int maxLength) {
        fArray[0] = new InputFilter.LengthFilter(maxLength);
        mNum.setFilters(fArray);
        return this;
    }

    public CommonNumberControl setText(String text) {
        mNum.setText(text);
        return this;
    }

    public String getText() {
        return mNum.getText().toString();
    }

    /**
     * 设置默认数字
     *
     * @param defaltNum 默认数字
     * @return this
     */
    public CommonNumberControl setDefaultNum(int defaltNum) {
        this.defaltNum = defaltNum;
        return this;
    }

    public String getCurrentNum() {
        return mNum.getText().toString();
    }

    private onCommonNumberControlListener mListener;

    public CommonNumberControl setEditTextListener(onCommonNumberControlListener listener) {
        mListener = listener;
        return this;
    }

    public EditText getEditText() {
        return mNum;
    }

    public CommonNumberControl setCurrentNum(String num) {
        mNum.setText(num);
        return this;
    }

    public void setSelection(int length) {
        mNum.setSelection(length);
    }

    public void canEdit(boolean canEdit) {
        this.canEdit = canEdit;
        mNum.setEnabled(canEdit);
        if (canEdit) {
            mNum.setBackground(getResources().getDrawable(R.drawable.bg_rect_stroke_gray_top_bottom));
            mAdd.setVisibility(VISIBLE);
            mMinus.setVisibility(VISIBLE);
        } else {
            mNum.setBackground(getResources().getDrawable(R.color.white_ffffff));
            mAdd.setVisibility(GONE);
            mMinus.setVisibility(GONE);
        }
    }

    public void setShowPop(boolean showPop) {
        isShowPop = showPop;
        setListener();
    }

    public interface onCommonNumberControlListener {
        void setCurrentNum(String num);
    }

    /**
     * 点击显示数字控制器的弹窗
     */
    public interface OnShowDialogListener {
        void onShowDialog();
    }

    private OnShowDialogListener onShowDialogListener;

    public CommonNumberControl setOnShowDialogListener(OnShowDialogListener onShowDialogListener) {
        this.onShowDialogListener = onShowDialogListener;
        return this;
    }

    /**
     * 设置点击中间的editeText是处于编辑状态 还是 弹dialog再编辑
     */
    private void setListener() {
        if (isShowPop) {
            mNum.setFocusable(false);
            mNum.setOnClickListener(v -> {
                if (null != onShowDialogListener) {
                    onShowDialogListener.onShowDialog();
                }
            });
        } else {
            mNum.setFocusable(true);
            mNum.setOnFocusChangeListener((v, hasFocus) -> {
                if (!hasFocus) {
                    if (TextUtils.isEmpty(mNum.getText().toString())) {
                        mNum.setText(minNum + "");
                    }
                    if (Double.parseDouble(mNum.getText().toString()) < minNum) {
                        mNum.setText(minNum + "");
                    }
                }
            });
        }
    }
}
