<template>
  <div class="login-container">
    <!-- 背景图 -->
    <div class="background-left">
      <img class="background-image" :src="loginbg" alt="背景图">
    </div>
    
    <!-- 登录框 -->
    <div class="login-form-container">
      <div class="login-box">
        <el-card class="login-card" shadow="never">
          <template #header>
            <div class="login-header">
              <img :src="loginLogo" alt="logo" class="login-logo"/>
              <h2>{{ $t('login.subtitle') }}</h2>
            </div>
          </template>

          <el-form
            :model="loginForm"
            :rules="loginRules"
            ref="loginFormRef"
            @keyup.enter="handleLogin"
            hide-required-asterisk
            label-position="left"
          >
            <el-form-item prop="username" 
            :label="`${$t('login.username')}：`" 
            style="margin-bottom: 20px;" 
            label-width="100px">
              <el-input
                v-model="loginForm.username"
                :placeholder="$t('login.inputusername')"
                prefix-icon="User"
                clearable
              />
            </el-form-item>

            <el-form-item prop="password" 
            :label="`${$t('login.password')}：`" 
            style="margin-bottom: 20px;" 
            label-width="100px">
              <el-input
                v-model="loginForm.password"
                :placeholder="$t('login.inputpassword')"
                prefix-icon="Lock"
                show-password
                clearable
              />
            </el-form-item>
          
            <el-form-item prop="remember" style="margin-bottom: 20px;">
              <div style="width: 100%; display: flex; justify-content: space-between;">
                <el-checkbox v-model="loginForm.remember" class="remember-me">{{ $t('login.rememberMe') }}</el-checkbox>
                <el-link type="info" class="forgot-password">{{ $t('login.forgotPassword') }}</el-link>
              </div>
            </el-form-item>

            <el-form-item>
              <el-button
                type="primary"
                class="login-btn"
                :loading="loading"
                @click="handleLogin"
                
              >
                {{ $t('login.loginButton') }}
              </el-button>
            </el-form-item>
          </el-form>
        
          <!-- <div class="login-footer">
            <div class="register-prompt">没有账号？点击</div>
            <el-link type="primary" @click="goToRegister">注册</el-link>
          </div> -->
        </el-card>
      </div>
      
    </div>
  </div>
</template>

<script setup>
import { ElMessage } from 'element-plus'
import router from "@/router"
import { request,enPassword } from "@/utils/request"
import secureStorage from '@/utils/secureStorage'

import { getToken, setToken, setUserId} from "@/utils/token"
import { useUserStore } from '@/store/user'

import loginbg from '@/assets/img/login-bg.png'
import loginLogo from '@/assets/img/login-logo.png'
import { useI18n } from 'vue-i18n'

const { t, locale } = useI18n()


// 表单引用
const loginFormRef = ref(null)

// 获取userStore实例
const userStore = useUserStore()

// 登录表单数据
const loginForm = reactive({
  username: secureStorage.get('savedUsername') || '',
  password: secureStorage.get('savedPassword') || '',
  remember: secureStorage.get('rememberPassword') === 'true'
})

// 加载状态
const loading = ref(false)

// 表单验证规则
const loginRules = reactive({
  username: [
    { min: 3, max: 18, message: t('login.usernameLength'), trigger: 'blur' }
  ],
  password: [
    { min: 6, max: 18, message: t('login.passwordLength'), trigger: 'blur' }
  ]
})


// 登录方法
const handleLogin = () => {
  loginFormRef.value.validate(valid => {
    if (!valid) return
    // 检查是否有输入用户名和密码
    if (!loginForm.username || !loginForm.password) {
      ElMessage.error(t('login.checknamepwd'));
      return;
    }
    if (loginForm.remember) {
        secureStorage.set('savedUsername', loginForm.username)
        secureStorage.set('savedPassword', loginForm.password)
        secureStorage.set('rememberPassword', 'true')
      } else {
        secureStorage.remove('savedUsername')
        secureStorage.remove('savedPassword')
        secureStorage.remove('rememberPassword')
      }
    loading.value = true
    
    const params = {
      transCode: "A00002",
      loginName: loginForm.username,
      password: enPassword(loginForm.password),
      type: "",
    }
    // console.log(params)
    request(params)
    .then((res) => {
      setToken(res.clientToken)
      setUserId(res.userId)

      userStore.setToken(res.clientToken)
      // 存储用户信息到pinia
      userStore.setUserInfo({
        userId: res.userId,
        userName: res.userName,
        nickName: res.nickName,
        userType: res.userType,
        regTime: res.regTime,
        email: res.email || '',
        mobileNo: res.mobileNo,
      })

      router.push({ path: "/" })
    })
    .catch((err) => {
      // console.error('错误信息：',err);
      ElMessage.error(t('login.loginError'));
      loading.value = false;
    })
    .finally(() => {
      loading.value = false
    });
    
  })
}

// 跳转到注册页面
const goToRegister = () => {
  router.push({ path: "/register" })
}
</script>

<style lang="scss" scoped>
.login-container {
  position: relative;
  width: 100%;
  height: 100vh;
  min-width: 1200px;
  min-height: 600px;
  display: flex;
  overflow: auto;
}

.background-image {
  // position: absolute;
  // top: 0;
  // left: 0;
  width: 100%;
  height: 100%;
  object-fit: fill;
  object-position: center;
  z-index: 0;
}

.background-left {
  width: 60%;
  height: 100%;
}

.login-form-container {
  // position: absolute;
  // left: 60%;
  width: 40%;
  height: 100%;
}

.login-box {
  height: 100%;
  background-color: rgba(255, 255, 255, 0.6);
  display: flex;
  justify-content: center;
  align-items: center;
}

.login-card {
  border: none !important;
  width: 80%;
  background-color: transparent;
  :deep(.el-card__header) {
    border-bottom: none;
    padding-bottom: 0;
  }
}

.login-card {
  // 设置label文字大小
  :deep(.el-form-item__label) {
    font-size: 14px;
    font-weight: 400;
    line-height: 39px; /* 保持垂直居中 */
    color: #333333; /* 可选：设置label颜色 */
    text-align: left;
  }
  
  // 设置输入框文字大小
  :deep(.el-input__inner) {
    font-size: 14px;
    height: 39px; /* 可选：调整输入框高度 */
    line-height: 39px; /* 保持垂直居中 */
  }

  :deep(.el-input__wrapper) {
    background-color: transparent;
    border: 1px solid #B3B3B3;
    height: 39px;
  }
  
  // 设置placeholder文字大小
  :deep(.el-input__inner::placeholder) {
    font-size: 14px;
  }
}

.login-header {
  text-align: start;
  // width: 75%;
  margin-bottom: 30px;

  h2 {
    margin: 0;
    font-size: 17px;
    font-weight: 400;
    color: #1A1A1A;
    margin: 10px 0;
    font-style: normal;
    text-transform: none;
    letter-spacing: 1px;
  }
}

.login-logo {
  width: 110px;
  // margin-bottom: 18px;
  transform: translateX(-20px); /* 向左移动10px */
}

.forgot-password{
  color: #12739E;
}

.remember-me {
  color: #4D4D4D;
}

.login-btn {
  width: 100%;
  height: 42px;
  margin-top: 10px;
  font-size: 16px;
  background-color: #12739E;
}

.login-footer {
  display: flex;
  justify-content: center;
  margin-top: 10px;
}

.register-prompt {
  margin-right: 5px;
  font-size: 13px;
}

</style>