<template>
  <div class="pc-login-container">
    <img src="@/assets/image/logo.png" class="top-left-logo" alt="logo" />

    <div class="lang-selector-wrapper">
      <selectLang />
    </div>

    <div class="bg-glow glow-top-right"></div>
    <div class="bg-glow glow-bottom-left"></div>

    <div class="login-card">
      <div class="mclaren-header">
        <img src="@/assets/image/login/mclaren.png" class="mclaren-img-logo" alt="mclaren logo" />
        <div class="main-title">迈凯伦</div>
        <div class="sub-partner">官方合作伙伴</div>
      </div>

      <el-tabs v-model="activeLoginType" class="custom-tabs" stretch @tab-change="updateRememberPwdStatus">
        <el-tab-pane :label="t('账号登录')" name="account"></el-tab-pane>
        <el-tab-pane :label="t('邮箱登录')" name="email"></el-tab-pane>
      </el-tabs>

      <div v-show="activeLoginType === 'account'" class="form-wrapper">
        <el-input
            v-model="accountForm.account"
            :placeholder="t('请输入账号')"
            clearable
            size="large"
            class="custom-input"
            @keyup.enter="onLoginClick"
        >
          <template #prefix>
            <img src="@/assets/image/login/user.png" class="input-icon" alt="icon"/>
          </template>
        </el-input>

        <el-input
            v-model="accountForm.password"
            :placeholder="t('请输入登录密码')"
            type="password"
            show-password
            clearable
            size="large"
            class="custom-input"
            @keyup.enter="onLoginClick"
        >
          <template #prefix>
            <img src="@/assets/image/login/lock.png" class="input-icon" alt="icon"/>
          </template>
        </el-input>
      </div>

      <div v-show="activeLoginType === 'email'" class="form-wrapper">
        <el-input
            v-model="emailForm.account"
            :placeholder="t('请输入登录邮箱')"
            clearable
            size="large"
            class="custom-input"
            @keyup.enter="onLoginClick"
        >
          <template #prefix>
            <img src="@/assets/image/login/account.png" class="input-icon" alt="icon"/>
          </template>
        </el-input>

        <el-input
            v-model="emailForm.password"
            :placeholder="t('请输入登录密码')"
            type="password"
            show-password
            clearable
            size="large"
            class="custom-input"
            @keyup.enter="onLoginClick"
        >
          <template #prefix>
            <img src="@/assets/image/login/lock.png" class="input-icon" alt="icon"/>
          </template>
        </el-input>
      </div>

      <div class="options-agreement-row">
        <el-checkbox v-model="RememberPwd" class="custom-checkbox">{{ t('记住密码') }}</el-checkbox>
        <div class="agreement-content">
          <el-checkbox v-model="agreed" class="custom-checkbox">{{ t('我已阅读并同意') }}</el-checkbox>
          <span class="agreement-link" @click="onAgreementClick">{{ t('相关条款') }}</span>
          <span>{{ t('和') }}</span>
          <span class="agreement-link" @click="onAgreementClick">{{ t('隐私政策') }}</span>
        </div>
      </div>

      <el-button type="primary" class="submit-btn" size="large" @click="onLoginClick">
        {{ t('登录') }}
      </el-button>

      <div class="bottom-action-group">
        <div class="action-item" @click="router.push('/register')">
          <img src="@/assets/image/login/register.png" class="action-icon" alt="register" />
          <span>{{ t('注册') }}</span>
        </div>
        <div class="action-item" @click="onGuestClick">
          <img src="@/assets/image/login/user-lock.png" class="action-icon" alt="guest" />
          <span>{{ t('游客模式') }}</span>
        </div>
        <div class="action-item" @click="onLineService">
          <img src="@/assets/image/login/kefu.png" class="action-icon" alt="guest" />
          <span>{{ t('在线客服') }}</span>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { useI18n } from 'vue-i18n';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Message, Lock, Iphone, Key } from '@element-plus/icons-vue';
import socket from '@/utils/websocket.js'
import { appDescription, appName } from '@/settings/index.mjs';
import selectLang from '@/components/selectLang/index.vue';
import {postUserLogin, userGuestRegister} from "@/request/api";

const router = useRouter();
const { t } = useI18n();

const agreed = ref(false);
const RememberPwd = ref(false);
// 将默认选中的 Tab 改为账号登录
const activeLoginType = ref('account');

const emailForm = reactive({ account: '', password: '' });
const accountForm = reactive({ account: '', password: '' });

function initRecall() {
  // 分别读取邮箱和账号的缓存
  const isRememberEmail = localStorage.getItem('is_remember_pwd_email');
  if (isRememberEmail === 'true') {
    emailForm.account = localStorage.getItem('saved_account_email') || '';
    emailForm.password = localStorage.getItem('saved_password_email') || '';
  }

  const isRememberAccount = localStorage.getItem('is_remember_pwd_account');
  if (isRememberAccount === 'true') {
    accountForm.account = localStorage.getItem('saved_account_account') || '';
    accountForm.password = localStorage.getItem('saved_password_account') || '';
  }

  // 初始化当前选项卡的记住密码状态
  updateRememberPwdStatus();
}

function updateRememberPwdStatus() {
  // 切换Tab时，动态回显对应的记住密码勾选状态
  if (activeLoginType.value === 'email') {
    RememberPwd.value = localStorage.getItem('is_remember_pwd_email') === 'true';
  } else {
    RememberPwd.value = localStorage.getItem('is_remember_pwd_account') === 'true';
  }
}

function onAgreementClick() {
  ElMessageBox.alert(
      `<div style="line-height: 1.6; color: #333; text-align: left;">
      <h3 style="margin-bottom: 16px;">平台服务协议</h3>
      <p>1. 本平台提供相关的体育与彩票服务...</p>
      <p>2. 请确保您已达到法定年龄...</p>
    </div>`,
      t('产品服务协议'),
      { dangerouslyUseHTMLString: true, confirmButtonText: t('确定'), customClass: 'agreement-msgbox' }
  );
}

function validateEmailForm() {
  if (!emailForm.account) { ElMessage.warning(t('请输入登录邮箱')); return false; }
  if (!emailForm.password) { ElMessage.warning(t('请输入登录密码')); return false; }
  if (emailForm.password.length < 6 || emailForm.password.length > 20) {
    ElMessage.warning(t('密码长度需在6-20个字符之间'));
    return false;
  }
  return true;
}

function validateAccountForm() {
  if (!accountForm.account) { ElMessage.warning(t('请输入账号')); return false; }
  if (!accountForm.password) { ElMessage.warning(t('请输入登录密码')); return false; }
  if (accountForm.password.length < 6 || accountForm.password.length > 20) {
    ElMessage.warning(t('密码长度需在6-20个字符之间'));
    return false;
  }
  return true;
}

function checkAgreement(callback) {
  if (!agreed.value) {
    ElMessageBox.confirm(
        t('为了保障您的权益，请先阅读并同意') + '《' + t('产品服务协议') + '》',
        t('温馨提示'),
        { confirmButtonText: t('同意并继续'), cancelButtonText: t('取消'), type: 'warning' }
    ).then(() => {
      agreed.value = true;
      callback();
    }).catch(() => {});
    return;
  }
  callback();
}

function onGuestClick() {
  checkAgreement(() => { router.push('/'); });
}

function onLineService() {
  if(!localStorage.getItem('youke_token')){
    userGuestRegister().then((res) => {
      localStorage.setItem('youke_token', res.data.token);
      router.push({
        name: 'CustomerService',
        query: { GuestMode: 1 }
      });
    })
  } else {
    router.push({
      name: 'CustomerService',
      query: { GuestMode: 1 }
    });
  }
}

function onLoginClick() {
  checkAgreement(async () => {
    let isValid = false;
    let loginData = { account: '', password: '' };

    if (activeLoginType.value === 'email') {
      isValid = validateEmailForm();
      loginData.account = emailForm.account;
      loginData.password = emailForm.password;
    } else {
      isValid = validateAccountForm();
      loginData.account = accountForm.account;
      loginData.password = accountForm.password;
    }

    if (!isValid) return;

    // 接口已封装提示，此处直接调用，不额外手写 Loading 或 ElMessage.success
    postUserLogin(loginData).then((res) => {
      socket.close();

      // 记住密码逻辑：区分邮箱和账号独立缓存
      if (activeLoginType.value === 'email') {
        if (RememberPwd.value) {
          localStorage.setItem('is_remember_pwd_email', 'true');
          localStorage.setItem('saved_account_email', loginData.account);
          localStorage.setItem('saved_password_email', loginData.password);
        } else {
          localStorage.removeItem('is_remember_pwd_email');
          localStorage.removeItem('saved_account_email');
          localStorage.removeItem('saved_password_email');
        }
      } else {
        if (RememberPwd.value) {
          localStorage.setItem('is_remember_pwd_account', 'true');
          localStorage.setItem('saved_account_account', loginData.account);
          localStorage.setItem('saved_password_account', loginData.password);
        } else {
          localStorage.removeItem('is_remember_pwd_account');
          localStorage.removeItem('saved_account_account');
          localStorage.removeItem('saved_password_account');
        }
      }

      localStorage.setItem('token', res.data.token);
      localStorage.setItem('has_payment_password', res.data.has_payment_password ? 1 : 0);
      let timer = setTimeout(() => {
        clearTimeout(timer)
        socket.connect(res.data.token);
      }, 2000)

      setTimeout(() => {
        // 判断当前是不是第一页 (基于 history 路由模式)
        if (window.history.state && window.history.state.back) {
          // 不是第一页，返回上一页
          router.back();
        } else {
          // 是第一页，按原来的方式跳转
          router.push('/');
        }
      }, 1000);
    });
  });
}

onMounted(() => { initRecall(); });
</script>

<style scoped lang="scss">
$mclaren-orange: #f8b932; // 迈凯伦主背景橙色
$btn-orange: #f8b932;     // 登录按钮橙色
$text-light: rgba(255, 255, 255, 0.8);

.pc-login-container {
  position: relative; min-height: 100vh; width: 100vw;
  background-image: url('@/assets/image/login/bg-login-pc.png');
  background-size: cover;
  background-position: center;
  display: flex; justify-content: center; align-items: center; overflow: hidden;

  .top-left-logo { position: absolute; top: 30px; left: 40px; height: 32px; z-index: 10; }
  .lang-selector-wrapper { position: absolute; top: 24px; right: 32px; z-index: 10; }

  /* 装饰光晕 */
  .bg-glow { position: absolute; border-radius: 50%; filter: blur(120px); opacity: 0.1; z-index: 1; }
  .glow-top-right { top: -10%; right: 10%; width: 400px; height: 400px; background-color: $mclaren-orange; }
  .glow-bottom-left { bottom: -10%; left: 10%; width: 300px; height: 300px; background-color: #fff; }

  .login-card {
    min-width: 480px; width: 30%;
    position: relative; z-index: 2; padding: 30px;
    background-color: rgba(255, 255, 255, 0.1);
    backdrop-filter: blur(20px);
    border-radius: 24px;
    box-shadow: 0 15px 50px rgba(0, 0, 0, 0.6);
    border: 1px solid rgba(255, 255, 255, 0.2);

    /* 迈凯伦 Header 样式适配 */
    .mclaren-header {
      border-radius: 12px;
      text-align: center;
      margin-bottom: 25px;
      display: flex;
      flex-direction: column;
      align-items: center;

      .mclaren-img-logo { height: 34px; margin-bottom: 2px; }

      .main-title {
        color: #fff; font-size: 20px; font-weight: 800;
        letter-spacing: 5px; line-height: 1;
        margin-top: 15px;
      }

      .sub-partner {
        color: rgba(255, 255, 255, 0.85); font-size: 12px;
        letter-spacing: 1px; margin-top: 4px;
      }
    }

    /* 选项卡样式 */
    .custom-tabs {
      margin-bottom: 20px;
      :deep(.el-tabs__nav-wrap::after) { display: none; }
      :deep(.el-tabs__active-bar) { display: none; }
      :deep(.el-tabs__nav) { width: 100%; display: flex; gap: 12px; }
      :deep(.el-tabs__item) {
        flex: 1; height: 46px; line-height: 46px; padding: 0 !important;
        color: #ccc; font-size: 15px; text-align: center;
        background: rgba(255, 255, 255, 0.12); border-radius: 8px;
        transition: all 0.3s;
        &.is-active { background: rgba(255, 255, 255, 0.25); color: #fff; font-weight: bold; }
      }
    }

    .form-wrapper { display: flex; flex-direction: column; gap: 15px; }

    /* 输入框玻璃样式 */
    .custom-input {
      :deep(.el-input__wrapper) {
        background-color: rgba(255, 255, 255, 0.2);
        box-shadow: none; height: 50px; border-radius: 10px;
        &:hover, &.is-focus { box-shadow: 0 0 0 1px $mclaren-orange inset; }
      }
      :deep(.el-input__inner) { color: #fff; &::placeholder { color: #bbb; } }
      .input-icon { width: 20px; height: 20px; opacity: 0.8; margin-right: 5px; }
    }

    /* 选项与协议区域：一左一右 */
    .options-agreement-row {
      display: flex;
      align-items: center;
      justify-content: space-between;
      font-size: 13px;
      margin: 15px 0 20px;
      color: #bbb;

      .agreement-content {
        display: flex;
        align-items: center;
      }

      .agreement-link {
        cursor: pointer;
        color: #fff;
        margin: 0 4px;
        text-decoration: underline;
      }
    }

    .custom-checkbox {
      :deep(.el-checkbox__label) { color: #bbb; font-size: 13px; }
      :deep(.el-checkbox__input.is-checked .el-checkbox__inner) { background-color: $btn-orange; border-color: $btn-orange; }
      :deep(.el-checkbox__inner) { background-color: rgba(255, 255, 255, 0.1); border-color: rgba(255,255,255,0.4); }
    }

    /* 登录按钮 */
    .submit-btn {
      width: 100%; height: 52px; font-size: 18px; font-weight: bold; color: #fff;
      background-color: $btn-orange; border-color: $btn-orange; border-radius: 10px;
      letter-spacing: 4px; margin-bottom: 20px;
      &:hover { opacity: 0.9; transform: translateY(-1px); }
    }

    /* 底部按钮组 */
    .bottom-action-group {
      display: flex; justify-content: space-between; gap: 12px; margin-top: 10px;
      .action-item {
        flex: 1; display: flex; flex-direction: column; align-items: center; justify-content: center;
        background: rgba(255, 255, 255, 0.15); border-radius: 10px; padding: 12px 0; cursor: pointer;
        transition: all 0.3s ease;
        &:hover { background: rgba(255, 255, 255, 0.25); }
        .action-icon { width: 24px; height: 24px; margin-bottom: 6px; }
        span { font-size: 13px; color: #ddd; }
      }
    }
  }

  /* 下拉菜单全局样式穿透 */
  :deep(.el-popper) {
    background-color: rgba(40, 40, 40, 0.95) !important;
    backdrop-filter: blur(10px);
    border: 1px solid rgba(255, 255, 255, 0.1) !important;
    .el-select-dropdown__item {
      color: #eee;
      &.is-hovering, &:hover { background-color: rgba(255, 255, 255, 0.1); }
      &.is-selected { color: $mclaren-orange; font-weight: bold; }
    }
  }
}
</style>
