<template>
	<div class="login_bg">
		<div class="login_adv" :style="{ backgroundImage: `url(${bg})` }">
		</div>
		<div class="login_main">
			<div class="login_config">
				<el-button :icon="dark?'el-icon-sunny':'el-icon-moon'" circle type="info"
						   @click="configDark"></el-button>
				<el-dropdown trigger="click" placement="bottom-end" @command="configLang">
					<el-button circle>
						<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"
							 aria-hidden="true" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet"
							 viewBox="0 0 512 512">
							<path
								d="M478.33 433.6l-90-218a22 22 0 0 0-40.67 0l-90 218a22 22 0 1 0 40.67 16.79L316.66 406h102.67l18.33 44.39A22 22 0 0 0 458 464a22 22 0 0 0 20.32-30.4zM334.83 362L368 281.65L401.17 362z"
								fill="currentColor"></path>
							<path
								d="M267.84 342.92a22 22 0 0 0-4.89-30.7c-.2-.15-15-11.13-36.49-34.73c39.65-53.68 62.11-114.75 71.27-143.49H330a22 22 0 0 0 0-44H214V70a22 22 0 0 0-44 0v20H54a22 22 0 0 0 0 44h197.25c-9.52 26.95-27.05 69.5-53.79 108.36c-31.41-41.68-43.08-68.65-43.17-68.87a22 22 0 0 0-40.58 17c.58 1.38 14.55 34.23 52.86 83.93c.92 1.19 1.83 2.35 2.74 3.51c-39.24 44.35-77.74 71.86-93.85 80.74a22 22 0 1 0 21.07 38.63c2.16-1.18 48.6-26.89 101.63-85.59c22.52 24.08 38 35.44 38.93 36.1a22 22 0 0 0 30.75-4.9z"
								fill="currentColor"></path>
						</svg>
					</el-button>
					<template #dropdown>
						<el-dropdown-menu>
							<el-dropdown-item v-for="item in langs" :key="item.value" :command="item"
											  :class="{'selected':lang===item.value}">{{ item.name }}
							</el-dropdown-item>
						</el-dropdown-menu>
					</template>
				</el-dropdown>
			</div>
			<div class="login-form">
				<div class="login-header">
					<div class="logo">
						<img :alt="sysConfig.APP_NAME" src="/images/logo.png">
						<label>{{ sysConfig.APP_NAME }}</label>
					</div>
				</div>
				<el-form ref="loginForm" :model="form" :rules="rules" label-width="0" size="large">
					<el-form-item prop="username">
						<el-input v-model="form.username" prefix-icon="el-icon-user" clearable
								  :placeholder="t('login.userPlaceholder')" @keyup.enter="login"></el-input>
					</el-form-item>
					<el-form-item prop="password">
						<el-input v-model="form.password" prefix-icon="el-icon-lock" clearable show-password
								  :placeholder="t('login.PWPlaceholder')" @keyup.enter="login"></el-input>
					</el-form-item>
					<el-form-item prop="code">
						<el-input v-model="form.code" prefix-icon="el-icon-iphone" clearable
								  :placeholder="t('login.codePlaceholder')" @keyup.enter="login">
							<template #append>
								<el-image :src="verImage" @click="getCode" style="padding: 1px;"/>
							</template>
						</el-input>
					</el-form-item>
					<el-form-item style="margin-bottom: 10px;">
						<el-col :span="12">
							<el-checkbox :label="t('login.rememberMe')" v-model="form.autologin"></el-checkbox>
						</el-col>
					</el-form-item>
					<el-form-item>
						<el-button type="primary" style="width: 100%;" :loading="isLogin" round @click="login">
							{{ t('login.signIn') }}
						</el-button>
					</el-form-item>
				</el-form>
			</div>
		</div>
	</div>
</template>

<script setup>
import {getCurrentInstance, ref, onMounted, watch, computed} from 'vue'
import {useI18n} from 'vue-i18n'
import {setupI18n} from "@/locales/setup"
import {useRouter, useRoute} from 'vue-router'
import tools from "@/utils/tools";
import sysConfig from "@/config/index"
import api from "@/api/index"

defineOptions({
	name: 'login'
})

const {proxy} = getCurrentInstance()
const {t} = useI18n()
const router = useRouter()
const route = useRoute()
import bg from '@/assets/images/bg.jpg'

let lang = ref(tools.data.get('APP_LANG') || sysConfig.LANG)
let dark = ref(false)
const redirect = ref(undefined);

const langs = ref([
	{
		name: '简体中文',
		value: 'zh-cn',
	},
	{
		name: 'English',
		value: 'en',
	},
	{
		name: '日本語',
		value: 'ja',
	},
	{
		name: 'Tiếng Việt',
		value: 'vi',
	}
])

let form = ref({
	username: "",
	password: "",
	code: "",
	uuid: "",
	autologin: false
})
let verImage = ref("")
const rules = computed(() => ({
	username: [
		{required: true, message: t('login.userError'), trigger: 'blur'}
	],
	password: [
		{required: true, message: t('login.PWError'), trigger: 'blur'}
	],
	code: [
		{required: true, message: t('login.codeError'), trigger: 'blur'}
	]
}));
let isLogin = ref(false);

const darkConfig = localStorage.getItem('APP_DARK') || sysConfig.DARK

if (darkConfig === "dark") {
	dark.value = true
} else if (darkConfig === 'follow') {
	const systemTheme = window.matchMedia('(prefers-color-scheme: dark)')
	if (systemTheme.matches) {
		dark.value = true
	}
}

// mounted
onMounted(() => {
	getCode()
	rememberMe()
})

watch(lang, (val) => {
	setupI18n(val)
	tools.data.set("APP_LANG", val)
})

watch(
	route,
	(newRoute) => {
		redirect.value = newRoute.query && newRoute.query.redirect;
	},
	{immediate: true}
);

function rememberMe() {
	const data = tools.data.get("ACCOUNT")
	if (data) {
		form.value.username = data.username
		form.value.password = data.password
		form.value.autologin = true
	}
}

async function getCode() {
	const res = await api.auth.captcha();
	form.value.uuid = res.data.uuid
	verImage.value = res.data.image
	form.value.code = "";
}

async function login() {
	// 校验登录
	const validate = await proxy.$refs.loginForm.validate().catch(() => {
	});
	if (!validate) {
		return false
	}
	isLogin.value = true
	const data = {
		username: tools.rsa.encrypt(form.value.username, sysConfig.RSA_PUBLIC_KEY),
		password: tools.rsa.encrypt(tools.md5(form.value.password), sysConfig.RSA_PUBLIC_KEY),
		uuid: form.value.uuid,
		code: tools.rsa.encrypt(form.value.code, sysConfig.RSA_PUBLIC_KEY)
	}
	// 登录接口
	const [res, err] = await tools.go(api.auth.login(data))
	isLogin.value = false
	if (err) {
		await getCode();
		return false;
	}
	tools.data.set("TOKEN", res.data.token, res.data.expireIn)
	// 记住密码
	if (form.value.autologin) {
		tools.data.set("ACCOUNT", {
			username: form.value.username,
			password: form.value.password
		})
	}
	// 获取账号信息
	await getInfo()
}

async function getInfo() {
	const [res, err] = await tools.go(api.auth.info())
	if (err) {
		return false
	}
	tools.data.set("USER_INFO", res.data)
	// 登录成功跳转
	router.replace(redirect.value || "/");
	proxy.$message.success("Login Success 登录成功")
}

function configDark() {
	dark.value = !dark.value
	if (dark.value) {
		document.documentElement.classList.add("dark")
		localStorage.setItem("APP_DARK", 'dark')
	} else {
		document.documentElement.classList.remove("dark")
		localStorage.setItem("APP_DARK", 'light')
	}
}

function configLang(command) {
	lang.value = command.value
}
</script>

<style scoped>
.login_bg {
	width: 100%;
	height: 100%;
	background: #fff;
	display: flex;
}

.login_adv {
	width: 33.3333%;
	background-color: #555;
	background-size: cover;
	background-repeat: no-repeat;
	position: relative;
}

.login_main {
	flex: 1;
	overflow: auto;
	display: flex;
}

.login-form {
	width: 400px;
	margin: auto;
	padding: 20px 0;
}

.login-header {
	margin-bottom: 40px;
}

.login-header .logo {
	display: flex;
	align-items: center;
}

.login-header .logo img {
	width: 40px;
	height: 40px;
	vertical-align: bottom;
	margin-right: 10px;
}

.login-header .logo label {
	font-size: 26px;
	font-weight: bold;
}

.login-form:deep(.login-forgot) {
	text-align: right;
}

.login-form:deep(.login-forgot) a {
	color: var(--el-color-primary);
}

.login-form:deep(.login-forgot) a:hover {
	color: var(--el-color-primary-light-3);
}

.login_config {
	position: absolute;
	top: 20px;
	right: 20px;
}

.login-form:deep(.login-msg-yzm) {
	display: flex;
	width: 100%;
}

@media (max-width: 1200px) {
	.login-form {
		width: 340px;
	}
}

@media (max-width: 1000px) {
	.login_main {
		display: block;
	}

	.login_main .login_config {
		position: static;
		padding: 20px 20px 0 20px;
		text-align: right;
	}

	.login-form {
		width: 100%;
		padding: 20px 40px;
	}

	.login_adv {
		display: none;
	}
}

:deep(.el-input-group__append, .el-input-group__prepend) {
	padding: 0;
}
</style>
