package com.xxrv.wallet.activity;

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

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.frame.base.bus.IDCardCertificationEvent;
import com.frame.base.bus.Observer;
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.bean.BeanUserInfo;
import com.ruiwenliu.wrapper.statusbar.StatusBarUtil;
import com.ruiwenliu.wrapper.util.ViewHolder;
import com.ruiwenliu.wrapper.weight.TitleView;
import com.rv.component.dialog.VerifiedTipsDialog;
import com.rv.home.rv.module.ApiConfig;
import com.rv.home.rv.module.ui.main.home.ConfirmOrderActivity;
import com.rv.home.rv.module.ui.main.home.dialog.TipsDialog;
import com.rv.home.rv.module.ui.main.home.order.CancelTheTripActivity;
import com.rv.home.rv.module.ui.main.home.order.bean.CancelTheTripBean;
import com.xxrv.wallet.R;
import com.xxrv.wallet.R2;
import com.xxrv.wallet.api.WalletApi;
import com.xxrv.wallet.bean.WalletBean;
import com.xxrv.wallet.bean.WalletCheckPwdBean;
import com.xxrv.wallet.event.SetPasswordSuccessEvent;
import com.xxrv.wallet.presenter.WalletPresenter;
import com.yuyife.okgo.OkGoUtil;

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

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.schedulers.Schedulers;

/**
 * 钱包
 */
@Route(path = Constance.ACTIVITY_URL_WALLET)
public class WalletActivity extends BaseStatusActivity<WalletPresenter> {

    @BindView(R2.id.tv_wallet_balance)
    TextView tvWalletBalance;
    @BindView(R2.id.tv_today_amount)
    TextView tvTodayAmount;
    @BindView(R2.id.tv_total_amount)
    TextView tvTotalAmount;
    @BindView(R2.id.tv_not_amount)
    TextView tvNotAmount;

    private String balance;

    private BeanUserInfo.UserInfo userInfo;


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

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        StatusBarUtil.setRootViewFitsSystemWindows(mActivity,false);
    }

    @Override
    protected void initView(Bundle savedInstanceState, TitleView titleView, Intent intent) {
        showTitle(false);
        initRxbus();
        userInfo = getUserInfo();
    }

    private void initRxbus() {
        RxBus.tObservable(SetPasswordSuccessEvent.class)
                .observeOn(Schedulers.newThread())
                .subscribe(new Observer<SetPasswordSuccessEvent>(disposable) {
                    @Override
                    public void onNext(SetPasswordSuccessEvent event) {
                        startActivity(WithdrawActivity.getIntent(mActivity, balance));
                    }
                });

        RxBus.tObservable(WithdrawSuccessEvent.class)
                .observeOn(Schedulers.newThread())
                .subscribe(new Observer<WithdrawSuccessEvent>(disposable) {
                    @Override
                    public void onNext(WithdrawSuccessEvent event) {
                        getWalletList();
                    }
                });

        RxBus.tObservable(IDCardCertificationEvent.class)
                .observeOn(Schedulers.newThread())
                .subscribe(new Observer<IDCardCertificationEvent>(disposable) {
                    @Override
                    public void onNext(IDCardCertificationEvent event) {
                        getCheckSetPwd();
                    }
                });
    }

    @Override
    public void onShowResult(int requestType, BaseBean result) {
        switch (requestType) {
            case 0:
                setWalletData((WalletBean) result);
                break;
            case 1:
                setCheckPwd((WalletCheckPwdBean) result);
                break;
        }
    }


    private void setWalletData(WalletBean bean) {
        if (bean != null && bean.getData() != null) {
            balance = bean.getData().getBalance();
            tvWalletBalance.setText("¥" + bean.getData().getBalance());
            tvTodayAmount.setText(bean.getData().getTodayAmount());
            tvTotalAmount.setText(bean.getData().getTotalAmount());
            tvNotAmount.setText(bean.getData().getUnbooked());
        }
    }

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


    /**
     * 获取钱包
     */
    private void getWalletList() {
        Map<String, Object> headMap = new LinkedHashMap<>();
        if (OkGoUtil.getToken() != null)
            headMap.put("Authorization", OkGoUtil.getToken());
        mPresenter.getDataHead(RvFrameConfig.HOST, 0, WalletApi.HTTP_URL_ADMIN_WALLET, WalletBean.class, headMap, false);
    }


    @OnClick({R2.id.iv_back, R2.id.tv_item_withdraw, R2.id.rl_item_consumer_details, R2.id.rl_item_commission_record, R2.id.rl_item_withdrawals_record})
    public void onViewClicked(View view) {

        int id = view.getId();
        if (id == R.id.iv_back) {
            finish();
        } else if (id == R.id.tv_item_withdraw) {
            //提现
            if (userInfo != null) { ////实名认证状态:0-未认证，1-已认证
                if (0==userInfo.getCertificationStatus()) {
                    new VerifiedTipsDialog(mActivity) {
                        @Override
                        public void helper(ViewHolder helper) {
                            super.helper(helper);
                            helper.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    int id = v.getId();
                                    if (id == R.id.tv_ok) {
                                        ARouter.getInstance()
                                                .build(Constance.ACTIVITY_URL_IDCARDCERTIFICATION)
                                                .navigation();
                                        dismiss();
                                    } else if (id == R.id.tv_cancel) {
                                        dismiss();
                                    }
                                }
                            }, R.id.tv_ok, R.id.tv_cancel);
                        }
                    }.show();

                } else {
                    getCheckSetPwd();
                }
            }

        } else if (id == R.id.rl_item_consumer_details) {
            startActivity(new Intent(getApplicationContext(), ConsumeDetailActivity.class));
            //消费明细
        } else if (id == R.id.rl_item_commission_record) {
            //佣金记录
            startActivity(new Intent(getApplicationContext(), CommissionDetailActivity.class));
        } else if (id == R.id.rl_item_withdrawals_record) {
            //提现记录
            startActivity(new Intent(getApplicationContext(), EnchashmentRecordActivity.class));
        }
    }

    /**
     * 检查用户是否设置过支付密码
     */
    private void getCheckSetPwd() {
        Map<String, Object> headMap = new LinkedHashMap<>();
        if (OkGoUtil.getToken() != null)
            headMap.put("Authorization", OkGoUtil.getToken());
        mPresenter.getDataHead(RvFrameConfig.HOST, 1, WalletApi.HTTP_URL_CHECK_SETPWD, WalletCheckPwdBean.class, headMap, false);

    }


    private void setCheckPwd(WalletCheckPwdBean bean) {
        if (bean != null) {
            if (bean.isData()) {  //true-设置过；false-没有
                startActivity(WithdrawActivity.getIntent(mActivity, balance));
            } else {
                startActivity(SetPayPwdActivity.getIntent(mActivity));
            }
        }
    }
}
