<script setup lang="ts">
import { encrypt, decrypt } from "@@/utils/crypto"
import { VbUtil } from "@@/vb-dom"
import appStore from "@s"
import apis from "@a"
import type { LoginData, TenantVO } from "@@/types/Account"

const userStore = appStore.authStore
const router = useRouter()
const loginFormRef = ref<HTMLFormElement>()
const show = ref(false)
const copyright = computed(() => {
	return appStore.appConfigStore.getConfig().copyrightYear || "2020"
})

const title = ref(import.meta.env.VITE_APP_TITLE || "后台管理系统")

const tenantOptions = ref<TenantVO[]>([])
const loginForm = ref<LoginData>({
	tenantId: "000000",
	username: "admin",
	password: "123iwb",
	rememberMe: false,
	code: "",
	uuid: ""
})

const loginRules = {
	tenantId: [{ required: true, trigger: "blur", message: "请输入您的租户编号" }],
	username: [{ required: true, trigger: "blur", message: "请输入您的账号" }],
	password: [{ required: true, trigger: "blur", message: "请输入您的密码" }],
	code: [{ required: true, trigger: "change", message: "请输入验证码" }]
}

const codeUrl = ref("")
const loading = ref(false)
// 租户开关
const tenantEnabled = ref(false)
// 验证码开关
const captchaEnabled = ref(false)
// 注册开关
const register = ref(false)

const redirect = ref(undefined)

function handleLogin() {
	loginFormRef.value?.validate((valid: boolean) => {
		if (valid) {
			loading.value = true
			//勾选了需要记住密码设置在 cookie 中设置记住用户名和密码
			if (loginForm.value.rememberMe) {
				VbUtil.CookieUtil.set("tenantId", loginForm.value.tenantId, { expires: 30 })
				VbUtil.CookieUtil.set("username", loginForm.value.username || "", { expires: 30 })
				VbUtil.CookieUtil.set("password", encrypt(loginForm.value.password || ""), {
					expires: 30
				})
				VbUtil.CookieUtil.set("rememberMe", loginForm.value.rememberMe ? "1" : "0", {
					expires: 30
				})
			} else {
				// 否则移除
				VbUtil.CookieUtil.delete("tenantId")
				VbUtil.CookieUtil.delete("username")
				VbUtil.CookieUtil.delete("password")
				VbUtil.CookieUtil.delete("rememberMe")
			}
			userStore
				.login(loginForm.value)
				.then(() => {
					router.push({ path: redirect.value || "/" })
					loading.value = false
				})
				.catch(() => {
					loading.value = false
					// 重新获取验证码
					if (captchaEnabled.value) {
						getCode()
					}
				})
		}
	})
}

const doSocialLogin = (type: string) => {
	if (loginForm.value.tenantId === "") {
		message.msgError("请选择租户")
		return
	}
	appStore.tenantStore.setTenantId(loginForm.value.tenantId)
	appStore.authStore.socialLogin(type).then((res: any) => {
		if (res.code === HttpStatus.SUCCESS) {
			// 获取授权地址跳转
			window.location.href = res.data
		} else {
			message.msgError(res.msg)
		}
	})
}

function getCode() {
	apis.loginApi.getCodeImg().then(({ data }) => {
		if (captchaEnabled.value) {
			codeUrl.value = "data:image/gif;base64," + data.img
			loginForm.value.uuid = data.uuid
		}
	})
}

function getCookie() {
	try {
		const tenantId = VbUtil.CookieUtil.get("tenantId")
		const username = VbUtil.CookieUtil.get("username")
		const password = VbUtil.CookieUtil.get("password")
		const rememberMe = VbUtil.CookieUtil.get("rememberMe")
		loginForm.value = {
			tenantId: tenantId === undefined ? loginForm.value.tenantId : tenantId,
			username: username === undefined ? loginForm.value.username : username,
			password: password === undefined ? loginForm.value.password : decrypt(password) + "",
			rememberMe: rememberMe === undefined ? false : Boolean(rememberMe),
			code: "",
			uuid: ""
		}
	} catch (e) {
		console.log("GET_COOKIE", e)
	}
}

const initTenant = async () => {
	appStore.tenantStore
		.initTenant()
		.then((res: any) => {
			tenantOptions.value = res
		})
		.catch(() => {
			tenantOptions.value = []
		})
}
function init() {
	appStore.appConfigStore
		.loadConfig()
		.then(() => {
			console.log("---", appStore.appConfigStore.getConfig())
			title.value = appStore.appConfigStore.getConfig().name
			register.value = appStore.appConfigStore.isRegister()
			if (appStore.appConfigStore.isTenant()) {
				tenantEnabled.value = true
				initTenant()
			}
			if (appStore.appConfigStore.isCaptcha()) {
				captchaEnabled.value = true
				getCode()
			}
		})
		.finally(() => {
			show.value = true
		})
	getCookie()
}

onMounted(init)
watch(
	() => router.currentRoute.value,
	(newRoute: any) => {
		redirect.value = newRoute.query && newRoute.query.redirect
	},
	{ immediate: true }
)
</script>

<template>
	<div class="login">
		<el-form
			v-if="show"
			ref="loginFormRef"
			:model="loginForm"
			:rules="loginRules"
			class="login-form">
			<h3 class="title">{{ title }}</h3>
			<el-form-item prop="tenantId" v-if="tenantEnabled">
				<el-select
					v-model="loginForm.tenantId"
					size="large"
					filterable
					placeholder="请选择/输入公司名称"
					style="width: 100%">
					<el-option
						v-for="item in tenantOptions"
						:key="item.tenantId"
						:label="item.companyName"
						:value="item.tenantId"></el-option>
					<template #prefix>
						<span class="el-input__icon input-icon"><VbIcon icon-name="home" class="fs-3" /></span>
					</template>
				</el-select>
			</el-form-item>
			<el-form-item prop="username">
				<el-input
					v-model="loginForm.username"
					type="text"
					size="large"
					auto-complete="off"
					placeholder="账号">
					<template #prefix>
						<span class="el-input__icon input-icon"><VbIcon icon-name="user" class="fs-3" /></span>
					</template>
				</el-input>
			</el-form-item>
			<el-form-item prop="password">
				<el-input
					v-model="loginForm.password"
					type="password"
					size="large"
					auto-complete="off"
					placeholder="密码"
					@keyup.enter="handleLogin">
					<template #prefix>
						<span class="el-input__icon input-icon"><VbIcon icon-name="lock" class="fs-3" /></span>
					</template>
				</el-input>
			</el-form-item>
			<el-form-item prop="code" v-if="captchaEnabled">
				<el-input
					v-model="loginForm.code"
					size="large"
					auto-complete="off"
					placeholder="验证码"
					style="width: 63%"
					@keyup.enter="handleLogin">
					<template #prefix>
						<span class="el-input__icon input-icon">
							<VbIcon icon-name="shield" class="fs-3" />
						</span>
					</template>
				</el-input>
				<div class="login-code">
					<img :src="codeUrl" @click="getCode" class="login-code-img" />
				</div>
			</el-form-item>
			<el-checkbox v-model="loginForm.rememberMe" style="margin: 0px 0px 25px 0px">
				记住密码
			</el-checkbox>
			<!-- <el-form-item style="float: right">
				<el-button circle title="微信登录" @click="doSocialLogin('wechat')">
					<svg-icon icon-class="wechat" />
				</el-button>
				<el-button circle title="MaxKey登录" @click="doSocialLogin('maxkey')">
					<svg-icon icon-class="maxkey" />
				</el-button>
				<el-button circle title="Gitee登录" @click="doSocialLogin('gitee')">
					<svg-icon icon-class="gitee" />
				</el-button>
				<el-button circle title="Github登录" @click="doSocialLogin('github')">
					<svg-icon icon-class="github" />
				</el-button>
			</el-form-item> -->
			<el-form-item style="width: 100%">
				<el-button
					:loading="loading"
					size="large"
					type="primary"
					style="width: 100%"
					@click.prevent="handleLogin">
					<span v-if="!loading">登 录</span>
					<span v-else>登 录 中...</span>
				</el-button>
				<div style="float: right" v-if="register">
					<router-link class="link-type" :to="'/register'">立即注册</router-link>
				</div>
			</el-form-item>
		</el-form>
		<!--  底部  -->
		<div class="el-login-footer">
			<span>
				Copyright ©{{ copyright }}-{{ new Date().getFullYear() }} VAP All Rights Reserved.
			</span>
		</div>
	</div>
</template>

<style lang="scss" scoped>
.login {
	display: flex;
	justify-content: center;
	align-items: center;
	height: 100%;
	background-image: url("/media/auth/bg5.jpg");
	background-size: cover;
}

.title {
	margin: 0px auto 30px auto;
	text-align: center;
	color: #707070;
}

.login-form {
	border-radius: 6px;
	background: rgba(255, 255, 255, 0.9);
	width: 400px;
	padding: 25px 25px 5px 25px;

	.el-input {
		height: 40px;

		input {
			height: 40px;
		}
	}

	.input-icon {
		height: 39px;
		width: 14px;
		margin-left: 0px;
	}
}

.login-tip {
	font-size: 13px;
	text-align: center;
	color: #bfbfbf;
}

.login-code {
	width: 33%;
	height: 40px;
	float: right;

	img {
		cursor: pointer;
		vertical-align: middle;
	}
}

.el-login-footer {
	height: 40px;
	line-height: 40px;
	position: fixed;
	bottom: 0;
	width: 100%;
	text-align: center;
	color: #fff;
	font-family: Arial;
	font-size: 12px;
	letter-spacing: 1px;
}

.login-code-img {
	height: 40px;
	padding-left: 12px;
}
</style>
