package com.rdiot.yx485.login;

import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.view.View;

import androidx.annotation.NonNull;

import com.king.zxing.util.LogUtils;
import com.rdiot.yx485.BaseActivity;
import com.rdiot.yx485.R;
import com.rdiot.yx485.databinding.FraLoginPwdBinding;
import com.rdiot.yx485.http.Url;
import com.rdiot.yx485.login.view.OnDialogClickListener;
import com.rdiot.yx485.login.view.PersonalInfoProtectTips;
import com.rdiot.yx485.login.viewModel.LoginViewModel;
import com.rdiot.yx485.main.MainActivityTab;
import com.rdiot.yx485.util.IntentUtils;
import com.rdiot.yx485.util.LocalCache;
import com.rdiot.yx485.webview.WebViewActivity;

import org.jetbrains.annotations.NotNull;

import java.util.Objects;

public class LoginWithPwdActivity extends BaseActivity {
    private static final int COUNTDOWN_TIME = 60000; // 60秒
    private static final int COUNTDOWN_INTERVAL = 1000; // 1秒间隔
    private final LoginViewModel mViewModel = new LoginViewModel();
    private FraLoginPwdBinding mBinding;
    private CountDownTimer countDownTimer;

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

        initView();
        initData();
        setupAgreementText();
    }

    private void setupAgreementText() {
        String fullText = "勾选即代表同意《永续绿建用户协议》和《隐私政策》，首次登录我们需要获取您的手机号进行身份验证";
        SpannableString spannableString = new SpannableString(fullText);

        // 用户协议点击事件
        ClickableSpan userAgreementClick = new ClickableSpan() {
            @Override
            public void onClick(@NonNull View widget) {
                // 跳转到用户协议页面
                WebViewActivity.newIntent(LoginWithPwdActivity.this,
                        Url.BASE_URL2 + "/#/ServiceAgreement", "永续绿建用户协议");
            }

            @Override
            public void updateDrawState(TextPaint ds) {
                ds.setColor(getResources().getColor(R.color.colorPrimary));
                ds.setUnderlineText(false);
            }
        };

        // 隐私政策点击事件
        ClickableSpan privacyPolicyClick = new ClickableSpan() {
            @Override
            public void onClick(@NonNull View widget) {
                // 跳转到隐私政策页面
                WebViewActivity.newIntent(LoginWithPwdActivity.this,
                        Url.BASE_URL2 + "/#/PrivacyPolicy", "隐私政策");
            }

            @Override
            public void updateDrawState(TextPaint ds) {
                ds.setColor(getResources().getColor(R.color.colorPrimary));
                ds.setUnderlineText(false);
            }
        };

        // 设置可点击范围
        spannableString.setSpan(userAgreementClick,
                fullText.indexOf("《永续绿建用户协议》"),
                fullText.indexOf("《永续绿建用户协议》") + "《永续绿建用户协议》".length(),
                Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

        spannableString.setSpan(privacyPolicyClick,
                fullText.indexOf("《隐私政策》"),
                fullText.indexOf("《隐私政策》") + "《隐私政策》".length(),
                Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

        // 设置文本
        mBinding.tvAgreement.setText(spannableString);
        // 设置文本可点击
        mBinding.tvAgreement.setMovementMethod(LinkMovementMethod.getInstance());
    }

    private void initView() {
        mBinding.title.setOnClickListener(view -> {
            String type = mViewModel.getLoginType().getValue();
            if ("验证码登录".equals(type)) {
                mViewModel.getLoginType().setValue("密码登录");
            } else {
                mViewModel.getLoginType().setValue("验证码登录");
            }
        });
        mBinding.btnForgetPwd.setOnClickListener(view -> {
            IntentUtils.intentToSetPwd(this, false);
        });
        mBinding.tvGetSmsCode.setOnClickListener(v -> {
            String phone = Objects.requireNonNull(mBinding.etPhone.getText()).toString().trim();
            if (TextUtils.isEmpty(phone)) {
                showMessage("请输入手机号");
                return;
            }
            if (phone.length() != 11) {
                showMessage("请输入正确的手机号");
                return;
            }
            // 发送验证码
            mBinding.tvGetSmsCode.setEnabled(false);
            mViewModel.sendSmsCode(phone);
        });
        mBinding.btnLogin.setOnClickListener(view -> {
            login();
        });
    }

    private void initData() {
        boolean agree = LocalCache.isAgree();
        if (!agree) {
            showAgreeDialog();
        }

        LoginAccountBean bean = LocalCache.getLoginAccount();
        mBinding.etPhone.setText(bean.phone);
        mBinding.etPwd.setText(bean.password);
        LogUtils.d(bean.toString());

        mViewModel.getLoginType().observe(this, this::refreshView);
        mViewModel.getErrorMessage().observe(this, error -> {
            mBinding.loading.setVisibility(View.GONE);
            mBinding.tvGetSmsCode.setEnabled(true);
            showMessage(error);
        });
        mViewModel.getSendState().observe(this, success -> {
            if (success) {
                startCountDown();
            } else {
                mBinding.tvGetSmsCode.setEnabled(true);
            }
        });
        mViewModel.getLoginState().observe(this, loginSuccess -> {
            mBinding.loading.setVisibility(View.GONE);
            if (loginSuccess) {
                MainActivityTab.newIntent(this, true);
                finish();
            }
        });
    }

    private void showAgreeDialog() {
        PersonalInfoProtectTips dialog = new PersonalInfoProtectTips(this);
        dialog.setOnClickListener(new OnDialogClickListener() {
            @Override
            public void onCancel() {
                onBackPressed();
            }

            @Override
            public void onConfirm() {
                LocalCache.saveAgree();
            }
        });
        dialog.show();
    }

    private void startCountDown() {
        if (countDownTimer != null) {
            countDownTimer.cancel();
        }

        countDownTimer = new CountDownTimer(COUNTDOWN_TIME, COUNTDOWN_INTERVAL) {
            @Override
            public void onTick(long millisUntilFinished) {
                int seconds = (int) (millisUntilFinished / 1000);
                mBinding.tvGetSmsCode.setText(seconds + "s后重新获取");
            }

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

    private void refreshView(@NotNull String type) {
        mBinding.title.setText(type);
        if ("验证码登录".equals(type)) {
            mBinding.layoutInputPwd.setVisibility(View.VISIBLE);
            mBinding.layoutInputCode.setVisibility(View.GONE);
        } else {
            mBinding.layoutInputPwd.setVisibility(View.GONE);
            mBinding.layoutInputCode.setVisibility(View.VISIBLE);
        }
    }

    private void login() {
        if (!mBinding.isxuanze.isChecked()) {
            showMessage("请勾选用户协议和隐私政策");
            return;
        }

        String phone = Objects.requireNonNull(mBinding.etPhone.getText()).toString().trim();
        if (TextUtils.isEmpty(phone)) {
            showMessage("请输入手机号");
            return;
        }
        if (phone.length() != 11) {
            showMessage("请输入正确的手机号");
            return;
        }

        // 显示登录中弹窗
        mBinding.loading.setVisibility(View.VISIBLE);

        if ("验证码登录".equals(mViewModel.getLoginType().getValue())) {
            String pwd = Objects.requireNonNull(mBinding.etPwd.getText()).toString().trim();
            if (TextUtils.isEmpty(pwd)) {
                showMessage("请输入密码");
                mBinding.loading.setVisibility(View.GONE);
                return;
            }
            mViewModel.loginWithPwd(phone, pwd);
            return;
        }

        String code = Objects.requireNonNull(mBinding.etCode.getText()).toString().trim();
        if (TextUtils.isEmpty(code)) {
            showMessage("请输入验证码");
            mBinding.loading.setVisibility(View.GONE);
            return;
        }
        mViewModel.loginWithSms(phone, code);
    }

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