<template>
  <div class="login-container">
    <el-card class="login-card">
      <template #header>
        <h2 class="login-title">调压通管理后台</h2>
      </template>
      <el-form :model="loginForm" :rules="rules" ref="loginFormRef" @keyup.enter="handleLogin">
        <el-form-item prop="phone">
          <el-input v-model="loginForm.phone" placeholder="请输入手机号" :prefix-icon="User" />
        </el-form-item>
        <el-form-item prop="password">
          <el-input v-model="loginForm.password" type="password" placeholder="请输入密码" show-password :prefix-icon="Lock" />
        </el-form-item>
        <el-form-item prop="role">
          <el-select v-model="loginForm.role" placeholder="请选择登录角色" style="width: 100%;">
            <el-option label="系统管理员" value="SYSTEM_ADMIN" />
            <el-option label="医院管理员" value="HOSPITAL_ADMIN" />
            <el-option label="科室主任" value="DIRECTOR" />
            <el-option label="医疗组长" value="LEADER" />
            <el-option label="医生" value="DOCTOR" />
            <el-option label="工程师" value="ENGINEER" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-input-number
            v-model="loginForm.hospitalId"
            :min="1"
            :controls="false"
            placeholder="医院 ID（多账号场景建议填写）"
            style="width: 100%;"
          />
        </el-form-item>
        <el-alert
          type="info"
          :closable="false"
          title="若同一手机号在多个医院有同角色账号，请填写医院 ID。"
          style="margin-bottom: 16px;"
        />
        <el-form-item>
          <el-button type="primary" class="login-btn" :loading="loading" @click="handleLogin">登录</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { useUserStore } from '../store/user';
import { User, Lock } from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';

const router = useRouter();
const route = useRoute();
const userStore = useUserStore();

const loginFormRef = ref(null);
const loading = ref(false);

const loginForm = reactive({
  phone: '',
  password: '',
  role: 'SYSTEM_ADMIN', // Default role
  hospitalId: null,
});

const rules = {
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1\d{10}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 8, message: '密码长度至少为 8 位', trigger: 'blur' }
  ],
  role: [{ required: true, message: '请选择角色', trigger: 'change' }]
};

const handleLogin = async () => {
  if (!loginFormRef.value) return;
  await loginFormRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true;
      try {
        const success = await userStore.login(loginForm);
        if (success) {
          ElMessage.success('登录成功');
          const redirect = route.query.redirect || '/';
          router.push(redirect);
        } else {
          ElMessage.error('登录失败，未获取到登录信息');
        }
      } catch (error) {
        console.error('Login failed', error);
      } finally {
        loading.value = false;
      }
    }
  });
};
</script>

<style scoped>
.login-container {
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #f0f2f5;
}
.login-card {
  width: 400px;
}
.login-title {
  margin: 0;
  text-align: center;
  color: #303133;
}
.login-btn {
  width: 100%;
}
</style>
