Tea.context(function () {
	this.username = "";
	this.password = "";
	this.passwordMd5 = "";
	this.encodedFrom = window.encodeURIComponent(this.from);

	this.showOTP = false

	this.isSubmitting = false

	const BASE_URL = window.location.origin;
	const googleRedirectUri = `${BASE_URL}/login/oauth2callback?provider=google`;
	this.googleAuthUri = `https://accounts.google.com/o/oauth2/auth?client_id=${this.googleAuthClientId}&redirect_uri=${encodeURIComponent(googleRedirectUri)}&response_type=code&scope=openid email profile&access_type=offline&prompt=select_account`;

	const githubRedirectUri = `${BASE_URL}/login/oauth2callback?provider=github`;
	this.githubAuthUri = `https://github.com/login/oauth/authorize?client_id=${this.githubAuthClientId}&redirect_uri=${encodeURIComponent(githubRedirectUri)}&prompt=select_account`;

	const gitlabRedirectUri = `${BASE_URL}/login/oauth2callback?provider=gitlab`;
	this.gitlabAuthUri = `https://gitlab.com/oauth/authorize?client_id=${this.gitlabAuthClientId}&redirect_uri=${encodeURIComponent(gitlabRedirectUri)}&response_type=code&scope=read_user&max_age=60`;

	const twitterRedirectUri = `${BASE_URL}/login/oauth2callback?provider=twitter`;
	this.twitterAuthUri = `https://twitter.com/i/oauth2/authorize?response_type=code&client_id=${this.twitterAuthClientId}&redirect_uri=${encodeURIComponent(twitterRedirectUri)}&scope=users.read%20email.read&prompt=login`;
	
	this.$delay(function () {
		this.$find("form input[name='username']").focus();
		this.changePassword();
	})

	this.usernamePlaceholder = "请输入用户名"
	var loginMethods = []
	if (this.emailCanLogin) {
		loginMethods.push("邮箱")
	}
	if (this.mobileCanLogin) {
		loginMethods.push("手机号码")
	}
	if (loginMethods.length > 0) {
		this.usernamePlaceholder += "/" + loginMethods.join("/")
	}

	this.changeUsername = function () {
		this.$post("/checkOTP")
			.params({
				username: this.username
			})
			.success(function (resp) {
				this.showOTP = resp.data.requireOTP
			})
	}

	this.changePassword = function () {
		this.passwordMd5 = md5(this.password.trim());
	}

	// 更多选项
	this.moreOptionsVisible = false;
	this.showMoreOptions = function () {
		this.moreOptionsVisible = !this.moreOptionsVisible;
	}

	this.submitBefore = function () {
		this.isSubmitting = true;
	}

	this.submitDone = function () {
		this.isSubmitting = false;
	}

	this.submitSuccess = function () {
		if (this.from.length == 0) {
			window.location = "/";
		} else {
			window.location = this.from;
		}
	}

	// switch dark mode
	document.documentElement.classList.remove("light");
	document.documentElement.classList.remove("dark");

	let darkMode = localStorage.getItem("teaDarkMode");
	if (darkMode === "dark") {
		document.documentElement.classList.add("dark");
	} else {
		document.documentElement.classList.add("light");
	}
})