package com.android.chmo.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.InputFilter;
import android.text.Spanned;
import android.text.TextUtils;
import android.widget.EditText;
import android.widget.TextView;

import com.android.chmo.R;
import com.android.chmo.base.BaseActivity;
import com.android.chmo.http.RequestCallback;
import com.android.chmo.http.response.WithdrawResponse;
import com.android.chmo.http.service.PayService;
import com.google.gson.Gson;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import butterknife.BindView;
import butterknife.OnClick;

public class WithdrawActivity extends BaseActivity {
    @BindView(R.id.et_name)
    EditText etName;
    @BindView(R.id.et_account)
    EditText etAccount;
    @BindView(R.id.et_amount)
    EditText etAmount;
    @BindView(R.id.tv_available)
    TextView tvAvailable;

    private double availableAmount;

    public static void open(Context context, double availableAmount) {
        Intent intent = new Intent(context, WithdrawActivity.class);
        intent.putExtra("availableAmount", availableAmount);
        context.startActivity(intent);
    }

    @Override
    protected int getContentResId() {
        return R.layout.activity_withdraw;
    }

    @Override
    public void initView() {
        availableAmount = getIntent().getDoubleExtra("availableAmount", 0);
        tvAvailable.setText("最多可提现" + availableAmount + "元");
        etAmount.setFilters(new InputFilter[]{(source, start, end, dest, dstart, dend) -> {
            String sourceText = source.toString();
            String destText = dest.toString();
            //验证删除等按键
            if (TextUtils.isEmpty(sourceText)) {
                return "";
            }
            Pattern mPattern = Pattern.compile("([0-9]|\\.)*");
            Matcher matcher = mPattern.matcher(source);
            // 已经输入小数点的情况下，只能输入数字
            if (destText.contains(".")) {
                if (!matcher.matches()) {
                    return "";
                } else {
                    if (".".contentEquals(source)) {  //只能输入一个小数点
                        return "";
                    }
                }
                double sumText = Double.parseDouble(destText + sourceText);
                if (sumText > 10000) {
                    return dest.subSequence(dstart, dend);
                }
                //验证小数点精度，保证小数点后只能输入2位
                int index = destText.indexOf(".");
                int length = dend - index;
                if (dest.toString() != null && dest.toString().length() > 0 && dest.toString().contains(".")) {
                    String[] amoArr = (dest.toString()).split("\\.");
                    int indexPoint = dest.toString().indexOf(".");
                    if (dstart <= indexPoint) {
                        if (dend > 0) {
                            String temp = amoArr[0].substring(0, dend - 1) + sourceText + amoArr[0].substring(dend - 1, amoArr[0].length());
                            if (Double.parseDouble(temp) > 10000) {
                                return "";
                            }
                        }
                    } else if (amoArr.length > 1 && amoArr[amoArr.length - 1].length() >= 2) {
                        return "";
                    }
                }
                if (length > 10) {
                    return dest.subSequence(dstart, dend);
                }
            } else { // 还没有输入小数点.的情况
                if (".".contentEquals(source) && dest.toString().length() == 0) {
                    return "0.";
                } else {
                    if (dest.toString() != null && dest.toString().length() > 0) {
                        double sumDou = Double.parseDouble(dest.toString());
                        if (sumDou > 10000) {
                            return "";
                        }
                    }
                    String[] amoArr = (dest.toString()).split("\\.");
                    int indexPoint = dest.toString().indexOf(".");
                    if (dstart <= indexPoint) {
                        if (dest.toString() != null && dest.toString().length() > 0) {
                            double sumDou = Double.parseDouble(dest.toString());
                            if (sumDou > 10000) {
                                return dest.subSequence(dstart, dend);
                            }
                        }
                    } else if (amoArr.length > 1 && amoArr[amoArr.length - 1].length() >= 2) {
                        return "";
                    } else if (".".contentEquals(source) && dest.toString().length() - dstart > 2) {
                        return "";
                    }
                }
            }
            if ((destText + sourceText).length() > 10) {
                return dest.subSequence(dstart, dend);
            }
            //验证输入金额的大小
            double sumText = Double.parseDouble(destText + sourceText);
            if (sumText > 10000) {
                return dest.subSequence(dstart, dend);
            }
            return dest.subSequence(dstart, dend) + sourceText;
        }});
    }

    @OnClick(R.id.btn_submit)
    void onClick() {
        if (TextUtils.isEmpty(etName.getText())) {
            showToast("请输入姓名");
        } else if (TextUtils.isEmpty(etAccount.getText())) {
            showToast("请输入支付宝账号");
        } else if (TextUtils.isEmpty(etAmount.getText())) {
            showToast("请输入提现金额");
        } else {
            try {
                double fee = Double.parseDouble(etAmount.getText().toString());
                String name = etName.getText().toString();
                String account = etAccount.getText().toString();
                if (fee <= 0) {
                    showToast("请输入正确的提现金额");
                } else if (fee > availableAmount) {
                    showToast("最多可提现" + availableAmount + "元");
                } else {
                    showLoading();
                    PayService.withdraw(String.valueOf(fee), name, account, new RequestCallback() {
                        @Override
                        public void onSuccess(String result) {
                            hideLoading();
                            WithdrawResponse response = new Gson().fromJson(result, WithdrawResponse.class);
                            if ("success".equals(response.getMsg())) {
                                openPage(WithdrawSuccessActivity.class);
                                finish();
                            } else {
                                showToast("提交失败，请稍后再试");
                            }
                        }

                        @Override
                        public void onFailure(String error) {
                            hideLoading();
                            showToast("提交失败，请稍后再试");
                        }
                    });
                }
            } catch (Exception e) {
                showToast("请输入正确的提现金额");
            }
        }
    }

}
