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.ModifyPhoneNumContract;
import com.cooleshow.student.databinding.ActivityModifyPhonenumBinding;
import com.cooleshow.student.presenter.mine.ModifyPhoneNumPresenter;
import com.cooleshow.usercenter.bean.SetDetailBean;
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 10:49
 *
 * @author Ryan
 * 类说明：
 */
@Route(path = RouterPath.MineCenter.MINE_MODIFY_PHONENUM)
public class ModifyPhoneNumActivity extends BaseMVPActivity<ActivityModifyPhonenumBinding, ModifyPhoneNumPresenter> implements ModifyPhoneNumContract.ModifyPhoneNumView, View.OnClickListener {

    private ImgVerifyCodeDialog mImgVerifyCodeDialog;

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_get_auth_code:
                String phone = viewBinding.etPhoneNum.getText().toString().trim();
                if (TextUtils.isEmpty(phone)) {
                    ToastUtil.getInstance().showShort("请输入手机号");
                    break;
                }
                showImgVerifyCodeDialog(phone);
                break;
            case R.id.tv_save:
                String phoneNum = viewBinding.etPhoneNum.getText().toString().trim();
                if (TextUtils.isEmpty(phoneNum)) {
                    ToastUtil.getInstance().showShort("请输入手机号");
                    break;
                }
                String authCode = viewBinding.etAuthCode.getText().toString().trim();
                if (TextUtils.isEmpty(authCode)) {
                    ToastUtil.getInstance().showShort("请输入验证码");
                    break;
                }
                presenter.updatePhone(oldPhone, phoneNum, authCode);
                break;
        }
    }

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

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

    @Override
    protected void initView() {
        ARouter.getInstance().inject(this);
        initMidTitleToolBar(viewBinding.toolbarInclude.toolbar, "新手机号绑定");
        viewBinding.tvGetAuthCode.setOnClickListener(this);
        viewBinding.tvSave.setOnClickListener(this);
    }

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

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

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

    @Override
    public void updatePhoneSuccess(Object object) {
        ToastUtil.getInstance().showShort("修改成功");
        UserHelper.saveUserToken("");
        ARouter.getInstance().build(RouterPath.UserCenter.PATH_VERIFY_LOGIN)
                .withString(UserConstants.PHONE_NUM_KEY, UserHelper.getUserPhone())
                .navigation();
        finish();
    }

    @Override
    public void verifyImgCodeSuccess(String phone) {
        if (!checkActivityExist()) {
            return;
        }
        if (mImgVerifyCodeDialog != null) {
            mImgVerifyCodeDialog.dismiss();
        }
        sendSmsCode(phone);
    }

    @Override
    public void sendSmsCodeSuccess(SetDetailBean setDetailBean) {
        getCodeSuccess();
    }

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

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