package com.cooleshow.usercenter.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.SpannableString;
import android.text.TextUtils;
import android.view.View;

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.KeyboardUtils;
import com.cooleshow.base.utils.ToastUtils;
import com.cooleshow.base.utils.Utils;
import com.cooleshow.base.utils.helper.QMUIStatusBarHelper;
import com.cooleshow.base.widgets.VerifyEditText;
import com.cooleshow.usercenter.R;
import com.cooleshow.usercenter.UserConstants;
import com.cooleshow.usercenter.bean.UserLoginInfo;
import com.cooleshow.usercenter.databinding.ActivityInputCodeLayoutBinding;
import com.cooleshow.usercenter.helper.UserHelper;
import com.cooleshow.usercenter.presenter.VerifyLoginPresenter;
import com.cooleshow.usercenter.presenter.contract.VerifyLoginContract;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

/**
 * Author by pq, Date on 2022/4/19.
 */
@Route(path = RouterPath.UserCenter.PATH_VERIFY_INPUT)
public class VerifyCodeInputActivity extends BaseMVPActivity<ActivityInputCodeLayoutBinding, VerifyLoginPresenter> implements VerifyLoginContract.VerifyLoginView, View.OnClickListener {
    public static final String TARGET_PHONE = "target_phone";
    public static final int TIME_COUNT_SPACE = 1000;
    public static final int TIME_COUNT_TOTAL = 10000;
    public static final int REQUEST_CODE_FOR_SET_PASSWORD = 100001;
    private String mPhoneNum;

    private CountDownTimer mCountDownTimer = new CountDownTimer(TIME_COUNT_TOTAL, TIME_COUNT_SPACE) {
        @Override
        public void onTick(long millisUntilFinished) {
            if (viewBinding.tvResendCode != null) {
                int lastTime = (int) (millisUntilFinished / TIME_COUNT_SPACE);
                viewBinding.tvResendCode.setText(getString(R.string.verify_input_count_time_tip, lastTime));
            }
        }

        @Override
        public void onFinish() {
            switchSendCodeButton(true);
        }
    };

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        QMUIStatusBarHelper.setStatusBarLightMode(this);
    }

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

    @Override
    protected void initView() {
        mPhoneNum = getIntent().getStringExtra(TARGET_PHONE);
        if (TextUtils.isEmpty(mPhoneNum)) {
            finish();
            return;
        }
        SpannableString string = Utils.diffColorString(getString(R.string.verify_input_phone_tip), mPhoneNum, getResources().getColor(R.color.black), getResources().getColor(com.cooleshow.base.R.color.color_999999));
        viewBinding.tvTipTargetPhone.setText(string);
        switchSendCodeButton(false);
        viewBinding.ivBack.setOnClickListener(this);
        viewBinding.tvResendCode.setOnClickListener(this);
        viewBinding.editCode.addInputCompleteListener(new VerifyEditText.InputCompleteListener() {
            @Override
            public void complete(String content) {
                //输入完成
                login(content);
            }
        });
    }

    private void login(String content) {
        KeyboardUtils.hideSoftInput(this);
        if (!TextUtils.isEmpty(mPhoneNum) && !TextUtils.isEmpty(content)) {
            if (presenter != null) {
                presenter.loginByVerifyCode(mPhoneNum, content);
            }
        }
    }

    @Override
    public void initData() {
        super.initData();
        sendVerifyCode();
    }

    private void sendVerifyCode() {
        if (presenter != null && !TextUtils.isEmpty(mPhoneNum)) {
            presenter.sendVerifyCode(mPhoneNum);
        }
    }

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


    private void switchSendCodeButton(boolean isAble) {
        if (viewBinding.tvResendCode != null) {
            viewBinding.tvResendCode.setClickable(isAble);
            viewBinding.tvResendCode.setBackgroundResource(isAble ? com.cooleshow.base.R.drawable.shape_login_bt_bg : com.cooleshow.base.R.drawable.shape_login_bt_bg_unselect);

            if (isAble) {
                viewBinding.tvResendCode.setText(getString(R.string.verify_input_resend_tip));
            }
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mCountDownTimer != null) {
            mCountDownTimer.cancel();
            mCountDownTimer = null;
        }
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.iv_back) {
            //返回键
            finish();
            return;
        }
        if (v.getId() == R.id.tv_resend_code) {
            //重新发送
            sendVerifyCode();
        }
    }

    /**
     * 发送验证码成功
     */
    @Override
    public void sendVerifyCodeSuccess() {
        ToastUtils.showShort(R.string.verify_code_send_success_tip);
        switchSendCodeButton(false);
        if (mCountDownTimer != null) {
            mCountDownTimer.start();
        }
    }

    /**
     * 发送验证码失败
     */
    @Override
    public void sendVerifyCodeFail() {
        switchSendCodeButton(true);
        if (mCountDownTimer != null) {
            mCountDownTimer.cancel();
        }
    }

    @Override
    public void loginByCodeSuccess(UserLoginInfo data) {
        //添加公共参数
        if (isFinishing() || isDestroyed()) {
            return;
        }
        if (data != null) {
            if (data.password) {
                //有设置密码
                UserHelper.handleLoginSuccessAction(data);
                setLoginResult();
            } else {
                //无密码,跳设置密码
                String tempToken = UserHelper.handleLoginSuccessActionNotSave(data);
                ARouter.getInstance().build(RouterPath.UserCenter.PATH_BIND_PASSWORD).withString(UserConstants.TEMP_TOKEN, tempToken).navigation(this, REQUEST_CODE_FOR_SET_PASSWORD);
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == REQUEST_CODE_FOR_SET_PASSWORD) {
                //设置密码成功
                if (data != null) {
                    String tokenResult = data.getStringExtra(UserConstants.TEMP_TOKEN);
                    UserHelper.saveUserToken(tokenResult);
                    setLoginResult();
                }
            }
        }
    }

    private void setLoginResult() {
        Intent intent = new Intent();
        intent.putExtra(UserConstants.LOGIN_STATUS, UserConstants.LOGIN_STATUS_SUCCESS);
        setResult(RESULT_OK, intent);
        finish();
    }
}
