<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 { 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';
import crypto from '@/utils/crypto';
import router from '@/router';
import { checkLoginStatus, clearLoginState } from '@/router';

// 初始化i18n
const { locale, t } = useI18n();

// 主题相关
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');

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

// 检查记住的登录信息
const checkRememberedLogin = () => {
  const savedUser = localStorage.getItem('rememberedUser');
  if (savedUser) {
    try {
      const decryptedData = crypto.decrypt(savedUser);
      const userData = JSON.parse(decryptedData);
      // 可以在这里自动填充用户名到登录表单
    } catch (e) {
      console.error('解析记住的用户数据失败:', 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;
  }
  
  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 {
    // 验证表单数据
    if (!formData || !formData.username || !formData.password) {
      ElMessage.error(t('auth.usernameOrPasswordEmpty'));
      return;
    }
    
    loginLoading.value = true;
    
    // 发送登录请求
    const response = await request.postWithoutEncryption(
        '/api/i4/v1/auth/login.php', 
        {
        login_name: formData.username,
        password: formData.password,
        rememberMe: formData.rememberMe
        }
    );

    // 关键修复：强制解析响应为JSON对象
    let parsedResponse = response;
    if (typeof response === 'string') {
        // 移除可能的多余符号（如< >）
        const cleanedResponse = response.replace(/[<>]/g, '');
        try {
        parsedResponse = JSON.parse(cleanedResponse);
        } catch (e) {
        console.error('响应解析失败:', e);
        ElMessage.error('登录失败，响应格式错误');
        return;
        }
    }

    // 使用解析后的响应判断
    console.log('解析后响应:', parsedResponse, 'BOOL:', parsedResponse?.code === 200);
    if (parsedResponse && parsedResponse.code === 200) {
      const userInfo = parsedResponse.data;
      console.log('用户信息:', userInfo);
      // 存储登录状态
      localStorage.setItem('isLoggedIn', 'true');
      
      // 加密存储用户信息
      const encryptedUserInfo = crypto.encrypt(JSON.stringify(userInfo));
      localStorage.setItem('userInfo', encryptedUserInfo);
      
      // 存储token
      Cookies.set('access_token', userInfo.token || '', {
        expires: formData.rememberMe ? 7 : 2/24, // 记住我时保存7天，否则2小时
        path: '/',
      });

      // 处理记住我
      if (formData.rememberMe) {
        const rememberedData = crypto.encrypt(JSON.stringify({
          username: formData.username,
          rememberMe: true
        }));
        localStorage.setItem('rememberedUser', rememberedData);
      } else {
        localStorage.removeItem('rememberedUser');
      }

      ElMessage.success(t('auth.loginSuccess'));

      // 验证登录状态并跳转
      setTimeout(async () => {
        try {
          if (checkLoginStatus()) {
            await router.push('/');
          } else {
            throw new Error('登录状态验证失败');
          }
        } catch (err) {
          console.error('跳转失败:', err);
          ElMessage.error('登录状态异常，请重试');
          clearLoginState();
        }
      }, 500);
    } 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 handleRegister = async (formData) => {
  // 注册逻辑实现
  ElMessage.info('注册功能待实现');
};

// 语言切换
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.001);
  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>
