package cn.muchinfo.rma.view.autoWidget.view;

import android.content.Context;
import android.content.res.TypedArray;
import android.text.Editable;
import android.text.TextWatcher;
import android.text.method.DigitsKeyListener;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageButton;

import com.blankj.utilcode.util.SPUtils;

import cn.muchinfo.rma.R;
import cn.muchinfo.rma.view.autoWidget.utils.NumberUtils;

/**
 * 输入框带 "+"、"-"号的
 * 资管的  样式不一样
 */
public class MangeNumberEditText2 extends FrameLayout implements View.OnClickListener {

    //region views
    private View view;
    private ImageButton p_sub;
    private ImageButton p_add;
    private EditText p_number;
    //endregion

    //region 数据
    private OnTextChangeListener onTextChangeListener;
    private OnTextChangedListener onTextChangedListener;
    private OnTextChangeBeforListener onTextChangeBeforListener;
    private int decimal = 0;
    private double step = 1;
    private double min;
    private double max;
    private double changeValue = 0;
    private boolean cll = false; // true，会自动去hint的值进行赋值
    private boolean canSubOrAdd = true;//为true时可以对加减号进行操作，false时不行
    //endregion
    private boolean isAddOrSub = false;//是否点击了增加减少

    public double getChangeValue() {
        return changeValue;
    }

    public void setChangeValue(double changeValue) {
        this.changeValue = changeValue;
    }

    public double getStep() {
        return step;
    }

    public void setStep(double step) {
        this.step = step;
    }

    public int getDecimal() {
        return decimal;
    }

    public void setDecimal(int decimal) {
        this.decimal = decimal;
    }

    public boolean isCanSubOrAdd() {
        return canSubOrAdd;
    }

    public void setCanSubOrAdd(boolean canSubOrAdd) {
        this.canSubOrAdd = canSubOrAdd;
    }

    private Context mContext;

    public MangeNumberEditText2(Context context) {
        super(context);
        this.mContext = context;
        init();
    }

    public MangeNumberEditText2(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.mContext = context;
        init();
    }

    public MangeNumberEditText2(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        this.mContext = context;
        init1(attrs, defStyleAttr);
        init();
    }

    public MangeNumberEditText2(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        this.mContext = context;
        init1(attrs, defStyleAttr);
        init();
    }

    private void init1(AttributeSet attrs, int defStyleAttr) {
        TypedArray a = mContext.getTheme().obtainStyledAttributes(attrs, R.styleable.MangeNumberEditText, defStyleAttr, 0);
        String digits = a.getString(R.styleable.MangeNumberEditText_digits);
        if (digits != null) {
            p_number.setKeyListener(DigitsKeyListener.getInstance(digits));
        }
    }

    public void setOnTextChangeListener(OnTextChangeListener onTextChangeListener) {
        this.onTextChangeListener = onTextChangeListener;
    }

    public OnTextChangeBeforListener getOnTextChangeBeforListener() {
        return onTextChangeBeforListener;
    }

    public void setOnTextChangeBeforListener(OnTextChangeBeforListener onTextChangeBeforListener) {
        this.onTextChangeBeforListener = onTextChangeBeforListener;
    }


    /**
     * 实例化
     */
    private void init() {
        view = LayoutInflater.from(getContext()).inflate(R.layout.manage_number_edittext2, null);
        p_sub = view.findViewById(R.id.p_sub);
        p_add = view.findViewById(R.id.p_add);
        p_number = view.findViewById(R.id.p_number);
        p_number.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                if(onTextChangeBeforListener != null){
                    onTextChangeBeforListener.onTextChanged(view, s.toString());
                }
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (NumberUtils.isNumeric(s.toString())) {

                    if ("-".equals(s.toString())) {
                        s = "";
                    }
                    /*if (!s.toString().matches("^[-\\+]?[.\\d]*$")){
                        return;
                    }*/
                    //region 畸形矫正
                    if (decimal == 0) {
                        if (s.toString().startsWith(".")) {
                            p_number.setText("0");
                            p_number.setSelection(p_number.getText().toString().length());
                            return;
                        }
                        if (s.toString().contains(".")) {
                            p_number.setText(s.toString().substring(0, s.toString().length() - 1));
                            p_number.setSelection(p_number.getText().toString().length());
                            return;
                        }
                    }
                    if (s.toString().startsWith(".")) {// 如果是.开头的话，就直接
                        p_number.setText("0.");
                        p_number.setSelection(p_number.getText().toString().length());
                        return;
                    }
                    if (s.toString().contains("..")) {// 不能重复输入两个
                        p_number.setText(s.toString().substring(0, s.toString().length() - 1));
                        p_number.setSelection(p_number.getText().toString().length());
                        return;
                    }
                    if (s.toString().endsWith(".")) {
                        if (s.toString().indexOf(".") != s.toString().length() - 1) {// 说明有2个哦
                            p_number.setText(s.toString().substring(0, s.toString().length() - 1));
                            p_number.setSelection(p_number.getText().toString().length());
                            return;
                        }
                    }
                    // 不能查过小数位数
                    int index = s.toString().indexOf(".");
                    if (index != -1 &&
                            s.toString().length() - index - 1 > decimal) {
                        p_number.setText(s.toString().substring(0, s.toString().length() - 1));
                        p_number.setSelection(p_number.getText().toString().length());
                        return;
                    }

                    if (max != 0 &&
                            !"".equals(s.toString())) {// 有值，才会处理
                        double currentNum = Double.parseDouble(s.toString());
                        if (currentNum > max) {
                            int endNum = (int) ((max / step) * step);// 去掉越界的部分
                            p_number.setText(String.valueOf(endNum));
                            p_number.setSelection(p_number.getText().toString().length());
                            return;
                        }
                    }

                    //endregion

                    if (onTextChangeListener != null) {
                        if(isCallBack) {
                            onTextChangeListener.onTextChange(view, s.toString());
                        }else{
                            isCallBack = true;
                        }
                    }
                }

            }

            @Override
            public void afterTextChanged(Editable s) {
                if(onTextChangedListener != null){
                    if(isAfterCallBack) {
                        onTextChangedListener.onTextChanged(view, s.toString());
                    }else{
                        isAfterCallBack = true;
                    }
                }
            }

        });
        addView(view);

        p_sub.setOnClickListener(this);
        p_add.setOnClickListener(this);

    }

    boolean isCallBack = true;
    boolean isAfterCallBack = true;
    public void setTextWithOnTextChangeBack(String text){
        this.setText(text);
        isCallBack = false;
        isAfterCallBack = false;
    }

    @Override
    public void onClick(View v) {

        if (isCanSubOrAdd()){//这里暂时是零边界只支持市价下单，所以加减价格的功能需要屏蔽掉
            if (mOnOperateListener != null) {
                mOnOperateListener.onOperate();
            }
            double de = Math.pow(10, -decimal);
            if(changeValue != 0){
                de = changeValue;
            }
            switch (v.getId()) {
                case R.id.p_sub:
                    operate(-de);
                    break;
                case R.id.p_add:
                    operate(de);
                    break;
            }
        }

    }

    private OnOperateListener mOnOperateListener;
    public interface OnOperateListener{
        void onOperate();
    }
    public void setOnOperateListener(OnOperateListener operateListener) {
        this.mOnOperateListener = operateListener;
    }


    /**
     * @param type
     */
    private void operate(double type) {
//        SPUtils.getInstance().put(Constent.ISCHANGEMSRKET,1);//1表示修改过价格可以进行价格模式进行修改
        String text = p_number.getText().toString().trim();
        /*if (!text.matches("^[-\\+]?[.\\d]*$")){
            return;
        }*/

        if (text.isEmpty()){
            p_number.setText("0");
        }
        if (NumberUtils.isNumeric(text)) {
            if (text.equals("")) {
                if (p_number.getHint() != null) {
                    if (!p_number.getHint().toString().equals("") && isCll()) {
                        p_number.setText(p_number.getHint().toString());
                        operate(type);
                    } else {
                        p_number.setText(String.valueOf(0));
                    }
                }

            } else {
                double _text = Double.parseDouble(text);
                if (_text < 0) {
                    p_number.setText(String.valueOf(0));
                } else {
                    if ((_text + type) > 0) {
                        p_number.setText(NumberUtils.roundNum(String.valueOf(_text + type), this.decimal));
                    } else {
                        p_number.setText("0");
                    }
                }
            }
        }

        p_number.setSelection(p_number.getText().toString().length());

    }

    public String getText() {
        if (p_number == null) {
            p_number = view.findViewById(R.id.p_number);
        }
        return p_number.getText().toString().trim();
    }

    public void setText(String text) {
        if (p_number == null) {
            p_number = view.findViewById(R.id.p_number);
        }
        if (text == null) {
            text = "";
        }
        if(text.equals("--")){
            text = "0";
        }
        if (NumberUtils.isNumeric(text)) {
            p_number.setText(NumberUtils.roundNum(text, this.decimal));
        } else {
            p_number.setText(text);
        }

    }

    /**
     * 输入框是否为空
     *
     * @return
     */
    public boolean isTextEmpty() {
        if (p_number == null) {
            return true;
        }
        return p_number.getText().toString().trim().equals("") ||
                p_number.getText().toString().trim().equals("null") ||
                Double.parseDouble(p_number.getText().toString().trim()) == 0;
    }

    public void setSelect(int a) {
        if (p_number.getText().toString().trim().length() < a) {
            a = p_number.getText().toString().trim().length();
        }
        p_number.setSelection(a);
    }

    public interface OnTextChangeListener {
        void onTextChange(View view, String value);
    }

    public interface OnTextChangedListener{
        void onTextChanged(View view, String value);
    }

    public interface OnTextChangeBeforListener{
        void onTextChanged(View view, String value);
    }

    /**
     * @param hint
     */
    public void setHintText(String hint) {
//        SpannableString ss = new SpannableString(hint);//定义hint的值
//        AbsoluteSizeSpan ass = new AbsoluteSizeSpan(15,true);//设置字体大小 true表示单位是sp
//        ss.setSpan(ass, 0, ss.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
//        p_number.setHint(new SpannedString(ss));
        p_number.setHint(hint);
    }

    @Override
    public void setEnabled(boolean enabled) {
        super.setEnabled(enabled);
        p_number.setEnabled(enabled);
        p_sub.setEnabled(enabled);
        p_add.setEnabled(enabled);

//        if (enabled) {
//            p_sub.setBackgroundResource(R.mipmap.p_sub);
//            p_add.setBackgroundResource(R.mipmap.p_add);
//        } else {
//            p_sub.setBackgroundResource(R.mipmap.p_sub_p);
//            p_add.setBackgroundResource(R.mipmap.p_add_p);
//        }

    }

    public double getMin() {
        return min;
    }

    public void setMin(double min) {
        this.min = min;
    }

    public double getMax() {
        return max;
    }

    public void setMax(double max) {
        this.max = max;
    }

    public OnTextChangedListener getOnTextChangedListener() {
        return onTextChangedListener;
    }

    public void setOnTextChangedListener(OnTextChangedListener onTextChangedListener) {
        this.onTextChangedListener = onTextChangedListener;
    }

    public boolean isCll() {
        return cll;
    }

    public void setCll(boolean cll) {
        this.cll = cll;
    }

    public EditText getP_number() {
        return p_number;
    }

    public void setP_number(EditText p_number) {
        this.p_number = p_number;
    }

    /*@Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        // 获取宽-测量规则的模式和大小
        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
        int widthSize = MeasureSpec.getSize(widthMeasureSpec);

        // 获取高-测量规则的模式和大小
        int heightMode = MeasureSpec.getMode(heightMeasureSpec);
        int heightSize = MeasureSpec.getSize(heightMeasureSpec);

        // 设置wrap_content的默认宽 / 高值
        // 默认宽/高的设定并无固定依据,根据需要灵活设置
        // 类似TextView,ImageView等针对wrap_content均在onMeasure()对设置默认宽 / 高值有特殊处理,具体读者可以自行查看
        int mWidth = 100;
        int mHeight = 80;

        // 当布局参数设置为wrap_content时，设置默认值
        if (getLayoutParams().width == ViewGroup.LayoutParams.WRAP_CONTENT && getLayoutParams().height == ViewGroup.LayoutParams.WRAP_CONTENT) {
            setMeasuredDimension(mWidth, mHeight);
            // 宽 / 高任意一个布局参数为= wrap_content时，都设置默认值
        } else if (getLayoutParams().width == ViewGroup.LayoutParams.WRAP_CONTENT) {
            setMeasuredDimension(mWidth, heightSize);
        } else if (getLayoutParams().height == ViewGroup.LayoutParams.WRAP_CONTENT) {
            setMeasuredDimension(widthSize, mHeight);
        }
    }*/
}
