<template>
  <div class="login-page">
    <div class="login-card">
      <h1>管理会计OS</h1>
      <p class="subtitle">博海网络科技</p>
      <el-form ref="formRef" :model="form" label-width="0" @keyup.enter="handleLogin">
        <el-form-item>
          <el-input v-model="form.username" placeholder="用户名" size="large" @input="onUsernameChange" />
        </el-form-item>
        <el-form-item>
          <el-select v-model="form.entity_id" placeholder="选择登录公司" size="large" style="width:100%" :disabled="entities.length === 0">
            <el-option v-for="e in entities" :key="e.id" :label="e.short_name || e.name" :value="e.id">
              <span>{{ e.short_name || e.name }}</span>
              <span style="float:right;color:#999;font-size:12px;">{{ e.name }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item><el-input v-model="form.password" type="password" placeholder="密码" size="large" show-password /></el-form-item>
        <el-form-item><el-button type="primary" size="large" style="width:100%" :loading="loading" @click="handleLogin">登 录</el-button></el-form-item>
      </el-form>
    </div>
  </div>
</template>

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

const router = useRouter()
const loading = ref(false)
const entities = ref<any[]>([])
const form = reactive({ username: 'admin', password: 'admin123', entity_id: undefined as number | undefined })

async function loadEntities(username: string) {
  try {
    const r: any = await authApi.loginEntities(username)
    entities.value = r.data || []
    // 默认选中第一个授权企业
    if (entities.value.length > 0 && (form.entity_id === undefined || !entities.value.some((e: any) => e.id === form.entity_id))) {
      form.entity_id = entities.value[0].id
    }
  } catch (_) {
    entities.value = []
  }
}

function onUsernameChange(val: string) {
  if (val && val.trim()) loadEntities(val.trim())
}

async function handleLogin() {
  if (form.entity_id === undefined) {
    ElMessage.warning('请选择登录公司')
    return
  }
  loading.value = true
  try {
    const res: any = await authApi.login({ ...form, entity_id: Number(form.entity_id) })
    localStorage.setItem('cma_token', res.token)
    localStorage.setItem('cma_user', JSON.stringify(res.user))
    localStorage.setItem('cma_entity_id', String(res.entity_id ?? res.user?.entity_id ?? 1))
    localStorage.setItem('cma_entity_name', res.entity_short_name || res.entity_name || '')
    router.push('/my-dashboard')
  } catch (e: any) {
    ElMessage.error(e?.response?.data?.detail || '登录失败')
  }
  loading.value = false
}

onMounted(() => loadEntities(form.username))
</script>

<style scoped>
.login-page { display: flex; align-items: center; justify-content: center; height: 100vh; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); }
.login-card { background: #fff; padding: 40px; border-radius: 12px; width: 380px; text-align: center; }
.login-card h1 { margin: 0 0 4px; font-size: 24px; }
.subtitle { color: #999; margin-bottom: 24px; }
@media screen and (max-width: 768px) {
  .login-page { padding: 20px; }
  .login-card { width: 100%; max-width: 380px; padding: 30px 24px; }
}
</style>
