package com.rdiot.yx485.login;

import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.TextUtils;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.View;
import android.widget.Toast;

import androidx.lifecycle.ViewModelProvider;

import com.rdiot.yx485.BaseActivity;
import com.rdiot.yx485.databinding.ActSetPwdBinding;
import com.rdiot.yx485.login.viewModel.LoginViewModel;
import com.rdiot.yx485.util.LocalCache;

public class SetPwdActivity extends BaseActivity {
    private static final String regex = "^(?![a-zA-Z]+$)(?![0-9]+$)(?![^a-zA-Z0-9]+$)[\\w!@#$%^&*()-+=]{8,20}$";
    private ActSetPwdBinding binding;
    private LoginViewModel viewModel;
    private CountDownTimer countDownTimer;
    private boolean isFirstLogin;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActSetPwdBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        isFirstLogin = getIntent().getBooleanExtra("isFirst", false);
        viewModel = new ViewModelProvider(this).get(LoginViewModel.class);
        initView();
        observeViewModel();
        initCountDownTimer();
    }

    private void initCountDownTimer() {
        countDownTimer = new CountDownTimer(60000, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                binding.tvGetSmsCode.setEnabled(false);
                binding.tvGetSmsCode.setText(String.format("%ss后重新获取", millisUntilFinished / 1000));
            }

            @Override
            public void onFinish() {
                binding.tvGetSmsCode.setEnabled(true);
                binding.tvGetSmsCode.setText("获取验证码");
            }
        };
    }

    private void initView() {
        binding.layoutTitle.btnTitleLeft.setOnClickListener(v -> onBackPressed());
        binding.btnConfirm.setOnClickListener(v -> setpwd());
        binding.tvGetSmsCode.setOnClickListener(v -> getSmsCode());
        LoginAccountBean loginAccount = LocalCache.getLoginAccount();
        if (!TextUtils.isEmpty(loginAccount.phone)) {
            binding.etPhone.setText(loginAccount.phone);
        }

        if (isFirstLogin) {
            binding.etPhone.setVisibility(View.GONE);
            binding.layout.setVisibility(View.GONE);
            binding.tvSubtitle.setText("设置密码");
        } else {
            binding.tvSubtitle.setText("修改密码");
        }

        binding.imageNewpwd.setOnClickListener(view -> {
            binding.imageNewpwd.setVisibility(View.GONE);
            binding.imageNewpwdopen.setVisibility(View.VISIBLE);
            binding.etPwd.setTransformationMethod(PasswordTransformationMethod.getInstance());
        });

        binding.imageNewpwdopen.setOnClickListener(view -> {
            binding.imageNewpwd.setVisibility(View.VISIBLE);
            binding.imageNewpwdopen.setVisibility(View.GONE);
            binding.etPwd.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
        });

        binding.imagePwd.setOnClickListener(view -> {
            binding.imagePwd.setVisibility(View.GONE);
            binding.imagePwdopen.setVisibility(View.VISIBLE);
            binding.etConfirmPwd.setTransformationMethod(PasswordTransformationMethod.getInstance());
        });

        binding.imagePwdopen.setOnClickListener(view -> {
            binding.imagePwd.setVisibility(View.VISIBLE);
            binding.imagePwdopen.setVisibility(View.GONE);
            binding.etConfirmPwd.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
        });
    }

    private void observeViewModel() {
        viewModel.getSetPwdState().observe(this, success -> {
            if (success) {
                showMessage("设置成功");
                Toast.makeText(this, "设置成功", Toast.LENGTH_SHORT).show();
                finish();
            }
        });

        viewModel.getErrorMessage().observe(this, this::showMessage);

        viewModel.getSendState().observe(this, success -> {
            if (success) {
                countDownTimer.start();
            }
        });
    }

    private void setpwd() {
        String phone = binding.etPhone.getText().toString();
        String code = binding.etCode.getText().toString();
        String pwd = binding.etPwd.getText().toString();
        String confirmPwd = binding.etConfirmPwd.getText().toString();

        if (pwd.isEmpty() || confirmPwd.isEmpty()) {
            Toast.makeText(this, "请输入密码", Toast.LENGTH_SHORT).show();
            return;
        }

        if (!pwd.equals(confirmPwd)) {
            Toast.makeText(this, "两次密码不一致", Toast.LENGTH_SHORT).show();
            return;
        }

        if (!pwd.matches(regex)) {
            showMessage("密码不符合要求，密码为8-20位，字母、数字、符号至少包含2种");
            return;
        }

        viewModel.setPassword(phone, code, pwd, isFirstLogin);
    }

    private void getSmsCode() {
        String phone = binding.etPhone.getText().toString().trim();
        viewModel.sendSmsCodeForPwd(phone);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (countDownTimer != null) {
            countDownTimer.cancel();
        }
        binding = null;
    }
}