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 AddAndReduceDoubleView extends LinearLayout implements View.OnClickListener {

    private final Button add;
    private final Button remove;
    private final TextView tvNum;
    private double num = 0;
    private double maxNum = 10000;


    public AddAndReduceDoubleView(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);
        tvNum.setText("0");
        add.setOnClickListener(this);
        remove.setOnClickListener(this);
    }

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

    public double getNumber() {
        return num;
    }

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

                break;
            case R.id.btn_reduce:
                if (num < 1) {
                    Toast.makeText(getContext(), "不能小于0", Toast.LENGTH_SHORT).show();
                } else {
                    num--;
                    tvNum.setText(num + "");
                    if (mOnNumberChangedListener != null)
                        mOnNumberChangedListener.OnNumberChanged(String.valueOf(num));
                }
                break;
        }
    }

    public double getMaxNum() {
        return maxNum;
    }

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

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

    private OnNumberChangedListener mOnNumberChangedListener;

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