package com.yidianling.user.mine;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.text.TextUtils;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.ToggleButton;

import com.umeng.socialize.UMAuthListener;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.ydl.webview.H5Params;
import com.ydl.webview.NewH5Activity;
import com.ydl.ydlcommon.base.BaseActivity;
import com.ydl.ydlcommon.bean.StatusBarOptions;
import com.ydl.ydlcommon.data.http.ThrowableConsumer;
import com.ydl.ydlcommon.modular.ModularServiceManager;
import com.ydl.ydlcommon.router.YdlCommonOut;
import com.ydl.ydlcommon.utils.LogUtil;
import com.ydl.ydlcommon.utils.SharedPreferencesEditor;
import com.ydl.ydlcommon.utils.remind.ToastHelper;
import com.ydl.ydlcommon.view.JumpTextView;
import com.ydl.ydlcommon.view.RoundCornerButton;
import com.ydl.ydlcommon.view.TitleBar;
import com.ydl.ydlcommon.view.dialog.CommonDialog;
import com.yidianling.common.tools.ToastUtil;
import com.yidianling.im.api.service.IImService;
import com.yidianling.user.LoginUtils;
import com.yidianling.user.R;
import com.yidianling.user.UserConstants;
import com.yidianling.user.UserHelper;
import com.yidianling.user.api.event.RefreshRecentContactListEvent;
import com.yidianling.user.event.UnRegisterEvent;
import com.yidianling.user.event.UpdateBindStatusEvent;
import com.yidianling.user.http.LoginApiRequestUtil;
import com.yidianling.user.http.UserHttp;
import com.yidianling.user.http.UserHttpImpl;
import com.yidianling.user.http.request.BindQQ;
import com.yidianling.user.http.request.BindWX;
import com.yidianling.user.http.request.UnBindThirdLoginParam;
import com.yidianling.user.route.UserIn;
import com.yidianling.user.ui.login.RegisterAndLoginActivity;
import com.yidianling.user.ui.login.VerificationCodeActivity;

import org.jetbrains.annotations.NotNull;

import java.util.Map;
import java.util.Objects;

import de.greenrobot.event.EventBus;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

/**
 * 账号设置
 * Created by softrice on 15/12/1.
 */
public class AccountSettingActivity extends BaseActivity implements View.OnClickListener {

    TitleBar tb_title;
    JumpTextView jtv_phone;
    JumpTextView jtv_change_password;
    LinearLayout ll_change_password;
    JumpTextView person_notify_setting;
    JumpTextView person_black_setting;
    ToggleButton tb_eare;
    JumpTextView jtv_wechat;
    JumpTextView jtv_qq;
    RoundCornerButton rcb_exit;
    JumpTextView tvAccountUnRegister;

    @NotNull
    @Override
    public StatusBarOptions getStatusViewOptions() {
        return new StatusBarOptions(true, true);
    }

    @Override
    protected int layoutResId() {
        return R.layout.user_mine_activity_account_setting;
    }

    @Override
    protected void initDataAndEvent() {
        tb_title = findViewById(R.id.tb_title);
        jtv_phone = findViewById(R.id.jtv_phone);
        jtv_change_password = findViewById(R.id.jtv_change_password);
        ll_change_password = findViewById(R.id.ll_change_password);
        person_notify_setting = findViewById(R.id.person_notify_setting);
        person_black_setting = findViewById(R.id.person_black_setting);
        tb_eare = findViewById(R.id.tb_eare);
        jtv_wechat = findViewById(R.id.jtv_wechat);
        jtv_qq = findViewById(R.id.jtv_qq);
        rcb_exit = findViewById(R.id.rcb_exit);
        tvAccountUnRegister = findViewById(R.id.tv_account_unregister);

        jtv_phone.setOnClickListener(this);
        jtv_change_password.setOnClickListener(this);
        jtv_wechat.setOnClickListener(this);
        jtv_qq.setOnClickListener(this);
        rcb_exit.setOnClickListener(this);
        person_notify_setting.setOnClickListener(this);
        person_black_setting.setOnClickListener(this);
        tvAccountUnRegister.setOnClickListener(this);

        init();
        EventBus.getDefault().register(this);

        userHttp = UserHttpImpl.Companion.getInstance();
        //判断用户是否设置密码 去设置 去修改
        getPasswordData();
    }

    /**
     * 判断是否有密码
     */
    @SuppressLint("CheckResult")
    private void getPasswordData() {

        if (TextUtils.isEmpty(UserHelper.INSTANCE.getUserInfo().getUserInfo().getPhone()) || TextUtils.isEmpty(UserHelper.INSTANCE.getUserInfo().getUserInfo().getCountry_code())) {
            return;
        }
        showProgressDialog();
        LoginApiRequestUtil.Companion.checkPhoneStatus(UserHelper.INSTANCE.getUserInfo().getUserInfo().getPhone(), UserHelper.INSTANCE.getUserInfo().getUserInfo().getCountry_code())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(response -> {
                    dismissProgressDialog();
                    if (response == null || response.data == null) {
                        hasPassword(false);
                    } else {
                        if (response.data.getHasPwd() == 1) {
                            hasPassword(true);
                        } else {
                            hasPassword(false);
                        }
                    }
                }, new ThrowableConsumer() {
                    @Override
                    public void accept(@NotNull String msg) {
                        dismissProgressDialog();
                        hasPassword(false);
                    }
                });
    }

    private void hasPassword(boolean hasPassword) {
        if (hasPassword) {
            jtv_change_password.setRightText("去修改");
        } else {
            jtv_change_password.setRightText("去设置");
        }
    }

    /**
     * 更改听筒模式状态
     *
     * @param b
     */
    private void changeEarMode(boolean b) {
        try {
            final String EAR_MODE_KEY = ModularServiceManager.INSTANCE.provide(IImService.class).getEarModeKey();
            final String EAR_MODE_OPEN = ModularServiceManager.INSTANCE.provide(IImService.class).getEarModeOpenType();
            final String EAR_MODE_CLOSE = ModularServiceManager.INSTANCE.provide(IImService.class).getEarModeCloseType();
            SharedPreferencesEditor.putString(EAR_MODE_KEY, b ? EAR_MODE_OPEN : EAR_MODE_CLOSE);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    void init() {
        tb_eare.setOnCheckedChangeListener((compoundButton, b) -> {
            //设置听筒模式
            try {
                ModularServiceManager.INSTANCE.provide(IImService.class).updateEarMode(b);
            } catch (Exception e) {
                e.printStackTrace();
            }
            changeEarMode(b);
        });
        jtv_phone.setRightText(isNullString(UserHelper.INSTANCE.getUserInfo().getUserInfo().getPhone()));
        if (TextUtils.isEmpty(UserHelper.INSTANCE.getUserInfo().getUserInfo().getPhone())) {
            ll_change_password.setVisibility(View.GONE);
        } else {
            ll_change_password.setVisibility(View.VISIBLE);
        }

        //如果是壹点灵正版则开放qq登录入口，而是马甲版则屏蔽qq登录入口
        if (YdlCommonOut.Companion.getChannelName().startsWith("android")) {
            jtv_qq.setVisibility(View.VISIBLE);
            if (UserHelper.INSTANCE.getUserInfo().getUserInfo().getBind_qq() == 0) {
                jtv_qq.setRightText("未绑定");
            } else {
                jtv_qq.setRightText("已绑定");
            }
        }

        if (UserHelper.INSTANCE.getUserInfo().getUserInfo().getBind_weixin() == 0) {
            jtv_wechat.setRightText("未绑定");
        } else {
            jtv_wechat.setRightText("已绑定");
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        dismissProgressDialog();
        EventBus.getDefault().unregister(this);
    }

    /**
     * 更新绑定状态
     *
     * @param event
     */
    public void onEvent(UpdateBindStatusEvent event) {
        jtv_phone.setRightText(isNullString(UserHelper.INSTANCE.getUserInfo().getUserInfo().getPhone()));
        if (TextUtils.isEmpty(UserHelper.INSTANCE.getUserInfo().getUserInfo().getPhone())) {
            ll_change_password.setVisibility(View.GONE);
        } else {
            ll_change_password.setVisibility(View.VISIBLE);
        }

        if (UserHelper.INSTANCE.getUserInfo().getUserInfo().getBind_qq() == 0) {
            jtv_qq.setRightText("未绑定");
        } else {
            jtv_qq.setRightText("已绑定");
        }

        if (UserHelper.INSTANCE.getUserInfo().getUserInfo().getBind_weixin() == 0) {
            jtv_wechat.setRightText("未绑定");
        } else {
            jtv_wechat.setRightText("已绑定");
        }
    }

    public void onEvent(UnRegisterEvent event) {
        LogOut();
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.jtv_phone) {
            if (UserHelper.INSTANCE.isLogin() && !TextUtils.isEmpty(UserHelper.INSTANCE.getUserInfo().getUserInfo().getPhone())) {
                startActivity(new Intent(this, PwdCheckActivity.class));
            } else {
                bindPhone();

            }
        } else if (id == R.id.jtv_change_password) {
            if (UserHelper.INSTANCE.isLogin() && TextUtils.isEmpty(UserHelper.INSTANCE.getUserInfo().getUserInfo().getPhone()))
                ToastUtil.toastShort("未绑定手机号，无法修改密码");
            else
                changePassword();
        } else if (id == R.id.person_black_setting) {//黑名单管理
            H5Params h5Params = new H5Params(UserConstants.INSTANCE.getMy_BLACK(), null);
            NewH5Activity.start(this, h5Params);
        } else if (id == R.id.jtv_wechat) {
            if (UserHelper.INSTANCE.getUserInfo().getUserInfo().getBind_weixin() == 0) {
                bindWx();
            } else {
                showEnsureDialog(1);
            }
        } else if (id == R.id.jtv_qq) {
            if (UserHelper.INSTANCE.getUserInfo().getUserInfo().getBind_qq() == 0) {
                bindQQ();
            } else {
                showEnsureDialog(2);
            }
        } else if (id == R.id.rcb_exit) {
            LogOut();
        } else if (id == R.id.person_notify_setting) {
            startActivity(new Intent(this, NotificationsSettingActivity.class));
        } else if (id == R.id.tv_account_unregister) {
            startActivity(new Intent(this, AccountUnRegisterActivity.class));
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
    }

    /**
     * 退出登录
     */
    private void LogOut() {
        //清除UserInfo
        UserHelper.INSTANCE.setUserinfo(null);
        UserIn.INSTANCE.clearImData();

        LoginUtils.logout();
        EventBus.getDefault().post(new RefreshRecentContactListEvent());
        finish();
    }

    private UserHttp userHttp;

    /**
     * 绑定QQ
     */
    private void bindQQ() {
        showProgressDialog("绑定QQ中...");
        UMShareAPI.get(this).doOauthVerify(this, SHARE_MEDIA.QQ, new UMAuthListener() {
            @Override
            public void onStart(SHARE_MEDIA share_media) {

            }

            @SuppressLint("CheckResult")
            @Override
            public void onComplete(SHARE_MEDIA share_media, int i, Map<String, String> map) {
                if (map == null || map.size() == 0) {
                    return;
                }
                userHttp.bindQQ(new BindQQ(map.get("openid"), map.get("unionid")))
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(o -> {
                            dismissProgressDialog();
                            if (o.code == 0) {
                                Objects.requireNonNull(UserHelper.INSTANCE.getUserInfo().getUserInfo()).setBind_qq(1);
                                jtv_qq.setRightText("已绑定");
                                ToastUtil.toastShort("绑定成功");
                            } else {
                                ToastHelper.Companion.show(o.msg);
                            }
                        }, new ThrowableConsumer() {
                            @Override
                            public void accept(@NotNull String msg) {
                                dismissProgressDialog();
                                ToastHelper.Companion.show(msg);
                            }
                        });

                UMShareAPI.get(AccountSettingActivity.this).deleteOauth(AccountSettingActivity.this, SHARE_MEDIA.QQ, this);
            }

            @Override
            public void onError(SHARE_MEDIA share_media, int i, Throwable throwable) {
                dismissProgressDialog();
                ToastUtil.toastShort(throwable.getMessage());
            }

            @Override
            public void onCancel(SHARE_MEDIA share_media, int i) {
                dismissProgressDialog();
            }
        });

    }

    /**
     * 绑定微信
     */
    private void bindWx() {
        showProgressDialog("绑定微信中...");
        UMShareAPI.get(this).getPlatformInfo(this, SHARE_MEDIA.WEIXIN, new UMAuthListener() {
            @Override
            public void onStart(SHARE_MEDIA share_media) {

            }

            @SuppressLint("CheckResult")
            @Override
            public void onComplete(SHARE_MEDIA share_media, int i, Map<String, String> map) {
                if (map == null||map.size()==0) {
                    return;
                }
                String openid = map.get("openid");
                String unionid = map.get("unionid");
                userHttp.bindWX(new BindWX(openid, unionid))
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(o -> {
                            dismissProgressDialog();
                            if (o.code == 0) {
                                UserHelper.INSTANCE.getUserInfo().getUserInfo().setBind_weixin(1);
                                jtv_wechat.setRightText("已绑定");
                                ToastUtil.toastShort("绑定成功");
                            } else {
                                ToastHelper.Companion.show(o.msg);
                            }
                        }, new ThrowableConsumer() {
                            @Override
                            public void accept(@NotNull String msg) {
                                dismissProgressDialog();
                            }
                        });

                UMShareAPI.get(AccountSettingActivity.this).deleteOauth(AccountSettingActivity.this, SHARE_MEDIA.WEIXIN, this);
            }

            @Override
            public void onError(SHARE_MEDIA share_media, int i, Throwable throwable) {
                dismissProgressDialog();
                ToastUtil.toastShort(throwable.getMessage());
            }

            @Override
            public void onCancel(SHARE_MEDIA share_media, int i) {
                dismissProgressDialog();
            }
        });
    }

    /**
     * 确认弹窗
     *
     * @param type 1-微信 2-qq
     */
    private void showEnsureDialog(int type) {
        String msg;
        if (type == 1) {
            msg = "您确认要解绑微信？";
        } else {
            msg = "您确认要解绑QQ？";
        }

        CommonDialog.create(this)
                .setMessage(msg)
                .setLeftOnclick("取消", v -> {

                })
                .setRightClick("确认", v -> checkUnbind(type))
                .setCancelAble(true)
                .show();
    }

    /**
     * 判断是否满足解绑条件
     *
     * @param type 1-微信 2-qq
     */
    private void checkUnbind(int type) {
        //没有绑定手机号，且微信和qq只有一个绑定了，解绑前需要再次弹窗确认
        if (TextUtils.isEmpty(UserHelper.INSTANCE.getUserInfo().getUserInfo().getPhone())) {
            int flag = 0;
            if (UserHelper.INSTANCE.getUserInfo().getUserInfo().getBind_weixin() == 1) {
                flag++;
            }
            if (UserHelper.INSTANCE.getUserInfo().getUserInfo().getBind_qq() == 1) {
                flag++;
            }
            if (flag != 2) {
                //满足再次弹窗确认条件
                noticeDialog(type);
            }else{
                unbindThirdLogin(type);
            }
        } else {
            unbindThirdLogin(type);
        }

    }

    /**
     * 再次弹窗确认提示
     *
     * @param type 1-微信 2-qq
     */
    private void noticeDialog(int type) {
        CommonDialog.create(this)
                .setMessage("由于您账号未绑定手机号，取消绑定后账号信息将被清除，确认要解绑？")
                .setLeftOnclick("取消", v -> {

                })
                .setRightClick("确认", v -> unbindThirdLogin(type))
                .setCancelAble(true)
                .show();
    }

    /**
     * 解绑第三方登录账号
     *
     * @param type 1-微信 2-qq
     */
    @SuppressLint("CheckResult")
    private void unbindThirdLogin(int type) {
        UnBindThirdLoginParam param = new UnBindThirdLoginParam();
        param.type = type;
        showProgressDialog();
        userHttp.unBindThirdLogin(param)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(response -> {
                    dismissProgressDialog();
                    if (response != null && response.code == 200) {
                        ToastUtil.toastShort("解绑成功");
                        if (type == 1) {
                            Objects.requireNonNull(UserHelper.INSTANCE.getUserInfo().getUserInfo()).setBind_weixin(0);
                            jtv_wechat.setRightText("未绑定");
                        } else {
                            Objects.requireNonNull(UserHelper.INSTANCE.getUserInfo().getUserInfo()).setBind_qq(0);
                            jtv_qq.setRightText("未绑定");
                        }
                    } else {
                        ToastUtil.toastShort(response.msg);
                    }
                }, new ThrowableConsumer() {
                    @Override
                    public void accept(@NotNull String msg) {
                        dismissProgressDialog();
                        ToastUtil.toastShort(msg);
                    }
                });

    }

    /**
     * 修改密码
     */
    private void changePassword() {
        //跳转到新的修改密码页面
        VerificationCodeActivity.Companion.start(this, UserHelper.INSTANCE.getUserInfo().getUserInfo().getPhone(), UserHelper.INSTANCE.getUserInfo().getUserInfo().getCountry_code(), VerificationCodeActivity.Companion.getSTATUS_FORGET_PWD());
    }

    /**
     * 绑定手机
     */
    private void bindPhone() {
        RegisterAndLoginActivity.Companion.start(this,true);
    }

    private String isNullString(String str) {
        if (TextUtils.isEmpty(str))
            return "未绑定";
        else {
            StringBuffer sb = new StringBuffer();
            for (int i = 0; i < str.length(); i++) {
                if (i >= 3 && i <= 5) {
                    sb.append("*");
                } else {
                    sb.append(str.charAt(i));
                }
            }
            return sb.toString();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        //
        jtv_phone.setRightText(isNullString(UserHelper.INSTANCE.getUserInfo().getUserInfo().getPhone()));
        try {
            if (ModularServiceManager.INSTANCE.provide(IImService.class).getEarModeIsOpen()) {
                tb_eare.setChecked(true);
            } else {
                tb_eare.setChecked(false);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (!TextUtils.isEmpty(UserHelper.INSTANCE.getUserInfo().getUserInfo().getPhone())) {
            ll_change_password.setVisibility(View.VISIBLE);
        } else {
            ll_change_password.setVisibility(View.GONE);
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

}
