package com.cooleshow.student.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.student.R;
import com.cooleshow.student.contract.ModifyPasswordContract;
import com.cooleshow.student.databinding.ActivityModifyPasswordBinding;
import com.cooleshow.student.presenter.mine.ModifyPasswordPresenter;
import com.cooleshow.usercenter.constants.UserConstants;
import com.cooleshow.usercenter.helper.UserHelper;


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 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 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;
        }
    }

    @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, phoneNum.length());
        viewBinding.tvPhone.setText(cPhone);
    }


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

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

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

    @Override
    public void updatePasswordSuccess(Object object) {
        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();
        }
        Map<String, String> map = new HashMap<>();
        map.put("mobile", phone);
        map.put("type", "PASSWD");
        presenter.sendSmsCode(map);
    }


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

    /**
     * 执行完成
     */
    public static final int EXECUTE_FINISH = 0X11000;
    /**
     * 执行中
     */
    public static final int EXECUTE_LOADING = 0X4000;
    private int mTimerId = 60;

    private TimerTask timerTask;

    private Timer timer;

    /**
     * 开始倒计时
     */
    private void startTimer() {

        if (timerTask == null) {
            timerTask = new TimerTask() {
                @Override
                public void run() {
                    Message msg = new Message();
                    msg.what = EXECUTE_LOADING;
                    msg.arg1 = --mTimerId;
                    handler.sendMessage(msg);
                }
            };
            timer = new Timer();
            timer.schedule(timerTask, 100, 1000);
        }
    }

    /**
     * 结束计时
     */
    private void closeTimer() {
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
        if (timerTask != null) {
            timerTask = null;
        }
        mTimerId = 60;
        handler.sendEmptyMessage(EXECUTE_FINISH);
    }

    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case EXECUTE_LOADING:
                    viewBinding.tvGetAuthCode.setText(msg.arg1 + "s");
                    viewBinding.tvGetAuthCode.setClickable(false);
                    if (msg.arg1 == 0) {
                        closeTimer();
                        viewBinding.tvGetAuthCode.setClickable(true);
                    }
                    break;
                case EXECUTE_FINISH:
                    viewBinding.tvGetAuthCode.setClickable(true);
                    viewBinding.tvGetAuthCode.setText("获取验证码");
                    break;
            }
            super.handleMessage(msg);
        }
    };

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
        if (timerTask != null) {
            timerTask = null;
        }
        if (handler != null) {
            handler.removeCallbacksAndMessages(null);
        }
    }
}
