<template>
  <div class="login">
    <el-form ref="loginRef" :model="loginForm" :rules="loginRules" class="login-form">
      <div class="title-container">
        <h3 class="title">{{ title }}</h3>
      </div>
      
      <!-- 登录方式切换 Tab（仅开启邮箱登录时显示） -->
      <div class="login-tabs" v-if="emailLoginEnabled">
        <div 
          class="tab-item" 
          :class="{ active: loginType === 'account' }" 
          @click="loginType = 'account'"
        >
          账号登录
        </div>
        <div 
          class="tab-item" 
          :class="{ active: loginType === 'email' }" 
          @click="loginType = 'email'"
        >
          邮箱登录
        </div>
        <div class="tab-slider" :style="{ left: loginType === 'account' ? '0%' : '50%' }"></div>
      </div>
      
      <!-- 账号登录表单 -->
      <template v-if="loginType === 'account'">
        <el-form-item prop="username">
          <el-input
            v-model="loginForm.username"
            type="text"
            size="large"
            auto-complete="off"
            placeholder="账号"
            class="login-input"
          >
            <template #prefix><svg-icon icon-class="user" class="el-input__icon input-icon" /></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"
            class="login-input"
            show-password
          >
            <template #prefix><svg-icon icon-class="password" class="el-input__icon input-icon" /></template>
          </el-input>
        </el-form-item>
        <el-form-item prop="code" v-if="captchaEnabled">
          <div class="captcha-container">
            <el-input
              v-model="loginForm.code"
              size="large"
              auto-complete="off"
              placeholder="验证码"
              class="login-input captcha-input"
              @keyup.enter="handleLogin"
            >
              <template #prefix><svg-icon icon-class="validCode" class="el-input__icon input-icon" /></template>
            </el-input>
            <div class="login-code">
              <img :src="codeUrl" @click="getCode" class="login-code-img"/>
            </div>
          </div>
        </el-form-item>
      </template>

      <!-- 邮箱登录表单 (UI Only) -->
      <template v-else>
        <el-form-item prop="email">
          <el-input
            v-model="loginForm.email"
            type="text"
            size="large"
            auto-complete="off"
            placeholder="请输入邮箱地址"
            class="login-input"
          >
            <template #prefix><svg-icon icon-class="email" class="el-input__icon input-icon" /></template>
          </el-input>
        </el-form-item>
        <el-form-item prop="emailCode">
          <div class="captcha-container">
            <el-input
              v-model="loginForm.emailCode"
              size="large"
              auto-complete="off"
              placeholder="邮箱验证码"
              class="login-input captcha-input"
              @keyup.enter="handleLogin"
            >
              <template #prefix><svg-icon icon-class="validCode" class="el-input__icon input-icon" /></template>
            </el-input>
            <el-button size="large" class="get-code-btn" :disabled="emailCodeDisabled" @click="handleSendEmailCode">
              {{ emailCodeBtnText }}
            </el-button>
          </div>
        </el-form-item>
      </template>
      
      <div class="form-options">
        <el-checkbox v-model="loginForm.rememberMe">记住密码</el-checkbox>
        <div class="link-group">
          <router-link v-if="register" class="link-type" :to="'/register'">立即注册</router-link>
        </div>
      </div>

      <el-form-item style="width:100%;">
        <el-button
          :loading="loading"
          size="large"
          type="primary"
          class="login-btn"
          @click.prevent="handleLogin"
        >
          <span v-if="!loading">登 录</span>
          <span v-else>登 录 中...</span>
        </el-button>
      </el-form-item>
    </el-form>
    
    <!--  底部  -->
    <div class="el-login-footer">
      <span>{{ footerContent }}</span>
    </div>
  </div>
</template>

<script setup>
import { getCodeImg, sendEmailCode } from "@/api/login"
import { ElMessage } from 'element-plus'
import Cookies from "js-cookie"
import { encrypt, decrypt } from "@/utils/jsencrypt"
import useUserStore from '@/store/modules/user'
import defaultSettings from '@/settings'

const title = import.meta.env.VITE_APP_TITLE
const footerContent = defaultSettings.footerContent
const userStore = useUserStore()
const route = useRoute()
const router = useRouter()
const { proxy } = getCurrentInstance()

const loginType = ref('account') // account | email

const loginForm = ref({
  username: "admin",
  password: "admin123",
  rememberMe: false,
  code: "",
  uuid: "",
  email: "",
  emailCode: ""
})

const loginRules = {
  username: [{ required: true, trigger: "blur", message: "请输入您的账号" }],
  password: [{ required: true, trigger: "blur", message: "请输入您的密码" }],
  code: [{ required: true, trigger: "change", message: "请输入验证码" }],
  email: [
    { required: true, trigger: "blur", message: "请输入您的邮箱" },
    { type: "email", trigger: "blur", message: "请输入正确的邮箱格式" }
  ],
  emailCode: [{ required: true, trigger: "blur", message: "请输入邮箱验证码" }]
}

// 邮箱验证码倒计时相关
const emailCodeDisabled = ref(false)
const emailCodeBtnText = ref('获取验证码')
let emailCodeTimer = null

const codeUrl = ref("")
const loading = ref(false)
// 验证码开关
const captchaEnabled = ref(true)
// 注册开关
const register = ref(false)
// 邮箱登录开关
const emailLoginEnabled = ref(false)
const redirect = ref(undefined)

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

function handleLogin() {
  // 根据登录类型验证不同的字段
  const fieldsToValidate = loginType.value === 'account' 
    ? ['username', 'password', ...(captchaEnabled.value ? ['code'] : [])] 
    : ['email', 'emailCode']
  
  proxy.$refs.loginRef.validateField(fieldsToValidate, (valid) => {
    if (valid) {
      loading.value = true
      
      if (loginType.value === 'account') {
        // 账号密码登录
        // 勾选了需要记住密码设置在 cookie 中设置记住用户名和密码
        if (loginForm.value.rememberMe) {
          Cookies.set("username", loginForm.value.username, { expires: 30 })
          Cookies.set("password", encrypt(loginForm.value.password), { expires: 30 })
          Cookies.set("rememberMe", loginForm.value.rememberMe, { expires: 30 })
        } else {
          // 否则移除
          Cookies.remove("username")
          Cookies.remove("password")
          Cookies.remove("rememberMe")
        }
        // 调用action的登录方法
        userStore.login(loginForm.value).then(() => {
          handleLoginSuccess()
        }).catch(() => {
          loading.value = false
          // 重新获取验证码
          if (captchaEnabled.value) {
            getCode()
          }
        })
      } else {
        // 邮箱登录
        userStore.emailLoginAction(loginForm.value).then(() => {
          handleLoginSuccess()
        }).catch(() => {
          loading.value = false
        })
      }
    }
  })
}

// 登录成功后的跳转处理
function handleLoginSuccess() {
  const query = route.query
  const otherQueryParams = Object.keys(query).reduce((acc, cur) => {
    if (cur !== "redirect") {
      acc[cur] = query[cur]
    }
    return acc
  }, {})
  router.push({ path: redirect.value || "/", query: otherQueryParams })
}

// 发送邮箱验证码
function handleSendEmailCode() {
  // 先验证邮箱格式
  proxy.$refs.loginRef.validateField('email', (valid) => {
    if (valid) {
      emailCodeDisabled.value = true
      sendEmailCode(loginForm.value.email).then(res => {
        ElMessage.success(res.msg || '验证码已发送')
        // 开始倒计时
        let countdown = 60
        emailCodeBtnText.value = `${countdown}s后重新获取`
        emailCodeTimer = setInterval(() => {
          countdown--
          if (countdown <= 0) {
            clearInterval(emailCodeTimer)
            emailCodeDisabled.value = false
            emailCodeBtnText.value = '获取验证码'
          } else {
            emailCodeBtnText.value = `${countdown}s后重新获取`
          }
        }, 1000)
      }).catch(() => {
        emailCodeDisabled.value = false
      })
    }
  })
}

function getCode() {
  getCodeImg().then(res => {
    captchaEnabled.value = res.captchaEnabled === undefined ? true : res.captchaEnabled
    register.value = res.registerEnabled === undefined ? false : res.registerEnabled
    emailLoginEnabled.value = res.emailLoginEnabled === undefined ? false : res.emailLoginEnabled
    // 如果邮箱登录关闭，强制切换回账号登录
    if (!emailLoginEnabled.value && loginType.value === 'email') {
      loginType.value = 'account'
    }
    if (captchaEnabled.value) {
      codeUrl.value = "data:image/gif;base64," + res.img
      loginForm.value.uuid = res.uuid
    }
  })
}

function getCookie() {
  const username = Cookies.get("username")
  const password = Cookies.get("password")
  const rememberMe = Cookies.get("rememberMe")
  loginForm.value = {
    username: username === undefined ? loginForm.value.username : username,
    password: password === undefined ? loginForm.value.password : decrypt(password),
    rememberMe: rememberMe === undefined ? false : Boolean(rememberMe)
  }
}

getCode()
getCookie()
</script>

<style lang='scss' scoped>
.login {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  position: relative;
  overflow: hidden;
    position: relative;
    overflow: hidden;
    background-image: url("../assets/images/login-background.jpg");
    background-size: cover;
    background-position: center;
  }

  /* 登录卡片 - 科技感升级 */
  .login-form {
    position: relative;
    border-radius: 12px;
    background: rgba(13, 22, 45, 0.7); /* 深蓝半透明 */
    backdrop-filter: blur(10px);
    -webkit-backdrop-filter: blur(10px);
    border: 1px solid rgba(59, 130, 246, 0.2); /* 蓝色微光边框 */
    box-shadow: 0 0 40px rgba(0, 0, 0, 0.6), 0 0 20px rgba(37, 99, 235, 0.1);
    width: 440px; /* 稍微加宽 */
    padding: 45px 40px;
    z-index: 1;
  }

  .title-container {
    text-align: center;
    margin-bottom: 30px;
    
    .title {
      margin: 0;
      color: #fff;
      font-size: 28px;
      font-weight: 700;
      letter-spacing: 2px;
      text-shadow: 0 2px 10px rgba(0, 0, 0, 0.5);
    }
  }

  /* 登录方式切换 */
  .login-tabs {
    position: relative;
    display: flex;
    margin-bottom: 35px;
    border-bottom: 2px solid rgba(255, 255, 255, 0.05);
    
    .tab-item {
      flex: 1;
      text-align: center;
      padding: 12px 0;
      color: rgba(255, 255, 255, 0.4);
      cursor: pointer;
      font-size: 16px;
      transition: all 0.3s;
      position: relative;
      z-index: 1;
      
      &.active {
        color: #fff;
        font-weight: 600;
        text-shadow: 0 0 10px rgba(59, 130, 246, 0.5);
      }
      
      &:hover:not(.active) {
        color: rgba(255, 255, 255, 0.8);
      }
    }
    
    .tab-slider {
      position: absolute;
      bottom: -2px;
      left: 0;
      width: 50%;
      height: 2px;
      background: #3b82f6;
      transition: left 0.3s cubic-bezier(0.4, 0, 0.2, 1);
      box-shadow: 0 -4px 15px rgba(59, 130, 246, 0.8);
    }
  }

  /* 输入框样式重写 - 更清晰的边界 */
  :deep(.el-input) {
    --el-input-bg-color: rgba(0, 0, 0, 0.3);
    --el-input-border-color: rgba(59, 130, 246, 0.2);
    --el-input-hover-border-color: rgba(59, 130, 246, 0.5);
    --el-input-focus-border-color: #3b82f6;
    --el-input-text-color: #fff;
    --el-input-placeholder-color: rgba(255, 255, 255, 0.25);
    
    .el-input__wrapper {
      background-color: var(--el-input-bg-color);
      box-shadow: none !important;
      border: 1px solid var(--el-input-border-color);
      border-radius: 6px;
      padding: 1px 15px;
      transition: all 0.3s;
      height: 44px; /* 加高 */
      
      &:hover {
        border-color: var(--el-input-hover-border-color);
        background-color: rgba(0, 0, 0, 0.4);
      }
      
      &.is-focus {
        background-color: rgba(0, 0, 0, 0.5);
        border-color: var(--el-input-focus-border-color);
        box-shadow: 0 0 15px rgba(59, 130, 246, 0.15) !important;
      }
    }
    
    .el-input__inner {
      height: 44px;
      font-size: 15px;
    }
    
    .input-icon {
      color: rgba(59, 130, 246, 0.7); /* 图标改用蓝色 */
      font-size: 16px;
    }
  }

  /* 验证码布局 */
  .captcha-container {
    display: flex;
    justify-content: space-between;
    align-items: center;
    width: 100%;
    
    .captcha-input {
      flex: 1;
      margin-right: 15px;
    }
    
    .login-code {
      width: 120px;
      height: 44px; /* 与输入框等高 */
      background: rgba(255, 255, 255, 0.9); /* 亮色背景衬托验证码 */
      border-radius: 6px;
      overflow: hidden;
      cursor: pointer;
      border: 1px solid rgba(255, 255, 255, 0.1);
      display: flex;
      align-items: center;
      justify-content: center;
      
      img {
        width: 100%;
        height: 100%;
        object-fit: fill;
        opacity: 1;
      }
    }
    
    .get-code-btn {
      width: 120px;
      height: 44px;
      border-radius: 6px;
      background: rgba(59, 130, 246, 0.1);
      border: 1px solid rgba(59, 130, 246, 0.3);
      color: #60a5fa;
      font-weight: 500;
      
      &:hover {
        background: rgba(59, 130, 246, 0.2);
        border-color: #3b82f6;
        color: #fff;
      }
    }
  }

  /* 选项行 */
  .form-options {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 30px;
    padding: 0 5px;
    
    :deep(.el-checkbox) {
      color: rgba(255, 255, 255, 0.6);
      
      .el-checkbox__inner {
        background-color: transparent;
        border-color: rgba(255, 255, 255, 0.4);
        border-radius: 4px;
      }
      
      &.is-checked .el-checkbox__inner {
        background-color: #3b82f6;
        border-color: #3b82f6;
      }
      
      .el-checkbox__label { color: rgba(255, 255, 255, 0.6); }
    }
    
    .link-group {
      .link-type {
        color: #60a5fa;
        font-size: 14px;
        text-decoration: none;
        transition: all 0.3s;
        
        &:hover {
          color: #93c5fd;
          text-shadow: 0 0 10px rgba(59, 130, 246, 0.5);
        }
      }
    }
  }

  /* 登录按钮 */
  .login-btn {
    width: 100%;
    height: 48px; /* 加大 */
    background: #3b82f6;
    border: none;
    border-radius: 6px;
    font-size: 16px;
    font-weight: 600;
    letter-spacing: 6px;
    transition: all 0.3s;
    box-shadow: 0 4px 15px rgba(59, 130, 246, 0.4);
    
    &:hover {
      background: #2563eb;
      transform: translateY(-2px);
      box-shadow: 0 8px 25px rgba(59, 130, 246, 0.5);
    }
    
    &:active {
      transform: scale(0.98);
    }
  }

  /* 底部版权 */
  .el-login-footer {
    height: 40px;
    line-height: 40px;
    position: fixed;
    bottom: 20px;
    width: 100%;
    text-align: center;
    color: rgba(255, 255, 255, 0.3);
    font-size: 12px;
    letter-spacing: 1px;
    z-index: 1;
  }
</style>
