package top.octopusyan.controller;

import com.jfoenix.controls.JFXButton;
import com.jfoenix.controls.JFXPasswordField;
import com.jfoenix.controls.JFXTextField;
import javafx.application.Platform;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.layout.StackPane;
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.NotNull;
import top.octopusyan.base.BaseController;
import top.octopusyan.config.TextValidate;
import top.octopusyan.http.EasyHttp;
import top.octopusyan.http.listener.OnHttpListener;
import top.octopusyan.manager.http.Api;
import top.octopusyan.manager.http.request.RegisterParam;
import top.octopusyan.manager.http.request.SendEmailCheckParam;
import top.octopusyan.model.ApplicatonStore;
import top.octopusyan.utils.AlertUtil;
import top.octopusyan.utils.JsoupUtil;

import java.io.IOException;
import java.io.Serializable;

/**
 * @author : octopus yan
 * @email : octopus_yan@foxmail.com
 * @description :  注册表单
 * @create : 2022-4-3 22:39
 */
public class RegisterController extends BaseController<StackPane> implements Serializable {

    @FXML
    public StackPane root;

    @FXML
    public JFXButton closeBtn, minimizeBtn;
    @FXML
    public JFXTextField accooundTextField, emailTf, emailCheckCodeTf;
    @FXML
    public JFXButton registerBtn, sendCheckCodeBtn;
    @FXML
    public JFXPasswordField passwordTextField;
    @FXML
    public JFXButton loginBtn;
    @FXML
    public Label appVersionLabel;

    @Override
    public boolean dragWindow() {
        return true;
    }

    @Override
    public StackPane getRootPanel() {
        return root;
    }

    @NotNull
    @Override
    public String getRootFxmlPath() {
        return "/fxml/register.fxml";
    }

    @Override
    public Label getAppVersionLabel() {
        return appVersionLabel;
    }

    @Override
    public Button getClooseBtn() {
        return closeBtn;
    }

    @Override
    public Button getMinimizeBtn() {
        return minimizeBtn;
    }

    @Override
    public JFXButton getFirstBtn() {
        return minimizeBtn;
    }

    @Override
    public void initData() {
        String account = ApplicatonStore.getAccount();
        String password = ApplicatonStore.getPassword();

        if (StringUtils.isNotEmpty(account)) accooundTextField.setText(account);
        if (StringUtils.isNotEmpty(password)) passwordTextField.setText(password);
    }

    @Override
    public void initViewStyle() {

        // 记录账号
        accooundTextField.textProperty().addListener((observable, oldValue, newValue) -> ApplicatonStore.setAccount(newValue));
        // 记录密码
        passwordTextField.textProperty().addListener((observable, oldValue, newValue) -> ApplicatonStore.setPassword(newValue));
        // 记录密码
        emailTf.textProperty().addListener((observable, oldValue, newValue) -> ApplicatonStore.setEmail(newValue));

        // 添加文本验证
        accooundTextField.getValidators().add(TextValidate.AccoountRequired);
        accooundTextField.getValidators().add(TextValidate.AccoountValidator);
        accooundTextField.getValidators().add(TextValidate.getLengthValidator(6, 18, "账号"));
        passwordTextField.getValidators().add(TextValidate.PasswordRequired);
        emailTf.getValidators().add(TextValidate.EmailFormat);
        emailCheckCodeTf.getValidators().add(TextValidate.getLengthValidator("验证码", 6));

        // 文本验证
        accooundTextField.focusedProperty().addListener((observable, oldValue, newValue) -> {
            if (newValue) accooundTextField.resetValidation();
            else accooundTextField.validate();
        });
        emailTf.focusedProperty().addListener((observable, oldValue, newValue) -> {
            if (newValue) emailTf.resetValidation();
            else emailTf.validate();
        });
        passwordTextField.focusedProperty().addListener((observable, oldValue, newValue) -> {
            if (newValue) passwordTextField.resetValidation();
            else passwordTextField.validate();
        });
        emailCheckCodeTf.focusedProperty().addListener((observable, oldValue, newValue) -> {
            if (newValue)
                emailCheckCodeTf.resetValidation();
            else
                emailCheckCodeTf.validate();
        });
    }

    @Override
    public void initViewAction() {
        // 登录
        loginBtn.setOnMouseClicked(event -> {
            try {
                jumpTo(new LoginController());
            } catch (IOException e) {
                e.printStackTrace();
            }
        });

        // 点击了发送验证码
        sendCheckCodeBtn.setOnMouseClicked(event -> {
            // 如果邮箱地址正确
            if (emailTf.validate()) {
                // 发送邮箱验证
                EasyHttp.builder()
                        .api(Api.SendEmailCheck)
                        .param(new SendEmailCheckParam(emailTf.getText()))
                        .request(new OnHttpListener<String>() {
                            @Override
                            public void onSucceed(String result) {
                                Platform.runLater(() -> AlertUtil.info("系统已发送一封邮件至您的邮箱，请查收。").show());
                            }

                            @Override
                            public void onFail(Exception e) {

                            }
                        });
            }
        });

        // 注册
        registerBtn.setOnMouseClicked(event -> register());
    }

    private void register() {
        // 文本校验
        if (accooundTextField.validate() && passwordTextField.validate() && emailTf.validate() && emailCheckCodeTf.validate()) {
            EasyHttp.builder()
                    .api(Api.Register)
                    .param(new RegisterParam(
                            ApplicatonStore.getAccount(),
                            ApplicatonStore.getPassword(),
                            ApplicatonStore.getEmail(),
                            emailCheckCodeTf.getText()
                    ))
                    .request(new OnHttpListener<String>() {
                        @Override
                        public void onSucceed(String result) {

                            // 注册出错
                            if (JsoupUtil.isAlertSuccess(result)) {
                                // 注册成功
                                Platform.runLater(() ->
                                        AlertUtil.info(JsoupUtil.getSuccessMessage(result)).header(null).show()
                                );
                                ApplicatonStore.setRegisterSuccess(true);
                                Platform.runLater(() -> {
                                    try {
                                        jumpTo(new LoginController());
                                    } catch (IOException e) {
                                        e.printStackTrace();
                                    }
                                });
                            } else
                                Platform.runLater(() ->
                                        AlertUtil.error(JsoupUtil.getErrorMessage(result)).header(null).show()
                                );
                        }

                        @Override
                        public void onFail(Exception e) {

                        }
                    });
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }
}
