import { api, setToken } from "@/api/client"; import type { LoginResponse } from "@/types"; export async function login(username: string, password: string): Promise { const res = await api.post("/auth/login", { username, password }); setToken(res.token); return res; } // ---- 四种登录:短信验证码 / 微信扫码 / 小程序扫码 ---- export async function sendCode(phone: string): Promise<{ sent: boolean; message: string; stub_code?: string }> { return api.post("/auth/send-code", { phone }); } export async function phoneLogin(phone: string, code: string): Promise { const res = await api.post("/auth/phone-login", { phone, code }); setToken(res.token); return res; } /** 绑定手机号(验证码;若手机号已被占用则后端按手机号合并,返回新令牌需切换) */ export async function bindPhone(phone: string, code: string): Promise { const res = await api.post("/auth/bind-phone", { phone, code }); setToken(res.token); // 可能合并成另一个账号,必须切换到新令牌 return res; } /** 解绑登录方式:phone | wx | wx_mini(至少保留一种) */ export async function unbind(type: "phone" | "wx" | "wx_mini") { return api.post("/auth/unbind", { type }); } export async function wxQrStart(): Promise<{ scene: string; qr_url: string; redirect_uri: string; stub: boolean }> { return api.get("/auth/wx-qr/start"); } export async function wxQrPoll(scene: string): Promise<{ status: string; token?: string; profile?: LoginResponse }> { return api.get(`/auth/wx-qr/poll?scene=${encodeURIComponent(scene)}`); } export async function mpQrStart(): Promise<{ scene: string; qr_url: string; mp_enabled: boolean }> { return api.get("/auth/mp-qr/start"); } export async function mpQrPoll(scene: string): Promise<{ status: string; token?: string; profile?: LoginResponse; message?: string }> { return api.get(`/auth/mp-qr/poll?scene=${encodeURIComponent(scene)}`); } /** 发起「绑定小程序」:返回小程序码(微信扫码自动打开小程序确认),绑定到当前账号 */ export async function bindMpStart(): Promise<{ scene: string; qr_image?: string; qr_url?: string; mp_enabled: boolean }> { return api.get("/auth/mp-qr/bind-start"); } export async function fetchMe(): Promise> { return api.get("/auth/me"); } export function getSavedUser(): { username?: string; role?: string } | null { try { return JSON.parse(localStorage.getItem("@cloud-opc-admin/user") || "null"); } catch { return null; } } export function saveUser(user: { username?: string; role?: string } | null) { if (user) localStorage.setItem("@cloud-opc-admin/user", JSON.stringify(user)); else localStorage.removeItem("@cloud-opc-admin/user"); }