<template>
  <div class="login-layout">
    <div class="login-container">
      <div class="login-header">
        <div class="login-logo">
          <el-icon><Document /></el-icon>
        </div>
        <h1 class="login-title">PANJIT 翻譯系統</h1>
        <p class="login-subtitle">企業級文件批量翻譯管理系統</p>
      </div>
      
      <div class="login-body">
        <el-form
          ref="loginFormRef"
          :model="loginForm"
          :rules="loginRules"
          @keyup.enter="handleLogin"
          label-position="top"
          size="large"
        >
          <el-form-item label="AD 帳號" prop="username">
            <el-input
              v-model="loginForm.username"
              placeholder="請輸入您的 AD 帳號"
              :prefix-icon="User"
              clearable
              :disabled="loading"
            />
          </el-form-item>
          
          <el-form-item label="密碼" prop="password">
            <el-input
              v-model="loginForm.password"
              type="password"
              placeholder="請輸入密碼"
              :prefix-icon="Lock"
              show-password
              clearable
              :disabled="loading"
            />
          </el-form-item>
          
          <el-form-item>
            <el-checkbox v-model="rememberMe" :disabled="loading">
              記住登入狀態
            </el-checkbox>
          </el-form-item>
          
          <el-form-item>
            <el-button
              type="primary"
              size="large"
              :loading="loading"
              :disabled="!loginForm.username || !loginForm.password"
              @click="handleLogin"
              style="width: 100%"
            >
              {{ loading ? '登入中...' : '登入' }}
            </el-button>
          </el-form-item>
        </el-form>
        
        <!-- 錯誤訊息顯示 -->
        <div v-if="errorMessage" class="error-message">
          <el-alert
            :title="errorMessage"
            type="error"
            :closable="false"
            show-icon
          />
        </div>
        
        <!-- 登入提示 -->
        <div class="login-tips">
          <el-alert
            title="登入說明"
            type="info"
            :closable="false"
            show-icon
          >
            <p>請使用您的 PANJIT AD 域帳號登入系統。</p>
            <p>如果您忘記密碼或遇到登入問題，請聯繫 IT 部門協助。</p>
          </el-alert>
        </div>
      </div>
      
      <div class="login-footer">
        <p>&copy; 2024 PANJIT Group. All rights reserved.</p>
        <p>Powered by PANJIT IT Team</p>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import { useAuthStore } from '@/stores/auth'
import { ElMessage } from 'element-plus'
import { Document, User, Lock } from '@element-plus/icons-vue'

// Router 和 Store
const router = useRouter()
const authStore = useAuthStore()

// 響應式數據
const loginFormRef = ref()
const loading = ref(false)
const rememberMe = ref(false)
const errorMessage = ref('')

// 登入表單數據
const loginForm = reactive({
  username: '',
  password: ''
})

// 表單驗證規則
const loginRules = {
  username: [
    { required: true, message: '請輸入 AD 帳號', trigger: 'blur' },
    { min: 3, message: '帳號長度不能少於3個字元', trigger: 'blur' },
    {
      pattern: /^[a-zA-Z0-9._@-]+$/,
      message: '帳號格式不正確，只能包含字母、數字、點、下劃線、@符號和連字符',
      trigger: 'blur'
    }
  ],
  password: [
    { required: true, message: '請輸入密碼', trigger: 'blur' },
    { min: 1, message: '密碼不能為空', trigger: 'blur' }
  ]
}

// 方法
const handleLogin = async () => {
  try {
    // 清除之前的錯誤訊息
    errorMessage.value = ''
    
    // 驗證表單
    const valid = await loginFormRef.value.validate()
    if (!valid) {
      return
    }
    
    loading.value = true
    
    // 準備登入資料
    const credentials = {
      username: loginForm.username.trim(),
      password: loginForm.password
    }
    
    // 如果帳號不包含 @，自動添加域名
    if (!credentials.username.includes('@')) {
      credentials.username = `${credentials.username}@panjit.com.tw`
    }
    
    // 執行登入
    await authStore.login(credentials)
    
    // 如果選擇記住登入狀態，可以在這裡處理
    if (rememberMe.value) {
      localStorage.setItem('rememberLogin', 'true')
    }
    
    // 登入成功，跳轉到首頁
    router.push('/')
    
  } catch (error) {
    console.error('登入失敗:', error)
    
    // 處理不同的錯誤類型
    if (error.response?.status === 401) {
      errorMessage.value = '帳號或密碼錯誤，請重新輸入'
    } else if (error.response?.status === 403) {
      errorMessage.value = '您的帳號沒有權限存取此系統'
    } else if (error.response?.status === 500) {
      errorMessage.value = '伺服器錯誤，請稍後再試'
    } else if (error.message?.includes('LDAP')) {
      errorMessage.value = 'AD 伺服器連接失敗，請聯繫 IT 部門'
    } else if (error.message?.includes('network')) {
      errorMessage.value = '網路連接失敗，請檢查網路設定'
    } else {
      errorMessage.value = error.message || '登入失敗，請重試'
    }
    
    // 清空密碼欄位
    loginForm.password = ''
    
    // 3秒後自動清除錯誤訊息
    setTimeout(() => {
      errorMessage.value = ''
    }, 5000)
    
  } finally {
    loading.value = false
  }
}

const clearError = () => {
  errorMessage.value = ''
}

// 生命週期
onMounted(() => {
  // 如果已經登入，直接跳轉
  if (authStore.isAuthenticated) {
    router.push('/')
    return
  }
  
  // 檢查是否記住了登入狀態
  const rememberLogin = localStorage.getItem('rememberLogin')
  if (rememberLogin === 'true') {
    rememberMe.value = true
  }
  
  // 僅在頁面載入時檢查認證狀態（不調用API）
  const authUser = localStorage.getItem('auth_user')
  const authAuthenticated = localStorage.getItem('auth_authenticated')
  
  if (authUser && authAuthenticated === 'true') {
    // 如果已經有認證資訊，直接跳轉
    router.push('/')
  }
  
  // 監聽表單變化，清除錯誤訊息
  const unwatchForm = watch([() => loginForm.username, () => loginForm.password], () => {
    if (errorMessage.value) {
      clearError()
    }
  })
  
  // 頁面卸載時取消監聽
  onUnmounted(() => {
    unwatchForm()
  })
})
</script>

<style lang="scss" scoped>
.error-message {
  margin-top: 16px;
}

.login-tips {
  margin-top: 24px;
  
  :deep(.el-alert__content) {
    p {
      margin: 4px 0;
      font-size: 13px;
      line-height: 1.4;
      
      &:first-child {
        margin-top: 0;
      }
      
      &:last-child {
        margin-bottom: 0;
      }
    }
  }
}

// 響應式設計
@media (max-width: 480px) {
  .login-layout {
    padding: 16px;
    
    .login-container {
      max-width: 100%;
      
      .login-header {
        padding: 24px;
        
        .login-logo {
          width: 48px;
          height: 48px;
          margin-bottom: 16px;
        }
        
        .login-title {
          font-size: 20px;
          margin-bottom: 8px;
        }
        
        .login-subtitle {
          font-size: 13px;
        }
      }
      
      .login-body {
        padding: 24px;
      }
      
      .login-footer {
        padding: 16px 24px;
        font-size: 12px;
      }
    }
  }
}

// 加載狀態下的樣式
.loading {
  pointer-events: none;
  opacity: 0.7;
}

// 動畫效果
.login-container {
  animation: slideInUp 0.5s ease-out;
}

@keyframes slideInUp {
  from {
    transform: translateY(30px);
    opacity: 0;
  }
  to {
    transform: translateY(0);
    opacity: 1;
  }
}

// Element Plus 組件樣式覆蓋
:deep(.el-form-item__label) {
  color: var(--el-text-color-primary);
  font-weight: 500;
}

:deep(.el-input__inner) {
  border-radius: 6px;
}

:deep(.el-button) {
  border-radius: 6px;
  font-weight: 500;
}

:deep(.el-checkbox__label) {
  font-size: 14px;
  color: var(--el-text-color-regular);
}
</style>