package com.xxrv.wallet.activity;

import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.android.arouter.launcher.ARouter;
import com.alipay.sdk.app.AuthTask;
import com.frame.base.bus.RxBus;
import com.frame.base.bus.WithdrawSuccessEvent;
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.util.listener.TextChangedListener;
import com.ruiwenliu.wrapper.weight.TitleView;
import com.rv.component.utils.IsAppInstall;
import com.rv.home.rv.module.ApiConfig;
import com.umeng.socialize.UMAuthListener;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.utils.SocializeUtils;
import com.xxrv.wallet.R;
import com.xxrv.wallet.R2;
import com.xxrv.wallet.api.WalletApi;
import com.xxrv.wallet.bean.AccountNumberListBean;
import com.xxrv.wallet.bean.AuthResult;
import com.xxrv.wallet.bean.CheckAmountBean;
import com.xxrv.wallet.bean.WalletAuthInfoBean;
import com.xxrv.wallet.bean.WithdrawBean;
import com.xxrv.wallet.bean.WithdrawalRulesBean;
import com.xxrv.wallet.dialog.AccountTypeSelectionDialog;
import com.xxrv.wallet.dialog.PayPassDialog;
import com.xxrv.wallet.dialog.VerifyAccountHintDialog;
import com.xxrv.wallet.presenter.WalletPresenter;
import com.xxrv.wallet.view.PayPassView;
import com.yuyife.okgo.OkGoUtil;

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

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

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


    @BindView(R2.id.et_withdrawal_amount)
    EditText etWithdrawalAmount;
    @BindView(R2.id.tv_hint)
    TextView tvHint;
    @BindView(R2.id.iv_account_number_icon)
    ImageView ivAccountNumberIcon;
    @BindView(R2.id.tv_account_number)
    TextView tvAccountNumber;
    @BindView(R2.id.tv_item_withdraw)
    TextView tvItemWithdraw;

    private String withdrawalAmount;
    private List<AccountNumberListBean.DataBean> accountNumberList;
    private AccountNumberListBean.DataBean selectAccountNumber;
    private String balance;
    private WithdrawalRulesBean.DataBean rulesData;
    private boolean isType;
    private static final int SDK_AUTH_FLAG = 2;
    public ProgressDialog dialog;
    private AccountTypeSelectionDialog accountTypeSelectionDialog;

    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("提现");

        balance = intent.getStringExtra("balance");
        tvHint.setText("当前账户余额" + balance + "元");

        dialog = new ProgressDialog(this);
        etWithdrawalAmount.addTextChangedListener(new TextChangedListener() {
            @Override
            public void afterTextChanged(Editable s) {
                super.afterTextChanged(s);
                String withdrawalAmount = etWithdrawalAmount.getText().toString();
                if (rulesData == null) {
                    return;
                }
                if (withdrawalAmount.length() > 0) {
                    tvItemWithdraw.setEnabled(true);
                    tvItemWithdraw.setSelected(true);

                    if (Double.valueOf(withdrawalAmount) > Double.valueOf(balance)) {
                        tvHint.setText("提现金额不能超过账户余额，当前账户余额" + balance + "元");
                        tvHint.setTextColor(getResources().getColor(R.color.colorBg));
                    } else if (Double.valueOf(withdrawalAmount) < rulesData.getMinAmount()) {
                        tvHint.setText("提现金额不能低于" + rulesData.getMinAmount() + "元，当前账户余额" + balance + "元");
                        tvHint.setTextColor(getResources().getColor(R.color.colorBg));
                    } else if (Double.valueOf(withdrawalAmount) > rulesData.getAmountOfDay()) {
                        tvHint.setText("提现金额不能大于" + rulesData.getAmountOfDay() + "元，当前账户余额" + balance + "元");
                        tvHint.setTextColor(getResources().getColor(R.color.colorBg));
                    } else {
                        tvHint.setText("当前账户余额" + balance + "元");
                        tvHint.setTextColor(getResources().getColor(R.color.textGray));
                    }

                } else {
                    tvItemWithdraw.setEnabled(false);
                    tvItemWithdraw.setSelected(false);

                    tvHint.setText("当前账户余额" + balance + "元");
                    tvHint.setTextColor(getResources().getColor(R.color.textGray));
                }
            }
        });
    }

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

    private void getAccountNumber() {
        Map<String, Object> headMap = new LinkedHashMap<>();
        if (OkGoUtil.getToken() != null)
            headMap.put("Authorization", OkGoUtil.getToken());
        mPresenter.getDataHead(RvFrameConfig.HOST, 5, WalletApi.HTTP_URL_WALLET_ACCOUNT_NUMBER, AccountNumberListBean.class, headMap, false);

    }

    /**
     * 提现规则
     */
    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);
    }

    @Override
    public void onShowError(String errorMsg, int errorType) {
        super.onShowError(errorMsg, errorType);
        tvHint.setText(errorMsg + "，当前账户余额" + balance + "元");
        tvHint.setTextColor(getResources().getColor(R.color.colorBg));
    }

    @Override
    public void onShowResult(int requestType, BaseBean result) {
        switch (requestType) {
            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()), selectAccountNumber.getNickname(), withdrawalAmount));
                    RxBus.post(new WithdrawSuccessEvent());
                    finish();
                }
                break;
            case 5:
                AccountNumberListBean bean2 = (AccountNumberListBean) result;
                accountNumberList = bean2.getData();
                setAccountNumber(bean2);
                break;
            case 6:
                alipayAuthV2((WalletAuthInfoBean) result);
                break;
            case 7:
                getAccountNumber();
                if (accountTypeSelectionDialog != null) {
                    accountTypeSelectionDialog.dismiss();
                }
                selectShow();
                break;
        }
    }

    /**
     * 设置帐号信息
     *
     * @param result
     */
    private void setAccountNumber(AccountNumberListBean result) {
        if (result != null && result.getData() != null && result.getData().size() > 0) {
            for (int i = 0; i < result.getData().size(); i++) {
                if (1 == result.getData().get(i).getType()) {
                    AccountNumberListBean.DataBean dataBean = result.getData().get(0);
                    selectAccountNumber = dataBean;
                    dataBean.setCheck(true);
                    if (dataBean.getType() == 1) { //1支付宝  2微信
                        ivAccountNumberIcon.setImageResource(R.drawable.common_icon_wallet_alipay_small);
                        tvAccountNumber.setText("支付宝余额(" + dataBean.getNickname() + ")");
                    } else if (dataBean.getType() == 2) {
                        ivAccountNumberIcon.setImageResource(R.drawable.common_icon_wallet_weiwx_small);
                        tvAccountNumber.setText("微信零钱(" + dataBean.getNickname() + ")");
                    }
                    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 + "元");
                if (selectAccountNumber != null) {
                    helper.setText(R.id.tv_account_number, selectAccountNumber.getNickname());
                }
                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) {
            rulesData = bean.getData();
            etWithdrawalAmount.setHint("提现金额至少" + bean.getData().getMinAmount() + "元，单笔限额 " + bean.getData().getAmountOfDay() + "元");
        }
    }


    @OnClick({R2.id.tv_item_withdraw, R2.id.tv_item_withdrawal_rules, R2.id.ll_item_select_account_number})
    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();
        } else if (id == R.id.ll_item_select_account_number) {
//            selectShow();
        }
    }

    /**
     * 选择帐号
     */
    private void selectShow() {
        accountTypeSelectionDialog = new AccountTypeSelectionDialog(mActivity) {
            @Override
            public void helper(final ViewHolder helper) {
                super.helper(helper);
                if (accountNumberList != null && accountNumberList.size() > 0) {
                    AccountNumberListBean.DataBean dataBean1 = accountNumberList.get(0);
                    if (dataBean1.getType() == 1) {
                        isType = false;
                        helper.setText(R.id.tv_name1, "支付宝余额(" + dataBean1.getNickname() + ")");
                        helper.setImageResource(R.id.iv_icon1, R.drawable.common_icon_wallet_alipay);
                        helper.setText(R.id.tv_name3, "添加微信提现，绑定微信");
                    } else if (dataBean1.getType() == 2) {
                        helper.setText(R.id.tv_name1, "微信零钱(" + dataBean1.getNickname() + ")");
                        helper.setImageResource(R.id.iv_icon1, R.drawable.common_icon_wallet_weiwx);
                        helper.setText(R.id.tv_name3, "添加支付宝提现，绑定支付宝");
                        isType = true;
                    }

                    ImageView select1 = (ImageView) helper.getView(R.id.iv_select1);
                    if (dataBean1.getCheck()) {
                        select1.setSelected(true);
                    } else {
                        select1.setSelected(false);
                    }

                    helper.setVisible(R.id.ll_item_select2, false);
                    helper.setVisible(R.id.ll_item_select3, true);

                    if (accountNumberList.size() > 1) {
                        helper.setVisible(R.id.ll_item_select2, true);
                        helper.setVisible(R.id.ll_item_select3, false);
                        AccountNumberListBean.DataBean dataBean2 = accountNumberList.get(1);
                        if (dataBean2.getType() == 1) {
                            helper.setText(R.id.tv_name2, "支付宝余额(" + dataBean2.getNickname() + ")");
                            helper.setImageResource(R.id.iv_icon2, R.drawable.common_icon_wallet_alipay);
                        } else if (dataBean2.getType() == 2) {
                            helper.setText(R.id.tv_name2, "微信零钱(" + dataBean2.getNickname() + ")");
                            helper.setImageResource(R.id.iv_icon2, R.drawable.common_icon_wallet_weiwx);
                        }

                        ImageView select2 = (ImageView) helper.getView(R.id.iv_select2);
                        if (dataBean2.getCheck()) {
                            select2.setSelected(true);
                        } else {
                            select2.setSelected(false);
                        }

                    }
                }

                helper.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        int id = v.getId();
                        AccountNumberListBean.DataBean dataBean = null;
                        if (id == R.id.iv_close) {
                            dismiss();
                        } else if (id == R.id.ll_item_select1) {
                            dataBean = accountNumberList.get(0);
                            ImageView select = (ImageView) helper.getView(R.id.iv_select1);
                            if (dataBean.getCheck()) {
                                select.setSelected(true);
                            } else {
                                select.setSelected(false);
                            }
                        } else if (id == R.id.ll_item_select2) {
                            dataBean = accountNumberList.get(1);
                            ImageView select = (ImageView) helper.getView(R.id.iv_select2);
                            if (dataBean.getCheck()) {
                                select.setSelected(true);
                            } else {
                                select.setSelected(false);
                            }
                        } else if (id == R.id.ll_item_select3) {
                            if (isType) {
                                //绑定支付宝
                                getAuthInfo();

                            } else {

                                //绑定微信
                                if (!IsAppInstall.isWeixinAvilible(mActivity)) {
                                    showToast("亲，您微信还没有安装呢");
                                    return;
                                }
                                bindThirdParty(SHARE_MEDIA.WEIXIN);

                            }
                        } else if (id == R.id.tv_ok) {
                            selectAccountNumber = dataBean;
                            dismiss();
                        }
                    }
                }, R.id.iv_close, R.id.ll_item_select1, R.id.ll_item_select2, R.id.ll_item_select3, R.id.tv_ok);
            }
        };
        if (accountTypeSelectionDialog != null) {
            accountTypeSelectionDialog.show();
        }
    }

    private void bindThirdParty(SHARE_MEDIA share_media) {
        UMShareAPI.get(mActivity).getPlatformInfo(mActivity, share_media, this);
    }

    private void getAuthInfo() {
        Map<String, Object> map = new LinkedHashMap<>();
        map.put("apiName", "com.xinxin.rv");
        map.put("appName", "滴房车");
        mPresenter.getData(RvFrameConfig.HOST, 6, WalletApi.HTTP_URL_WALLET_UNAUTH_GETPARAM, WalletAuthInfoBean.class, map, false);
    }

    /**
     * 提现
     */
    private void showHint() {

        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() {
                //忘记密码
                startActivity(SetPayPwdActivity.getIntent(mActivity, 1));
                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, selectAccountNumber.getTxAlipay(), selectAccountNumber.getNickname(), "1"), headMap, true);
    }


    /**
     * 支付宝授权
     */
    private void alipayAuthV2(final WalletAuthInfoBean bean) {

        Runnable authRunnable = new Runnable() {
            @Override
            public void run() {
                // 构造AuthTask 对象
                AuthTask authTask = new AuthTask(WithdrawActivity.this);
                // 调用授权接口，获取授权结果
                Map<String, String> result = authTask.authV2(bean.getData(), true);

                Message msg = new Message();
                msg.what = SDK_AUTH_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };

        // 必须异步调用
        Thread authThread = new Thread(authRunnable);
        authThread.start();
    }


    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_AUTH_FLAG: {
                    @SuppressWarnings("unchecked")
                    AuthResult authResult = new AuthResult((Map<String, String>) msg.obj, true);
                    String resultStatus = authResult.getResultStatus();
                    // 判断resultStatus 为“9000”且result_code
                    // 为“200”则代表授权成功，具体状态码代表含义可参考授权接口文档
                    if (TextUtils.equals(resultStatus, "9000") && TextUtils.equals(authResult.getResultCode(), "200")) {
                        // 传入，则支付账户为该授权账户
                        putAlipayCode(authResult.getAuthCode());
                        showToast("授权成功！");
                    } else {
                        // 其他状态值则为授权失败
                    }
                    break;
                }
                default:
                    break;
            }
        }
    };

    private void putAlipayCode(String code) {
        Map<String, Object> headMap = new LinkedHashMap<>();
        if (OkGoUtil.getToken() != null)
            headMap.put("Authorization", OkGoUtil.getToken());
        Map<String, Object> map = new LinkedHashMap<>();
        map.put("code", code);
        mPresenter.getData(RvFrameConfig.HOST, 7, WalletApi.HTTP_URL_WALLET_ALIPAY_GETUSERINFO, BaseBean.class, map, headMap, false);

    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ButterKnife.bind(this);
    }

    @Override
    public void onStart(SHARE_MEDIA share_media) {
        SocializeUtils.safeShowDialog(dialog);
    }

    @Override
    public void onComplete(SHARE_MEDIA share_media, int i, Map<String, String> data) {
        if (dialog != null) {
            SocializeUtils.safeCloseDialog(dialog);
        }
        data.get("iconurl");
//        mUnionid = data.get("unionid");
//        mWXOpenid = data.get("openid");
//        mName = data.get("name");
    }


    @Override
    public void onError(SHARE_MEDIA share_media, int i, Throwable t) {
        SocializeUtils.safeCloseDialog(dialog);
        showToast(mActivity.getString(com.rv.home.R.string.rv_login_authorization_failure) + t.getMessage());
    }

    @Override
    public void onCancel(SHARE_MEDIA share_media, int i) {
        SocializeUtils.safeCloseDialog(dialog);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        UMShareAPI.get(mActivity).release();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        UMShareAPI.get(mActivity).onSaveInstanceState(outState);
    }

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

        public Withdraw(String amount, String password, String accountNumber, String accountName, String cathType) {
            this.amount = amount;
            this.password = password;
            this.accountNumber = accountNumber;
            this.accountName = accountName;
            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;
        }

        public String getAccountName() {
            return accountName;
        }

        public void setAccountName(String accountName) {
            this.accountName = accountName;
        }
    }
}
