<template>
  <div class="page-container">
    <!-- 全局背景图片 -->
    <div 
      class="global-background"
      :class="{ 'bg-blue-50': !backgroundImageLoaded }"
      :style="backgroundImageStyle"
    ></div>

    <!-- 顶部操作区 -->
    <div class="top-controls">
        <!-- 主题切换按钮 -->
        <div class="theme-switch">
            <el-select 
              v-model="currentTheme" 
              size="small"
              @change="handleThemeChange"
              class="theme-select"
            >
              <el-option label="亮色主题" value="light"></el-option>
              <el-option label="暗色主题" value="dark"></el-option>
              <el-option label="自定义主题" value="custom"></el-option>
            </el-select>
        </div>

        <!-- 语言切换按钮 -->
        <div class="language-switch flex items-center gap-2" v-tooltip:bottom="$t('common.switchLang')">
            <el-switch
                v-model="currentLanguage"
                size="big"
                active-value="en-US"
                inline-prompt
                inactive-value="zh-CN"
                @change="toggleLanguage"
                active-text="中文"
                inactive-text="English"
                style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ee00ff"
            />
        </div>
    </div>

    <!-- 登录注册窗口 -->
    <div class="auth-container">
      <!-- 表单内容 -->
      <div class="form-content">
        <!-- 标题栏 -->
        <div class="title-bar">
          <h2 class="title-text">
            {{ isLoginMode ? $t('auth.loginTitle') : $t('auth.registerTitle') }}
          </h2>
        </div>

        <!-- 表单容器 -->
        <div class="form-container">
          <LoginForm 
            v-if="isLoginMode" 
            @submit-form="handleLogin" 
            :loading="loginLoading"
          />
          <RegisterForm v-else @submit-form="handleRegister" />
        </div>

        <!-- 切换按钮 -->
        <div class="mode-switch">
          <el-button 
            type="text"
            @click="toggleMode"
            class="switch-btn"
          >
            <span class="switch-text">
              {{ isLoginMode ? $t('auth.noAccount') : $t('auth.haveAccount') }}
            </span>
          </el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, inject, onMounted } from 'vue';
import { useI18n } from 'vue-i18n';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import LoginForm from './LoginForm.vue';
import RegisterForm from './RegisterForm.vue';
import { getLocale, setLocale } from '@/utils/storage';
import request from '@/utils/api';
import Cookies from 'js-cookie';
import backgroundImage from '@/assets/background/vtech.png';

// 初始化i18n
const { locale, t } = useI18n();
// 路由实例
const router = useRouter();

// 主题相关
const theme = inject('theme', null);
const currentTheme = ref(theme?.currentTheme || 'light');

// 状态管理
const isLoginMode = ref(true);
const backgroundImageLoaded = ref(false);
const backgroundImageStyle = ref({});
const loginLoading = ref(false);
const currentLanguage = ref(getLocale() || 'zh-CN');

// 加密工具兜底方案
let crypto;
try {
  crypto = require('@/utils/crypto').default;
} catch (e) {
  // 生产环境不输出警告
  crypto = {
    encrypt: (data) => data,
    decrypt: (data) => data
  };
}

// 初始化
onMounted(() => {
  locale.value = getLocale();
  loadBackgroundImage();
  checkRememberedLogin();
});

// 检查记住的登录信息
const checkRememberedLogin = () => {
  const savedUser = localStorage.getItem('rememberedUser');
  if (savedUser) {
    try {
      const userData = JSON.parse(crypto.decrypt(savedUser));
      // 移除调试输出
    } catch (e) {
      // 生产环境不输出错误
      localStorage.removeItem('rememberedUser');
    }
  }
};

// 处理主题切换
const handleThemeChange = (newTheme) => {
  if (theme && theme.switchTheme) {
    theme.switchTheme(newTheme);
    currentTheme.value = newTheme;
  }
};

// 加载背景图片的方法
const loadBackgroundImage = () => {
  try {
    const imgUrl = backgroundImage;
    const img = new Image();
    img.src = imgUrl;

    img.onload = () => {
      backgroundImageLoaded.value = true;
      backgroundImageStyle.value = {
        backgroundImage: `url(${imgUrl})`,
        backgroundSize: 'cover',
        backgroundPosition: 'center',
        backgroundRepeat: 'no-repeat',
        backgroundAttachment: 'fixed',
        opacity: 1.0,
      };
    };

    img.onerror = () => {
      handleImageError();
    };
  } catch (e) {
    handleImageError();
  }
};

const handleImageError = () => {
  backgroundImageLoaded.value = false;
  backgroundImageStyle.value = {
    backgroundColor: '#f0f9ff',
  };
};

// 切换登录/注册模式
const toggleMode = () => {
  isLoginMode.value = !isLoginMode.value;
};

// 错误信息提取方法
const getErrorMessage = (error) => {
  // 处理字符串错误
  if (typeof error === 'string') {
    return error;
  }
  
  // 处理Axios错误
  if (error && (error.name === 'AxiosError' || error.isAxiosError)) {
    if (error.code === 'ECONNABORTED') {
      return t('auth.requestTimeout');
    } else if (error.message.includes('Network Error')) {
      return t('auth.networkError');
    } else if (error.response?.status === 401) {
      return t('auth.unauthorized');
    } else if (error.response?.status === 403) {
      return t('auth.forbidden');
    } else if (error.response?.status === 404) {
      return t('auth.notFound');
    } else if (error.response?.status >= 500) {
      return t('auth.serverError');
    } else if (error.response?.data) {
      return error.response.data.message || error.response.data.msg || t('auth.requestFailed');
    } else {
      return error.message || t('auth.requestFailed');
    }
  }
  
  // 处理普通对象错误
  if (error && typeof error === 'object') {
    return error.message || error.msg || t('auth.unknownError');
  }
  
  // 兜底
  return t('auth.unknownError');
};


const handleLogin = async (formData) => {
  try {
    // 1. 验证表单数据是否存在
    if (!formData || !formData.username || !formData.password) {
      ElMessage.error(t('auth.usernameOrPasswordEmpty'));
      return;
    }
    
    loginLoading.value = true;
    
    // 2. 发送请求
    const response = await request.postWithoutEncryption(
      '/api/i4/v1/auth/login.php', 
      {
        login_name: formData.username,
        password: formData.password,
        rememberMe: formData.rememberMe
      },
      {
        headers: {
          'Content-Type': 'application/json',
          'Accept': 'application/json'
        },
        timeout: 10000
      }
    );

    if (response && response.code === 200) {
      
      const userInfo = response.data;
      // 关键修复：设置路由守卫依赖的登录状态
      localStorage.setItem('isLoggedIn', 'true');
      // 存储token（如果后端返回了token）
      Cookies.set('access_token', userInfo.token || '');
      localStorage.setItem('userInfo', crypto.encrypt(JSON.stringify(userInfo)));

      if (formData.rememberMe) {
        localStorage.setItem('rememberedUser', crypto.encrypt(JSON.stringify({
          username: formData.username,
          rememberMe: true
        })));
      } else {
        localStorage.removeItem('rememberedUser');
      }

      ElMessage.success(t('auth.loginSuccess'));
      
      // 改进跳转逻辑：使用路由实例的push并处理可能的异常
      setTimeout(async () => {
        try {
          await router.push('/main');
          // 跳转成功后可以刷新页面确保状态生效（可选）
          // window.location.reload();
        } catch (err) {
          console.error('路由跳转失败:', err);
          // 失败时的备选方案
          window.location.href = '/main';
        }
      }, 800);
    } else {
      const errorMsg = response?.message || t('auth.loginFailed');
      ElMessage.error(errorMsg);
    }
  } catch (error) {
    const errorMsg = getErrorMessage(error);
    ElMessage.error(errorMsg);
  } finally {
    loginLoading.value = false;
  }
};


// 语言切换
const toggleLanguage = (newLocale) => {
  locale.value = newLocale;
  setLocale(newLocale);
  currentLanguage.value = newLocale;
  ElMessage.success(t('common.languageChanged'));
};
</script>


<style scoped>
.page-container {
  position: relative;
  min-height: 100vh;
  width: 100%;
}

.global-background {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 0;
  transition: opacity 0.5s ease-in-out;
}

.auth-container {
  position: fixed;
  border: 1px solid #c2c4c2;
  right: 16px;
  bottom: 10px;
  width: 360px;
  height: 390px;
  border-radius: 16px;
  box-shadow: 0 10px 25px -5px var(--color-shadow);
  background-color: rgba(255, 255, 255, 0.05);
  backdrop-filter: blur(4px);
  overflow: hidden;
  transition: all 0.3s ease;
  z-index: 50;
}

:deep(.dark-theme) .auth-container {
  background-color: rgba(30, 30, 40, 0.9);
  border-color: #444;
}

.top-controls {
  position: absolute;
  top: 16px;
  right: 16px;
  left: 16px;
  display: flex;
  justify-content: flex-end;
  gap: 8px;
  z-index: 30;
}

.theme-switch {
  margin-right: auto;
}

.theme-select {
  width: 120px;
  background-color: rgba(255, 255, 255, 0.8);
  border-radius: 20px;
}

.language-switch {
  margin-left: auto;
}

.form-content {
  position: relative;
  z-index: 20;
  width: 100%;
  height: 100%;
}

.title-bar {
  padding: 24px;
  color: var(--color-text-alt);
}

.title-text {
  font-size: 24px;
  font-weight: bold;
  text-align: center;
  margin: 0;
}

.mode-switch {
  position: absolute;
  left: 50%;
  bottom: 2px;
  transform: translateX(-50%);
  width: 100%;
  padding: 12px 12px;
  display: flex;
  justify-content: center;
  background-color: inherit;
  z-index: 25;
  box-sizing: border-box;
}

.switch-btn {
  font-weight: 500 !important;
  display: flex !important;
  align-items: center !important;
  padding: 0 !important;
  color: var(--color-primary) !important;
}

.switch-btn:hover {
  color: var(--color-primary-dark) !important;
}

.switch-text {
  margin-right: 8px;
}

.form-container {
  height: 180px;
  padding: 32px;
  color: var(--color-text);
}

@media (max-width: 480px) {
  .auth-container {
    right: 0;
    bottom: 0;
    max-width: 100%;
    border-radius: 16px 16px 0 0;
    height: auto;
    min-height: 80vh;
  }
  
  .form-container {
    padding: 16px;
    min-height: 300px;
  }
}
</style>
