<script setup lang="ts">
import { reactive, ref } from "vue";
import { ElMessage } from "element-plus";
import { adminApi } from "../../api/admin";
import { setAdminInfo, setAdminToken } from "../../utils/auth";
import { goToAdminHome } from "../../utils/navigation";

const loading = ref(false);
const form = reactive({
  mobile: "",
  password: "",
});

async function submitLogin() {
  if (!form.mobile.trim() || !form.password.trim()) {
    ElMessage.warning("请输入手机号和密码");
    return;
  }

  loading.value = true;
  try {
    const response = await adminApi.login(form.mobile.trim(), form.password.trim());
    setAdminToken(response.data.token);
    setAdminInfo(response.data.admin_info);
    ElMessage.success("登录成功");
    goToAdminHome();
  } catch (error: any) {
    console.error(error);
    ElMessage.error(error?.message || error?.payload?.message || "登录失败");
  } finally {
    loading.value = false;
  }
}
</script>

<template>
  <div class="login-page">
    <div class="login-card">
      <div class="login-card__eyebrow">安心验后台</div>
      <div class="login-card__title">管理员登录</div>
      <div class="login-card__desc">进入订单履约、报告审核、用户管理和系统配置中心。</div>

      <el-form label-position="top" @submit.prevent>
        <el-form-item label="管理员手机号">
          <el-input v-model="form.mobile" placeholder="请输入管理员手机号" />
        </el-form-item>
        <el-form-item label="登录密码">
          <el-input v-model="form.password" type="password" show-password placeholder="请输入登录密码" @keyup.enter="submitLogin" />
        </el-form-item>
      </el-form>

      <el-button type="primary" class="login-card__action" :loading="loading" @click="submitLogin">
        {{ loading ? "登录中..." : "进入后台" }}
      </el-button>
    </div>
  </div>
</template>
