package com.cooleshow.teacher.ui.mine;

import android.annotation.SuppressLint;
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 androidx.annotation.Nullable;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.cooleshow.base.router.RouterPath;
import com.cooleshow.base.ui.activity.BaseMVPActivity;
import com.cooleshow.base.utils.ToastUtil;
import com.cooleshow.base.utils.ToastUtils;
import com.cooleshow.base.widgets.dialog.ImgVerifyCodeDialog;
import com.cooleshow.teacher.R;
import com.cooleshow.teacher.contract.ModifyPasswordContract;
import com.cooleshow.teacher.databinding.ActivityModifyPasswordBinding;
import com.cooleshow.teacher.presenter.mine.ModifyPasswordPresenter;
import com.cooleshow.usercenter.constants.UserConstants;
import com.cooleshow.usercenter.helper.UserHelper;

import org.jetbrains.annotations.NotNull;
import org.json.JSONException;
import org.json.JSONObject;

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

import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.core.Observable;
import io.reactivex.rxjava3.core.Observer;
import io.reactivex.rxjava3.disposables.Disposable;
import io.rong.imkit.utils.StatusBarUtil;

/**
 * 创建日期：2022/5/17 13:33
 *
 * @author Ryan
 * 类说明：
 */
@Route(path = RouterPath.MineCenter.MINE_MODIFY_PASSWORD)
public class ModifyPasswordActivity extends BaseMVPActivity<ActivityModifyPasswordBinding, ModifyPasswordPresenter> implements ModifyPasswordContract.ModifyPasswordView, View.OnClickListener {
    private Disposable disposable;
    private ImgVerifyCodeDialog mImgVerifyCodeDialog;

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_confirm:
                String password = viewBinding.etPassword.getText().toString().trim();
                if (TextUtils.isEmpty(password) || password.length() < 6 || password.length() > 20) {
                    ToastUtil.getInstance().showShort("请输入6-20位密码");
                    break;
                }
                String authCode = viewBinding.etAuthCode.getText().toString().trim();
                if (TextUtils.isEmpty(authCode)) {
                    ToastUtil.getInstance().showShort("请输入验证码");
                    break;
                }

                Map<String, String> params = new HashMap<>();
                params.put("mobile", phoneNum);
                params.put("authCode", authCode);
                params.put("newPassword", password);
                presenter.updatePassword(params);
                break;
            case R.id.tv_get_auth_code:
                showImgVerifyCodeDialog();
                break;
        }
    }

    private void showImgVerifyCodeDialog() {
        if (mImgVerifyCodeDialog == null) {
            mImgVerifyCodeDialog = new ImgVerifyCodeDialog(ModifyPasswordActivity.this);
        }
        if (!mImgVerifyCodeDialog.isShowing()) {
            mImgVerifyCodeDialog.show();
        }
        mImgVerifyCodeDialog.setPhone(phoneNum);
        mImgVerifyCodeDialog.setOnEventListener(new ImgVerifyCodeDialog.OnEventListener() {
            @Override
            public void onVerifyImgCode(String phone, String imgCode) {
                if (presenter != null) {
                    presenter.verifyImgCode(phone, imgCode);
                }
            }
        });
    }

    private void sendVerifyCode(String phone) {
        Map<String,String> jsonObject = new HashMap<>();
        jsonObject.put("mobile", phone);
        jsonObject.put("type", "PASSWD");
        presenter.sendSmsCode(jsonObject);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        StatusBarUtil.setStatusBarDarkTheme(this, true);
    }

    @Autowired(name = "phoneNum")
    String phoneNum;

    @Override
    protected void initView() {
        ARouter.getInstance().inject(this);
        initMidTitleToolBar(viewBinding.toolbarInclude.toolbar, "修改密码");
        viewBinding.tvConfirm.setOnClickListener(this);
        viewBinding.tvGetAuthCode.setOnClickListener(this);
        String cPhone = phoneNum.substring(0, 3) + "****" + phoneNum.substring(7);
        viewBinding.tvPhone.setText(cPhone);
    }

    @Override
    protected ActivityModifyPasswordBinding getLayoutView() {
        return ActivityModifyPasswordBinding.inflate(getLayoutInflater());
    }

    @Override
    protected ModifyPasswordPresenter createPresenter() {
        return new ModifyPasswordPresenter();
    }

    @Override
    public void updatePasswordSuccess(Object object) {
        ToastUtil.getInstance().showShort("修改成功");
        UserHelper.saveUserToken("");
        ARouter.getInstance().build(RouterPath.UserCenter.PATH_VERIFY_LOGIN)
                .withString(UserConstants.PHONE_NUM_KEY, UserHelper.getUserPhone())
                .addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK)
                .navigation();

        finish();
    }

    @Override
    public void sendSmsCodeSuccess(Object object) {
        getCodeSuccess();
    }

    @Override
    public void verifyImgCodeSuccess(String phone) {
        if (isFinishing() || isDestroyed()) {
            return;
        }
        if (mImgVerifyCodeDialog != null) {
            mImgVerifyCodeDialog.dismiss();
        }
        sendVerifyCode(phone);
    }


    public void getCodeSuccess() {
        ToastUtil.getInstance().showShort("验证码发送成功，请注意查收!");
        startTimer();

    }

    /**
     * 开始倒计时
     */
    private void startTimer() {
        Observable.interval(1000, TimeUnit.MILLISECONDS)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<Long>() {
                    @Override
                    public void onSubscribe(@NotNull Disposable d) {
                        disposable = d;
                    }

                    @Override
                    public void onNext(@NotNull Long aLong) {
                        if (aLong < 60) {
                            viewBinding.tvGetAuthCode.setText(59 - aLong + "s");
                            viewBinding.tvGetAuthCode.setClickable(false);
                        } else {
                            onComplete();
                        }
                    }

                    @Override
                    public void onError(@NotNull Throwable e) {

                    }

                    @Override
                    public void onComplete() {
                        closeTimer();
                    }
                });
    }

    /**
     * 结束计时
     */
    private void closeTimer() {
        if (disposable != null && !disposable.isDisposed()) {
            disposable.dispose();
        }
        viewBinding.tvGetAuthCode.setText("获取验证码");
        viewBinding.tvGetAuthCode.setClickable(true);
    }

    @Override
    public void onDestroy() {
        closeTimer();
        super.onDestroy();
    }
}
