package com.wd.workoffice.widget;

import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.wd.workoffice.R;

import flexible.xd.android_base.utils.ToastUtil;

public class AddAndReduceView extends LinearLayout implements View.OnClickListener {

    private final Button add;
    private final Button remove;
    private final TextView tvNum;
    private int num = 1;
    private int maxNum = 10000;


    public AddAndReduceView(Context context, AttributeSet attrs) {
        super(context, attrs);
        LayoutInflater.from(context).inflate(R.layout.view_add_remove, this);
        add = findViewById(R.id.btn_add);
        remove = findViewById(R.id.btn_reduce);
        tvNum = findViewById(R.id.tv_num);

        add.setOnClickListener(this);
        remove.setOnClickListener(this);
    }

    public void setNumber(int number) {
        num = number;
        tvNum.setText(number + "");
    }

    public int getNumber() {
        return num;
    }

    @Override
    public void onClick(View v) {
        String s = tvNum.getText().toString();
        num = Integer.parseInt(s);
        switch (v.getId()) {
            case R.id.btn_add:
                if (num == maxNum) {
                    ToastUtil.showShort("目前已选择最大数量");
                    return;
                }
                num++;
                tvNum.setText(num + "");
                if (mOnNumberChangedListener != null)
                    mOnNumberChangedListener.OnNumberChanged(num);

                break;
            case R.id.btn_reduce:
                if (num > 1) {
                    num--;
                    tvNum.setText(num + "");
                    if (mOnNumberChangedListener != null)
                        mOnNumberChangedListener.OnNumberChanged(num);
                    return;
                    //接口回调
                } else {
                    Toast.makeText(getContext(), "不能小于1", Toast.LENGTH_SHORT).show();
                }
                break;
        }
    }

    public int getMaxNum() {
        return maxNum;
    }

    public void setMaxNum(int maxNum) {
        this.maxNum = maxNum;
    }

    public interface OnNumberChangedListener {
        void OnNumberChanged(int vs);
    }

    private OnNumberChangedListener mOnNumberChangedListener;

    public void setOnNumberChangedListener(OnNumberChangedListener onNumberChangedListener) {
        mOnNumberChangedListener = onNumberChangedListener;
    }
}
