package com.xxrv.wallet.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.alibaba.android.arouter.launcher.ARouter;
import com.frame.base.bus.RxBus;
import com.frame.base.url.Constance;
import com.frame.rv.config.RvFrameConfig;
import com.ruiwenliu.wrapper.base.BaseBean;
import com.ruiwenliu.wrapper.base.BaseStatusActivity;
import com.ruiwenliu.wrapper.util.ViewHolder;
import com.ruiwenliu.wrapper.weight.TitleView;
import com.rv.home.rv.module.ApiConfig;
import com.xxrv.wallet.R;
import com.xxrv.wallet.R2;
import com.xxrv.wallet.api.WalletApi;
import com.xxrv.wallet.bean.AlipayListBean;
import com.xxrv.wallet.bean.CheckAmountBean;
import com.xxrv.wallet.bean.WithdrawBean;
import com.xxrv.wallet.bean.WithdrawalRulesBean;
import com.xxrv.wallet.dialog.PayPassDialog;
import com.xxrv.wallet.dialog.VerifyAccountHintDialog;
import com.frame.base.bus.WithdrawSuccessEvent;
import com.xxrv.wallet.presenter.WalletPresenter;
import com.xxrv.wallet.view.PayPassView;
import com.yuyife.okgo.OkGoUtil;

import java.util.LinkedHashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 提现
 */
public class WithdrawActivity extends BaseStatusActivity<WalletPresenter> {

    @BindView(R2.id.et_account_number)
    EditText etAccountNumber;
    @BindView(R2.id.et_withdrawal_amount)
    EditText etWithdrawalAmount;
    @BindView(R2.id.tv_hint)
    TextView tvHint;

    private String accountNumber;
    private String withdrawalAmount;


    public static Intent getIntent(Context context, String balance) {
        return new Intent(context, WithdrawActivity.class)
                .putExtra("balance", balance);
    }

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

    @Override
    protected void initView(Bundle savedInstanceState, TitleView titleView, Intent intent) {
        titleView.setTitle("提现");
        tvHint.setText("当前账户余额"+intent.getStringExtra("balance")+"元");
    }

    @Override
    protected void loadData(Bundle savedInstanceState, Intent intent) {
        super.loadData(savedInstanceState, intent);
        getAliPayList();
        getWithdrawalRules();
    }

    /**
     * 提现规则
     */
    private void getWithdrawalRules() {
        Map<String, Object> headMap = new LinkedHashMap<>();
        if (OkGoUtil.getToken() != null)
            headMap.put("Authorization", OkGoUtil.getToken());
        mPresenter.getDataHead(RvFrameConfig.HOST, 2, WalletApi.HTTP_URL_WALLET_RULE, WithdrawalRulesBean.class, headMap, true);
    }

    /**
     * 获取支付账号列表
     */
    private void getAliPayList() {
        Map<String, Object> headMap = new LinkedHashMap<>();
        if (OkGoUtil.getToken() != null)
            headMap.put("Authorization", OkGoUtil.getToken());
        mPresenter.getDataHead(RvFrameConfig.HOST, 1, WalletApi.HTTP_URL_WALLET_WXAPLIPAYLIST, AlipayListBean.class, headMap, true);
    }

    @Override
    public void onShowResult(int requestType, BaseBean result) {
        switch (requestType) {
            case 1:
                getAlipay((AlipayListBean) result);
                break;
            case 2:
                setWithdrawalRules((WithdrawalRulesBean) result);
                break;
            case 3:
                setCheckWithdraw((CheckAmountBean) result);
                break;
            case 4:
                WithdrawBean bean = (WithdrawBean) result;
                if (bean !=null){
                    startActivity(CashWithdrawalDetailsActivity.getIntent(mActivity,String.valueOf(bean.getData())));
                    RxBus.post(new WithdrawSuccessEvent());
                    finish();
                }

                break;
        }
    }

    /**
     * 检查提现下一步操作
     *
     * @param bean
     */
    private void setCheckWithdraw(CheckAmountBean bean) {
        new VerifyAccountHintDialog(mActivity) {
            @Override
            public void helper(ViewHolder helper) {
                super.helper(helper);
                helper.setText(R.id.tv_pay_amount, withdrawalAmount + "元");
                helper.setText(R.id.tv_account_number, accountNumber);
                helper.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        int id = v.getId();
                        if (id == R.id.tv_item_ok) {
                            payDialog();
                            dismiss();
                        } else if (id == R.id.tv_item_cancel) {
                            dismiss();
                        }
                    }
                }, R.id.tv_item_ok, R.id.tv_item_cancel);
            }
        }.show();
    }

    /**
     * 提现规则
     *
     * @param bean
     */
    private void setWithdrawalRules(WithdrawalRulesBean bean) {
        if (bean.getData() != null) {
            etWithdrawalAmount.setHint("提现金额至少" + bean.getData().getMinAmount() + "元，单笔限额 " + bean.getData().getAmountOfDay() + "万");
        }
    }

    private void getAlipay(AlipayListBean bean) {
        if (bean.getData() != null && bean.getData().size() > 0) {
            etAccountNumber.setText(bean.getData().get(0).getTxAlipay());
            etAccountNumber.setSelection(bean.getData().get(0).getTxAlipay().length());
        }
    }

    @OnClick({R2.id.tv_item_withdraw, R2.id.tv_item_withdrawal_rules})
    public void onViewClicked(View view) {
        int id = view.getId();
        if (id == R.id.tv_item_withdraw) {
            //提现
            showHint();

        } else if (id == R.id.tv_item_withdrawal_rules) {
            //提现规则
            ARouter.getInstance().build(Constance.ACTIVITY_URL_WEBVIEW)
                    .withString("title", "提现规则")
                    .withString("url", ApiConfig.HTTP_URL_CAR_TYPE_NOTICE)
                    .withInt("type", 20)
                    .navigation();
        }
    }

    /**
     * 提现
     */
    private void showHint() {
        accountNumber = etAccountNumber.getText().toString().trim();
        if (TextUtils.isEmpty(accountNumber)) {
            showToast("账户不能为空！");
            return;
        }

        withdrawalAmount = etWithdrawalAmount.getText().toString().trim();
        if (TextUtils.isEmpty(withdrawalAmount)) {
            showToast("提现金额不能为空！");
            return;
        }

        checkWithdraw();
    }

    /**
     * 支付密码
     */
    private void payDialog() {
        final PayPassDialog payPassDialog = new PayPassDialog(this);
        payPassDialog.setOutColse(false);
        payPassDialog.getPayViewPass().setPayClickListener(new PayPassView.OnPayClickListener() {
            @Override
            public void onPassFinish(String passContent) {
                //输入完成
//                showToast("提现成功！");
                setWithdraw(passContent);
                payPassDialog.dismiss();
            }


            @Override
            public void onPayClose() {
                payPassDialog.dismiss();
            }

            @Override
            public void onPayForget() {
                //忘记密码
                payPassDialog.dismiss();
            }
        });
    }

    /**
     * 提现检查
     */
    private void checkWithdraw() {
        Map<String, Object> headMap = new LinkedHashMap<>();
        if (OkGoUtil.getToken() != null)
            headMap.put("Authorization", OkGoUtil.getToken());

        Map<String, Object> map = new LinkedHashMap<>();
        map.put("amount", withdrawalAmount);
        mPresenter.getData(RvFrameConfig.HOST, 3, WalletApi.HTTP_URL_WALLET_CHECKAMOUNT, CheckAmountBean.class, map, headMap, true);
    }


    /**
     * 钱包提现
     */
    private void setWithdraw(String passContent) {
        Map<String, Object> headMap = new LinkedHashMap<>();
        if (OkGoUtil.getToken() != null)
            headMap.put("Authorization", OkGoUtil.getToken());
        mPresenter.postBodyData(RvFrameConfig.VEHICLE_ORDER, 4, WalletApi.HTTP_URL_WALLET_APPLYCATH, WithdrawBean.class, new Withdraw(withdrawalAmount, passContent, accountNumber, "1"), headMap, true);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    private class Withdraw {
        private String amount;
        private String password;
        private String accountNumber;
        private String cathType;

        public Withdraw(String amount, String password, String accountNumber, String cathType) {
            this.amount = amount;
            this.password = password;
            this.accountNumber = accountNumber;
            this.cathType = cathType;
        }

        public String getAmount() {
            return amount;
        }

        public void setAmount(String amount) {
            this.amount = amount;
        }

        public String getPassword() {
            return password;
        }

        public void setPassword(String password) {
            this.password = password;
        }

        public String getAccountNumber() {
            return accountNumber;
        }

        public void setAccountNumber(String accountNumber) {
            this.accountNumber = accountNumber;
        }

        public String getCathType() {
            return cathType;
        }

        public void setCathType(String cathType) {
            this.cathType = cathType;
        }
    }
}
