package com.rv.rvmine.traveler;


import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import com.alipay.sdk.app.AuthTask;
import com.frame.rv.config.RvFrameConfig;
import com.ruiwenliu.wrapper.base.BaseBean;
import com.ruiwenliu.wrapper.base.BaseStatusActivity;
import com.ruiwenliu.wrapper.base.presenter.CommonPresenter;
import com.ruiwenliu.wrapper.bean.UserInfoBean;
import com.ruiwenliu.wrapper.weight.TitleView;
import com.rv.component.utils.CacheEnum;
import com.rv.component.utils.IsAppInstall;
import com.rv.component.utils.RvCache;
import com.rv.home.rv.module.ApiConfig;
import com.rv.home.rv.module.ui.login.LoginRvActivity;
import com.rv.home.rv.module.ui.login.RegisteredActivity;
import com.rv.rvmine.R;
import com.rv.rvmine.R2;
import com.rv.rvmine.bean.AccountBindDto;
import com.rv.rvmine.bean.BindCallBackBean;
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.api.WalletApi;
import com.xxrv.wallet.bean.AuthResult;
import com.xxrv.wallet.bean.WalletAuthInfoBean;
import com.yuyife.okgo.OkGoUtil;

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

import butterknife.BindView;
import butterknife.OnClick;

public class AccountSafeActivity extends BaseStatusActivity<CommonPresenter> implements UMAuthListener {

    private static final int REQUEST_CODE_BIND_PHONE = 1001;

    @BindView(R2.id.tv_phone)
    TextView tvPhone;
    @BindView(R2.id.tv_qq)
    TextView tvQQ;
    @BindView(R2.id.tv_wx)
    TextView tvWx;
    @BindView(R2.id.tv_zfb)
    TextView tvZfb;

    private UserInfoBean bean; // 用户信息

    private boolean hasBindQQ; // 是否已经绑定QQ;
    private boolean hasBindWX; // 是否已经绑定微信
    private boolean hasBindZfb; // 是否已经绑定支付宝

    public ProgressDialog dialog;

    private int bindType; // 1 qq；2 微信；3支付宝

    @Override
    public void onShowResult(int requestType, BaseBean result) {
        if (requestType == 0) {
            bean = (UserInfoBean) result;
            setUserInfo();
        } else if (requestType == 1) {
            alipayAuthV2((WalletAuthInfoBean) result);
        } else if (requestType == 5) {
            if (bindType == 0) return;
            dealBindResult((BindCallBackBean) result);
        }
    }

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

    @Override
    protected void initView(Bundle savedInstanceState, TitleView titleView, Intent intent) {
        titleView.setTitle("账号与安全");
        dialog = new ProgressDialog(this);
    }

    @OnClick({R2.id.rl_item_phone, R2.id.rl_update_pwd, R2.id.rl_qq, R2.id.rl_wx, R2.id.rl_zfb})
    public void onViewClicked(View view) {
        int id = view.getId();
        if (id == R.id.rl_item_phone) {  // 修改手机号码
            //修改密码
            if (TextUtils.isEmpty(OkGoUtil.getToken())) {
                startActivity(LoginRvActivity.getIntent(mActivity, 0));
                return;
            }
            Intent intent = new Intent(mActivity, BindPhoneActivity.class);
            intent.putExtra("user", bean);
            startActivityForResult(intent, REQUEST_CODE_BIND_PHONE);
        } else if (id == R.id.rl_update_pwd) {
            //修改密码
            if (TextUtils.isEmpty(OkGoUtil.getToken())) {
                startActivity(LoginRvActivity.getIntent(mActivity, 0));
                return;
            }
            startActivity(RegisteredActivity.getIntent(mActivity, 1, 0));
        } else if (id == R.id.rl_qq) {
            if (hasBindQQ) {
                showToast("您已绑定过QQ");
                return;
            }
            //绑定qq
            if (!IsAppInstall.isQQClientAvailable(mActivity)) {
                showToast("亲，您QQ还没有安装呢");
                return;
            }
            bindType = 1;
            bindThirdParty(SHARE_MEDIA.QQ);
        } else if (id == R.id.rl_zfb) {

            if (hasBindZfb) {
                showToast("您已绑定过支付宝");
                return;
            }
            if (!IsAppInstall.isZfbClientAvailable(mActivity)) {
                showToast("亲，您支付宝还没有安装呢");
                return;
            }
            bindType = 3;
            getAuthInfo();

        } else if (id == R.id.rl_wx) {
            if (hasBindWX) {
                showToast("您已绑定过微信");
                return;
            }
            if (!IsAppInstall.isZfbClientAvailable(mActivity)) {
                showToast("亲，您微信还没有安装呢");
                return;
            }
            bindType = 2;
            bindThirdParty(SHARE_MEDIA.WEIXIN);
        }
    }

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

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

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

    private void getUser() {
        bean = (UserInfoBean) RvCache.getInstance().get(CacheEnum.USER);
        if (bean != null) {
            setUserInfo();
        } else {
            getUserData();
        }
    }

    private void dealBindResult(BindCallBackBean bindCallBackBean) {
        if (bindType == 1) {
            hasBindQQ = true;
            tvQQ.setTextColor(Color.parseColor("#171413"));
            tvQQ.setText(TextUtils.isEmpty(bindCallBackBean.getData()) ? "已绑定" : bindCallBackBean.getData());
            bean.getData().setBindQQ(true);
            bean.getData().setQqNickname(bindCallBackBean.getData());
        } else if (bindType == 2) {
            hasBindWX = true;
            tvWx.setTextColor(Color.parseColor("#171413"));
            tvWx.setText(TextUtils.isEmpty(bindCallBackBean.getData()) ? "已绑定" : bindCallBackBean.getData());
            bean.getData().setBindWx(true);
            bean.getData().setWxNickname(bindCallBackBean.getData());
        } else if (bindType == 3) {
            hasBindZfb = true;
            tvZfb.setTextColor(Color.parseColor("#171413"));
            tvZfb.setText(TextUtils.isEmpty(bindCallBackBean.getData()) ? "已绑定" : bindCallBackBean.getData());
            bean.getData().setBindAliPay(true);
            bean.getData().setAliPayNickName(bindCallBackBean.getData());
        }
        RvCache.getInstance().save(bean, CacheEnum.USER);
        showToast("授权绑定成功！");
    }

    /**
     * 获取用户信息请求
     */
    private void getUserData() {
        Map<String, Object> headMap = new LinkedHashMap<>();
        if (OkGoUtil.getToken() != null) {
            headMap.put("Authorization", OkGoUtil.getToken());
            mPresenter.getDataHead(RvFrameConfig.ADMIN_POST, 0, ApiConfig.HTTP_URL_APP_USER_INFO, UserInfoBean.class, headMap, false);
        }
    }

    private void setUserInfo() {
        String phone = bean.getData().getUsername();
        if (!TextUtils.isEmpty(phone)) {
            tvPhone.setText(phone);
        }
        setQqInfo();
        setWxInfo();
        setZfbInfo();
    }

    private void setQqInfo() {
        hasBindQQ = bean.getData().isBindQQ();
        if (hasBindQQ) {
            String qq = bean.getData().getQqNickname();
            tvQQ.setTextColor(Color.parseColor("#171413"));
            tvQQ.setText(!TextUtils.isEmpty(qq) ? qq : "已绑定");
        } else {
            tvQQ.setTextColor(Color.parseColor("#cccccc"));
            tvQQ.setText("去授权绑定QQ");
        }
    }

    private void setWxInfo() {
        hasBindWX = bean.getData().isBindWx();
        if (hasBindWX) {
            String wx = bean.getData().getWxNickname();
            tvWx.setTextColor(Color.parseColor("#171413"));
            tvWx.setText(!TextUtils.isEmpty(wx) ? wx : "已绑定");
        } else {
            tvWx.setTextColor(Color.parseColor("#cccccc"));
            tvWx.setText("去授权绑定微信");
        }
    }

    private void setZfbInfo() {
        hasBindZfb = bean.getData().isBindAliPay();
        if (hasBindZfb) {
            String zfb = bean.getData().getAliPayNickName();
            tvZfb.setTextColor(Color.parseColor("#171413"));
            tvZfb.setText(!TextUtils.isEmpty(zfb) ? zfb : "已绑定");
        } else {
            tvZfb.setTextColor(Color.parseColor("#cccccc"));
            tvZfb.setText("去授权绑定支付宝");
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        RvCache.getInstance().save(bean, CacheEnum.USER);
        UMShareAPI.get(mActivity).release();
    }

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

    private void authorize(AccountBindDto dto) {
        if (!TextUtils.isEmpty(OkGoUtil.getToken())) {
            Map<String, String> heads = new HashMap<>();
            heads.put("Authorization", OkGoUtil.getToken());
            mPresenter.postBodyData(5, ApiConfig.HTTP_URL_USER_BIND, BindCallBackBean.class, dto, heads, true);
        }
    }

    @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();
        AccountBindDto bindDto = null;
        if (share_media != null && "wxsession".equals(type)) { // 微信
            String openid = map.get("openid");
            String unionid = map.get("unionid");
            String nickName = map.get("name");
            bindDto = new AccountBindDto(openid, unionid, nickName, "wx");
            authorize(bindDto);
        } else if (share_media != null && "qq".equals(type)) {
            String mQQOpenid = map.get("openid");
            String nickName = map.get("name");
            bindDto = new AccountBindDto(mQQOpenid, null, nickName, "q");
            authorize(bindDto);
        }

//        Set<String> keys = map.keySet();
//        Log.e("key", "----------------------------------------start---------------------------------");
//        for (String key : keys) {
//            Log.i(key, " value=" + map.get(key));
//        }
////        Log.e("key", "----------------------------------------end---------------------------------");
    }

    @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 void alipayAuthV2(final WalletAuthInfoBean bean) {

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

                Message msg = new Message();
                msg.what = 0;
                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 0: {
                    @SuppressWarnings("unchecked")
                    Map<String, String> values = (Map<String, String>) msg.obj;
                    AuthResult authResult = new AuthResult(values, true);
                    String resultStatus = authResult.getResultStatus();
                    // 判断resultStatus 为“9000”且result_code
                    // 为“200”则代表授权成功，具体状态码代表含义可参考授权接口文档
                    if (TextUtils.equals(resultStatus, "9000") && TextUtils.equals(authResult.getResultCode(), "200")) {
                        // 传入，则支付账户为该授权账户
                        AccountBindDto bindDto = new AccountBindDto(authResult.getAlipayOpenId(), null, null, "aliPay", authResult.getAuthCode());
                        authorize(bindDto);
//                        putAlipayCode(authResult.getAlipayOpenId(), authResult.getAuthCode());
//                        showToast("授权成功！");
                    } else {
                        // 其他状态值则为授权失败
                    }
                    break;
                }
                default:
                    break;
            }
        }
    };

//    private void putAlipayCode(String openId, 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 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);
//    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_BIND_PHONE) {
            if (RESULT_OK == resultCode) {
                String phone = data.getStringExtra("phone");
                bean.getData().setUsername(phone);
                if (!TextUtils.isEmpty(phone)) {
                    tvPhone.setText(phone);
                }
            }
        } else
            UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
    }
}
