<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useAuthStore } from '../stores/auth'
import api from '../api'
import { ElMessage } from 'element-plus'

const router = useRouter()
const authStore = useAuthStore()

const activeTab = ref('sso')
const ssoUrl = ref('')

const form = ref({
  username: 'admin',
  password: ''
})

const loading = ref(false)

const fetchSSOConfig = async () => {
  try {
    const res = await api.get('/sso-config')
    ssoUrl.value = res.data.url
  } catch (error) {
    console.error('Failed to fetch SSO config', error)
    ElMessage.error('获取SSO配置失败')
  }
}

onMounted(() => {
  fetchSSOConfig()
})

const goToSSO = () => {
  if (ssoUrl.value) {
    window.location.href = ssoUrl.value
  } else {
    ElMessage.warning('正在获取跳转链接，请稍候...')
  }
}

const handleLogin = async () => {
  loading.value = true
  try {
    const formData = new FormData()
    formData.append('username', form.value.username)
    formData.append('password', form.value.password)
    
    const res = await api.post('/login', formData)
    authStore.setToken(res.data.access_token, form.value.username, res.data.is_superuser)
    ElMessage.success('登录成功')
    router.push('/')
  } catch (error) {
    ElMessage.error('登录失败')
  } finally {
    loading.value = false
  }
}
</script>

<template>
  <el-card class="login-card">
    <template #header>
      <div class="card-header">
        <span>AI 智能值班平台登录</span>
      </div>
    </template>
    <el-tabs v-model="activeTab" stretch>
      <el-tab-pane label="统一认证平台" name="sso">
        <div class="sso-container">
          <p>请点击下方按钮跳转至统一认证平台登录</p>
          <el-button type="primary" size="large" style="width: 100%; margin-top: 15px;" @click="goToSSO">前往统一认证平台</el-button>
        </div>
      </el-tab-pane>
      <el-tab-pane label="账号登录" name="account">
        <el-form :model="form" label-width="0px" class="login-form">
          <el-form-item>
            <el-input v-model="form.username" placeholder="用户名" prefix-icon="User" />
          </el-form-item>
          <el-form-item>
            <el-input v-model="form.password" type="password" placeholder="密码" prefix-icon="Lock" show-password @keyup.enter="handleLogin" />
          </el-form-item>
          <el-button type="primary" :loading="loading" style="width: 100%;" @click="handleLogin">登录</el-button>
        </el-form>
      </el-tab-pane>
    </el-tabs>
  </el-card>
</template>

<style scoped>
.login-card {
  width: 400px;
}
.card-header {
  text-align: center;
  font-weight: bold;
}
.sso-container {
  padding: 20px 10px;
  text-align: center;
}
.sso-container p {
  color: #606266;
  margin-bottom: 10px;
}
.login-form {
  margin-top: 10px;
}
</style>

