package com.xxrv.wallet.activity;

import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
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.alipay.sdk.app.AuthTask;
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.component.dialog.WalletTipsDialog;
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.WalletAuthInfoBean;
import com.xxrv.wallet.bean.WalletBean;
import com.xxrv.wallet.bean.WalletCheckPwdBean;
import com.xxrv.wallet.dialog.ThirdPartyBindingDialog;
import com.xxrv.wallet.event.SetPasswordSuccessEvent;
import com.xxrv.wallet.presenter.WalletPresenter;
import com.yuyife.okgo.OkGoUtil;

import java.util.HashMap;
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> implements UMAuthListener {

    @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;
    private static final int SDK_AUTH_FLAG = 2;
    private String isFrozen;
    public ProgressDialog dialog;

    @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();
        dialog = new ProgressDialog(this);
    }

    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) {
                        getAccountNumber();
                    }
                });
    }

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

    private void isAccountNumber(AccountNumberListBean result) {
        if (result != null && result.getData() != null && result.getData().size() > 0) {  ////1支付宝  2微信
            getCheckSetPwd();
        } else {
            showBindingDialog();
        }
    }

    private void showBindingDialog() {
        new ThirdPartyBindingDialog(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.ll_item_alipay) {
                            //支付宝绑定
                            getAuthInfo();
                            dismiss();
                        } else if (id == R.id.ll_item_wechat) {
                            //微信绑定
                            bindThirdParty(SHARE_MEDIA.WEIXIN);
                            dismiss();
                        }
                    }
                }, R.id.ll_item_alipay, R.id.ll_item_wechat);
            }
        }.show();
    }


    private void setWalletData(WalletBean bean) {
        if (bean != null && bean.getData() != null) {
            isFrozen = bean.getData().getIsFrozen();
            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_wallet_hint, 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) {

        final int id = view.getId();
        if (id == R.id.iv_back) {
            finish();
        } else if (id == R.id.tv_item_wallet_hint) {
            //钱包提现规则
            ARouter.getInstance().build(Constance.ACTIVITY_URL_WEBVIEW)
                    .withString("title", "提现规则")
                    .withString("url", ApiConfig.HTTP_URL_CAR_TYPE_NOTICE)
                    .withInt("type", 24)
                    .navigation();

        } else if (id == R.id.tv_item_withdraw) {
            //提现

            if (!TextUtils.isEmpty(isFrozen)) {  //// 0 正常 1冻结
                if ("1".equals(isFrozen)) {
                    new WalletTipsDialog(mActivity) {
                        @Override
                        public void helper(ViewHolder helper) {
                            super.helper(helper);
                            helper.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    if (v.getId() == R.id.tv_ok) {
                                        dismiss();
                                    }
                                }
                            }, R.id.tv_ok);
                        }
                    }.show();
                    return;
                }
            }

            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 {
                    getAccountNumber();
                }
            }

        } 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, 0));
            }
        }
    }


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

    /**
     * 获取帐号信息
     */
    private void getAccountNumber() {
        Map<String, Object> headMap = new LinkedHashMap<>();
        if (OkGoUtil.getToken() != null)
            headMap.put("Authorization", OkGoUtil.getToken());
        mPresenter.getDataHead(RvFrameConfig.HOST, 4, WalletApi.HTTP_URL_WALLET_ACCOUNT_NUMBER, AccountNumberListBean.class, headMap, false);

    }

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

        Runnable authRunnable = new Runnable() {
            @Override
            public void run() {
                // 构造AuthTask 对象
                AuthTask authTask = new AuthTask(WalletActivity.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
                    showToast(resultStatus.toString());
                    // 为“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, 3, WalletApi.HTTP_URL_WALLET_ALIPAY_GETUSERINFO, BaseBean.class, map, headMap, false);

    }

    private void bindThirdParty(SHARE_MEDIA share_media) {
        UMShareAPI.get(mActivity).getPlatformInfo(mActivity, share_media, 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> map) {
        if (dialog != null) {
            SocializeUtils.safeCloseDialog(dialog);
        }

        String type = share_media.getName();
        if (share_media != null && "wxsession".equals(type)) { // 微信
            String openid = map.get("openid");
            String unionid = map.get("unionid");
            String nickName = map.get("name");
            authorize(openid, unionid, nickName, "wx");
        }
    }


    /**
     * 微信绑定
     *
     * @param openid
     * @param unionid
     * @param nickName
     * @param type
     */
    private void authorize(String openid, String unionid, String nickName, String type) {
        if (!TextUtils.isEmpty(OkGoUtil.getToken())) {
            Map<String, String> heads = new HashMap<>();
            heads.put("Authorization", OkGoUtil.getToken());
            mPresenter.postBodyData(10, ApiConfig.HTTP_URL_USER_BIND, BaseBean.class, new AccountBindDto(openid, unionid, nickName, type), heads, false);
        }
    }

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

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


    private class AccountBindDto {
        private String openId;
        private String unionId;
        private String nickName;
        private String type;

        public AccountBindDto(String openId, String unionId, String nickName, String type) {
            this.openId = openId;
            this.unionId = unionId;
            this.nickName = nickName;
            this.type = type;
        }


        public String getOpenId() {
            return openId;
        }

        public void setOpenId(String openId) {
            this.openId = openId;
        }

        public String getUnionId() {
            return unionId;
        }

        public void setUnionId(String unionId) {
            this.unionId = unionId;
        }

        public String getNickName() {
            return nickName;
        }

        public void setNickName(String nickName) {
            this.nickName = nickName;
        }

        public String getType() {
            return type;
        }

        public void setType(String type) {
            this.type = type;
        }

    }
}
