package com.yidianling.user.ui;

import android.content.Context;
import android.text.TextUtils;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.ydl.webview.RefreshWebEvent;
import com.ydl.ydlcommon.base.BaseActivity;
import com.ydl.ydlcommon.data.http.EncryptUtils;
import com.ydl.ydlcommon.data.http.RxUtils;
import com.ydl.ydlcommon.data.http.ThrowableConsumer;
import com.ydl.ydlcommon.utils.ActivityManager;
import com.ydl.ydlcommon.utils.log.LogHelper;
import com.ydl.ydlcommon.utils.remind.ToastHelper;
import com.ydl.ydlcommon.view.RoundCornerButton;
import com.ydl.ydlcommon.view.TitleBar;
import com.yidianling.router.RouterManager;
import com.yidianling.router.im.IMLoginInfo;
import com.yidianling.router.im.IMRequestCallback;
import com.yidianling.router.user.UserResponse;
import com.yidianling.user.LoginHelper;
import com.yidianling.user.R;
import com.yidianling.user.UserConstants;
import com.yidianling.user.UserHelper;
import com.yidianling.user.event.UpdateBindStatusEvent;
import com.yidianling.user.http.UserHttp;
import com.yidianling.user.http.UserHttpImpl;
import com.yidianling.user.http.request.*;
import com.yidianling.user.route.UserIn;
import de.greenrobot.event.EventBus;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import org.jetbrains.annotations.NotNull;

import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.TimeUnit;

import static com.yidianling.user.UserConstants.FORGET_ACTION;
import static com.yidianling.user.UserConstants.REGISTER_ACTION;


/**
 * 绑定手机 验证码和登录密码
 */
public class GetIdentifyingCodeActivity extends BaseActivity implements View.OnClickListener {

    String phoneNum;
    String code;
    String action;

    //最后获取验证码的时间
    int lastGetCodeTime = 0;


    //手机号是否已经注册过
    boolean isRegisted = false;

    private TitleBar tb_title;
    private TextView tv_phone;
    private EditText et_code;
    private TextView tv_get_code;
    private LinearLayout lin_login_pass;
    private TextView text_pass_tip;
    private EditText et_password;
    private RoundCornerButton rcb_submit;
    Context context = this;
    //计时器
    private Timer timer;

    //按钮是否可点击
    private boolean isDisable = false;
    private boolean isFromSplash;
    private boolean isRegisterFromRedPacket;

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

    @Override
    protected void initDataAndEvent() {
        tb_title = findViewById(R.id.tb_title);
        tv_phone = findViewById(R.id.tv_phone);
        et_code = findViewById(R.id.et_code);
        tv_get_code = findViewById(R.id.tv_get_code);
        lin_login_pass = findViewById(R.id.lin_login_pass);
        text_pass_tip = findViewById(R.id.text_pass_tip);
        et_password = findViewById(R.id.et_password);
        rcb_submit = findViewById(R.id.rcb_submit);

        rcb_submit.setOnClickListener(this);
        tv_get_code.setOnClickListener(this);


        phoneNum = getIntent().getStringExtra("phoneNum");
        code = getIntent().getStringExtra("code");
        action = getIntent().getStringExtra("action");
        //最后获取验证码的时间
        lastGetCodeTime = getIntent().getIntExtra("lastGetCodeTime", 0);
        isRegisted = getIntent().getBooleanExtra("isRegisted", false);
        isFromSplash = getIntent().getBooleanExtra("isFromSplash", false);
        isRegisterFromRedPacket = getIntent().getBooleanExtra(UserConstants.IS_REGISTER_FROM_PACKET, false);
        init();
        timer = new Timer(true);
        timer.schedule(new UpdateUITimer(), 0, 1000);

        Observable.timer(300, TimeUnit.MILLISECONDS)
                .subscribe(aLong -> {
                    InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                    inputMethodManager.showSoftInput(et_code, 0);
                });
    }


    private class UpdateUITimer extends TimerTask {
        @Override
        public void run() {
            updateUI();
        }
    }

    void updateUI() {
        runOnUiThread(() -> {
            if (tv_get_code != null) {
                int currentTimeInSecond = (int) (System.currentTimeMillis() / 1000);
                int leftTime = currentTimeInSecond - lastGetCodeTime;
                if (leftTime > UserConstants.MIN_GET_CODE_TIME) {
                    if (isDisable) {
                        tv_get_code.setTextColor(0xFF49D281);
                        tv_get_code.setText("重新获取");
                        isDisable = false;
                    }
                } else {
                    tv_get_code.setTextColor(0xFFADADAD);
                    isDisable = true;
                    tv_get_code.setText(
                            String.format("重发(%d)", UserConstants.MIN_GET_CODE_TIME - leftTime)
                    );
                }
            }
        });

    }

    void init() {

        if (action.equals(UserConstants.BIND_PHONE_ACTION) && isRegisted) {

            //隐藏登录密码栏
            lin_login_pass.setVisibility(View.GONE);
            text_pass_tip.setVisibility(View.GONE);
        } else if (action.equals(FORGET_ACTION)) {
            tb_title.setTitle("找回密码");
        } else if (action.equals(UserConstants.CHANGE_ACTION)) {
            tb_title.setTitle("修改密码");
        } else if (action.equals(REGISTER_ACTION)) {
            tb_title.setTitle("注册");
            rcb_submit.setText("注册");
        }
        if (phoneNum.length() >= 11) {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < 11; i++) {
                if (i == 2 || i == 5)
                    sb.append(phoneNum.charAt(i) + " ");
                else
                    sb.append(phoneNum.charAt(i));
            }
            tv_phone.setText(sb.toString());
        } else {
            tv_phone.setText(phoneNum);
        }


    }


    @Override
    public void onClick(View v) {
        int i = v.getId();
        if (i == R.id.rcb_submit) {
            if (!judge()) {
                return;
            }
            switch (action) {
                case UserConstants.CHANGE_ACTION:
                case FORGET_ACTION:
                    forget();
                    break;
                case REGISTER_ACTION:
                    register();
                    break;
                case UserConstants.BIND_PHONE_ACTION:
                    bindPhone();
                    break;

            }

        } else if (i == R.id.tv_get_code) {
            if (!isDisable) {
                getCode();
            }
        }
    }

    private UserHttp userHttp = UserHttpImpl.Companion.getInstance();

    /**
     * 绑定手机
     */
    private void bindPhone() {

        userHttp.bindPhone(new BindPhoneParam(code, phoneNum,
                et_code.getText().toString(), et_password.getText().toString()))
                .compose(RxUtils.resultData())
                .observeOn(AndroidSchedulers.mainThread())
                .doOnSubscribe(disposable -> showProgressDialog(""))
                .doAfterTerminate(this::dismissProgressDialog)
                .subscribe(loginResponse -> {
                    if (loginResponse != null && !TextUtils.isEmpty(loginResponse.getAccessToken())) {
                        RouterManager.INSTANCE.getImRouter().logout();
//                        RouterManager.INSTANCE.getImRouter().clear();

                        //绑定成功，重新登录IM
                        UserHelper.INSTANCE.setUserinfo(loginResponse);
                        RouterManager.INSTANCE.getImRouter().login(
                                new IMLoginInfo(loginResponse.getUid(), loginResponse.getHxpwd()), null);
                        LogHelper.Companion.getInstance().writeLogSync("绑定手机成功");
                    } else {
                        //更新本地信息
                        UserHelper.INSTANCE.getUserInfo().getUserInfo().setPhone(phoneNum);
                        UserHelper.INSTANCE.getUserInfo().getUserInfo().setBind_phone(1);
                    }

                    ToastHelper.Companion.show("手机绑定成功");
                    finish();
                    EventBus.getDefault().post(new UpdateBindStatusEvent());
                }, new ThrowableConsumer() {
                    @Override
                    public void accept(@NotNull String msg) {
                        ToastHelper.Companion.show(msg);
                        LogHelper.Companion.getInstance().writeLogSync(String.format("绑定手机失败：%s", msg));
                    }
                });

    }

    private boolean judge() {
        if (TextUtils.isEmpty(et_code.getText().toString())) {
            ToastHelper.Companion.show("请输入验证码");
            return false;
        }

        if (action.equals(UserConstants.BIND_PHONE_ACTION)) {
            return true;
        } else if (et_password.getText().toString().length() < 6 || et_password.getText().toString().length() > 12) {
            ToastHelper.Companion.show("密码长度6-16位");
            return false;
        }
        return true;
    }

    /**
     * 是忘记密码的操作
     */
    private void forget() {

        userHttp.forget(new ForgetParam(code, phoneNum, et_password.getText().toString(), et_code.getText().toString()))
                .compose(RxUtils.resultData())
                .observeOn(AndroidSchedulers.mainThread())
                .doOnSubscribe(disposable ->
                        showProgressDialog("")
                )
                .doAfterTerminate(this::dismissProgressDialog)
                .subscribe(o -> {
                    ToastHelper.Companion.show("修改密码成功");
                    LogHelper.Companion.getInstance().writeLogSync("修改密码成功");
                    finish();
                }, new ThrowableConsumer() {
                    @Override
                    public void accept(@NotNull String msg) {
                        ToastHelper.Companion.show(msg);
                        LogHelper.Companion.getInstance().writeLogSync(String.format("修改密码失败：%s", msg));
                    }
                });
    }

    /**
     * 注册的操作
     */
    private void register() {

        userHttp.register(new RegisterParam(code, phoneNum,
                et_password.getText().toString(),
                et_code.getText().toString()))
                .compose(RxUtils.resultData())
                .observeOn(AndroidSchedulers.mainThread())
                .doOnSubscribe(disposable -> showProgressDialog(""))
                .doAfterTerminate(this::dismissProgressDialog)
                .subscribe(o -> {
                            LoginHelper.isRegister = true;
                            login(phoneNum, et_password.getText().toString());
                            LogHelper.Companion.getInstance().writeLogSync("注册成功");
                        },
                        new ThrowableConsumer() {
                            @Override
                            public void accept(@NotNull String msg) {
                                ToastHelper.Companion.show(msg);
                                LogHelper.Companion.getInstance().writeLogSync( String.format("注册失败：%s", msg));
                            }
                        });
    }


    /**
     * 登陆
     *
     * @param phoneNum
     * @param password
     */
    private void login(final String phoneNum, final String password) {

        userHttp.login(new LoginParam(code, phoneNum, EncryptUtils.encryptMD5ToString(password), 1, null))
                .compose(RxUtils.resultData())
                .observeOn(AndroidSchedulers.mainThread())
                .doOnSubscribe(disposable -> showProgressDialog(""))
                .doAfterTerminate(this::dismissProgressDialog)
                .subscribe(loginResponse -> {

                    LoginHelper.login(loginResponse);
                    LogHelper.Companion.getInstance().writeLogSync("注册后登录成功");
                    IMLoginInfo info = new IMLoginInfo(
                            String.valueOf(loginResponse.getUid()),
                            loginResponse.getHxpwd()
                    ); // config...
                    IMRequestCallback<IMLoginInfo> callback =
                            new IMRequestCallback<IMLoginInfo>() {
                                @Override
                                public void onSuccess(IMLoginInfo loginInfo) {
                                    setHXinfo(loginResponse);
                                }

                                @Override
                                public void onFailed(int i) {//服务器一直无反映.30秒后回调,错误408
                                    ToastHelper.Companion.show("网络超时");
                                }

                                @Override
                                public void onException(Throwable throwable) {
                                    ToastHelper.Companion.show("未知错误02");
                                }

                            };
                    UserIn.INSTANCE.imSetAccount(info.getAccount());
                    UserIn.INSTANCE.imLogin(info, callback);
                }, new ThrowableConsumer() {
                    @Override
                    public void accept(@NotNull String msg) {
                        ToastHelper.Companion.show(msg);
                        LogHelper.Companion.getInstance().writeLogSync("注册后登录失败" + msg);
                    }
                });

    }

    /**
     * 获取验证码
     */
    private void getCode() {
        lastGetCodeTime = (int) (System.currentTimeMillis() / 1000);
        String smsAction = "";
        if (action == REGISTER_ACTION) {
            smsAction = REGISTER_ACTION;
        } else {
            smsAction = FORGET_ACTION;
        }
        userHttp.code(new CodeParam(code, phoneNum, smsAction))
                .compose(RxUtils.resultData())
                .observeOn(AndroidSchedulers.mainThread())
                .doOnSubscribe(disposable -> showProgressDialog(""))
                .doAfterTerminate(this::dismissProgressDialog)
                .subscribe(o -> ToastHelper.Companion.show("验证码已发送"),
                        new ThrowableConsumer() {
                            @Override
                            public void accept(@NotNull String msg) {
                                ToastHelper.Companion.show(msg);
                            }
                        });

    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        timer.cancel();
    }

    //用户信息 获取登陆信息
    public void setHXinfo(UserResponse userInfo) {

        try {
            if (userInfo != null) {
                UserHelper.INSTANCE.setUserinfo(userInfo);
                UserIn.INSTANCE.imSetAccount(userInfo.getUid() + "");
                //流程改了 不需要跳转 用户完善信息界面了
                EventBus.getDefault().post(new RefreshWebEvent());
                startActivity(UserIn.INSTANCE.mainIntent(this));
                ActivityManager.Companion.finishActivity(InputPhoneActivity.class);
                ActivityManager.Companion.finishActivity(LoginActivity.class);
                finish();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}
