package com.cooleshow.teacher.ui.income;

import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;

import androidx.annotation.Nullable;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.cooleshow.base.common.WebConstants;
import com.cooleshow.base.router.RouterPath;
import com.cooleshow.base.ui.activity.BaseMVPActivity;
import com.cooleshow.base.utils.ToastUtil;
import com.cooleshow.base.utils.ToastUtils;
import com.cooleshow.base.widgets.dialog.CommonDialog;
import com.cooleshow.teacher.R;
import com.cooleshow.teacher.bean.WithdrawalInfoBean;
import com.cooleshow.teacher.contract.WithdrawalContract;
import com.cooleshow.teacher.databinding.ActivityWithdrawalBinding;
import com.cooleshow.teacher.presenter.income.WithdrawalPresenter;

import java.text.DecimalFormat;

import io.rong.imkit.utils.StatusBarUtil;

/**
 * 创建日期：2022/5/23 17:29
 *
 * @author Ryan
 * 类说明：
 */
@Route(path = RouterPath.IncomeCenter.TEACHER_MINE_WITHDRAWAL)
public class WithdrawalActivity extends BaseMVPActivity<ActivityWithdrawalBinding, WithdrawalPresenter> implements WithdrawalContract.WithdrawalView, View.OnClickListener {

    private CommonDialog mCommonDialog;
    private CommonDialog mProtocolTipDialog;

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_right_text:
                ARouter.getInstance().build(RouterPath.IncomeCenter.TEACHER_MINE_WITHDRAWAL_RECORD)
                        .navigation();
                break;
            case R.id.tv_withdrawal_all:
                viewBinding.etPrice.setText(mWithdrawalInfo.amountWithdrawal + "");
                break;
            case R.id.tv_confirm_withdrawal:
                if (mWithdrawalInfo == null) {
                    return;
                }
                String amountWithdrawal = viewBinding.etPrice.getText().toString().trim();
                if (TextUtils.isEmpty(amountWithdrawal)) {
                    return;
                }
                if (Double.parseDouble(amountWithdrawal) <= mWithdrawalInfo.withdrawalServiceFee) {
                    ToastUtil.getInstance().showShort("结算金额需要大于手续费");
                    break;
                }
                if (null == mWithdrawalInfo.userBankCard) {
                    ToastUtil.getInstance().showShort("请先绑定银行卡");
                    ARouter.getInstance().build(RouterPath.MineCenter.MINE_MY_BANKCARD)
                            .navigation();
                    break;
                }


                presenter.userAccountPage(amountWithdrawal, mWithdrawalInfo.userBankCard.id + "");
                break;
        }
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        StatusBarUtil.setStatusBarDarkTheme(this, true);
    }

    @Override
    protected void initView() {
        initMidTitleToolBar(viewBinding.toolbarInclude.toolbar, "结算");
        viewBinding.toolbarInclude.tvRightText.setTextColor(getResources().getColor(com.cooleshow.base.R.color.common_black));
        viewBinding.toolbarInclude.tvRightText.setVisibility(View.VISIBLE);
        viewBinding.toolbarInclude.tvRightText.setText("结算记录");
        viewBinding.toolbarInclude.tvRightText.setOnClickListener(this);
        viewBinding.tvWithdrawalAll.setOnClickListener(this);
        viewBinding.tvConfirmWithdrawal.setOnClickListener(this);

        viewBinding.etPrice.addTextChangedListener(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) {
                //删除.后面超过两位的数字
                if (s.toString().contains(".")) {
                    if (s.length() - 1 - s.toString().indexOf(".") > 2) {
                        s = s.toString().subSequence(0,
                                s.toString().indexOf(".") + 3);
                        viewBinding.etPrice.setText(s);
                        viewBinding.etPrice.setSelection(s.length());
                    }
                }

                //如果.在起始位置,则起始位置自动补0
                if (s.toString().trim().substring(0).equals(".")) {
                    s = "0" + s;
                    viewBinding.etPrice.setText(s);
                    viewBinding.etPrice.setSelection(2);
                }

                //如果起始位置为0并且第二位跟的不是".",则无法后续输入
                if (s.toString().startsWith("0")
                        && s.toString().trim().length() > 1) {
                    if (!s.toString().substring(1, 2).equals(".")) {
                        viewBinding.etPrice.setText(s.subSequence(0, 1));
                        viewBinding.etPrice.setSelection(1);
                        return;
                    }
                }

                //不允许输入两个"."
                if (s.toString().trim().length() > 2) {
                    int firstIndex = s.toString().trim().indexOf(".");
                    int lastIndex = s.toString().trim().lastIndexOf(".");
                    if (lastIndex - firstIndex == 1) {
                        viewBinding.etPrice.setText(s.subSequence(0, lastIndex));
                        viewBinding.etPrice.setSelection(lastIndex);
                    }
                }
            }

            @Override
            public void afterTextChanged(Editable s) {
                String price = viewBinding.etPrice.getText().toString();
                if (TextUtils.isEmpty(price)) {
                    viewBinding.etPrice.setTextSize(20);
                } else {
                    viewBinding.etPrice.setTextSize(32);
                }

            }
        });
    }

    @Override
    protected ActivityWithdrawalBinding getLayoutView() {
        return ActivityWithdrawalBinding.inflate(getLayoutInflater());
    }

    @Override
    protected WithdrawalPresenter createPresenter() {
        return new WithdrawalPresenter();
    }


    @Override
    public void initData() {
        super.initData();

    }

    @Override
    protected void onResume() {
        super.onResume();
        if (presenter != null) {
            presenter.checkContractSign();
        }
    }

    private WithdrawalInfoBean mWithdrawalInfo;

    @Override
    public void getWithdrawalInfoSuccess(WithdrawalInfoBean data) {
        if (!checkActivityExist()) {
            return;
        }
        mWithdrawalInfo = data;
        viewBinding.tvAvailablePrice.setText("可结算余额 " + getTwoDecimal(data.amountWithdrawal));
        viewBinding.tvServiceFee.setText("单次收入结算时，平台将收取" + getTwoDecimal(data.withdrawalServiceFee) + "元手续费");
        if (null != data.userBankCard) {
            viewBinding.tvBankName.setText(data.userBankCard.bankName + getBankNum(data.userBankCard.bankCard));
            viewBinding.tvTip.setVisibility(View.VISIBLE);
        } else {
            viewBinding.tvBankName.setText("您未绑定银行卡");
            viewBinding.tvTip.setVisibility(View.INVISIBLE);
            showNotBindBankCardTip();
        }
    }

    private void showNotBindBankCardTip() {
        if (mCommonDialog == null) {
            mCommonDialog = new CommonDialog(this);
        }
        if (!mCommonDialog.isShowing()) {
            mCommonDialog.show();
        }
        mCommonDialog.setTitle("绑定银行卡");
        mCommonDialog.setContent("您需要先绑定银行卡后才能结算");
        mCommonDialog.setOnConfirmClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ARouter.getInstance().build(RouterPath.MineCenter.MINE_MY_BANKCARD)
                        .navigation();
            }
        });
        mCommonDialog.setOnCancelClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mCommonDialog != null) {
                    mCommonDialog.dismiss();
                }
            }
        });
    }

    private void showProtocolTipDialog() {
        if (mProtocolTipDialog == null) {
            mProtocolTipDialog = new CommonDialog(this);
            mProtocolTipDialog.setCanceledOnTouchOutside(false);
            mProtocolTipDialog.setCancelable(false);
        }
        if (!mProtocolTipDialog.isShowing()) {
            mProtocolTipDialog.show();
        }
        mProtocolTipDialog.setTitle("协议签署");
        mProtocolTipDialog.setContent("您需要先签署协议才能结算");
        mProtocolTipDialog.setOnConfirmClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mProtocolTipDialog.dismiss();
                ARouter.getInstance().build(RouterPath.WebCenter.ACTIVITY_HTML)
                        .withString(WebConstants.WEB_URL, WebConstants.PROTOCOL_SIGN_BY_TEACHER_WIYHDRAW)
                        .navigation();
            }
        });
        mProtocolTipDialog.setOnCancelClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mProtocolTipDialog != null) {
                    mProtocolTipDialog.dismiss();
                }
                finish();
            }
        });
    }

    private String getTwoDecimal(double num) {
        DecimalFormat df = new DecimalFormat("#,##0.00");
        String str = df.format(num);
        return str;

    }

    @Override
    public void doWithdrawalSuccess(Object o) {
        ARouter.getInstance().build(RouterPath.IncomeCenter.TEACHER_MINE_WITHDRAWAL_SUCCESS)
                .navigation();
        finish();
    }

    @Override
    public void checkContractSignResult(boolean result) {
        if (!checkActivityExist()) {
            return;
        }
        if (result) {
            presenter.getWithdrawalInfo();
        } else {
            showProtocolTipDialog();
        }
    }

    private String getBankNum(String num) {
        if (TextUtils.isEmpty(num)) {
            return "";
        }
        try {
            String substring = num.substring(num.length() - 8);
            return "(" + substring + ")";
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }
}
