import request from '@/utils/request';
import { setToken } from '@/utils/token-util';
import type { ApiResult } from '@/api';
import type {
  LoginParam,
  LoginResult,
  CaptchaResult,
  SmsCaptchaResult
} from './model';
import { User } from '@/api/system/user/model';
import { SERVER_API_URL } from '@/config/setting';
import type { LoginOutcome, TenantOption } from './model';

/**
 * 登录态落地：把后端返回的 access_token / 租户 / 用户 持久化到本地
 */
function saveLoginState(result: LoginResult | undefined, remember?: boolean) {
  if (!result) return;
  if (result.access_token) {
    setToken(result.access_token, remember);
  }
  const user = result.user;
  if (user) {
    if (user.tenantId != null) {
      try {
        localStorage.setItem('TenantId', String(user.tenantId));
      } catch { /* ignore */ }
    }
    if (user.userId != null) {
      try {
        localStorage.setItem('UserId', String(user.userId));
      } catch { /* ignore */ }
    }
  }
}

/**
 * 登录
 */
export async function login(data: LoginParam) {
  const res = await request.post<ApiResult<LoginResult>>(
    SERVER_API_URL + '/login',
    data
  );
  if (res.data.code === 0) {
    setToken(res.data.data?.access_token, data.remember);
    if (res.data.data?.user) {
      const user = res.data.data?.user;
      localStorage.setItem('TenantId', String(user.tenantId));
      localStorage.setItem('UserId', String(user.userId));
    }

    return res.data.message;
  }
  return Promise.reject(new Error(res.data.message));
}

/**
 * 获取验证码
 */
export async function getCaptcha() {
  const res = await request.get<ApiResult<CaptchaResult>>(
    SERVER_API_URL + '/captcha'
  );
  if (res.data.code === 0 && res.data.data) {
    return res.data.data;
  }
  return Promise.reject(new Error(res.data.message));
}

export async function loginBySms(data: LoginParam) {
  const res = await request.post<ApiResult<LoginResult>>(
    SERVER_API_URL + '/loginBySms',
    data
  );
  if (res.data.code === 0) {
    setToken(res.data.data?.access_token, data.remember);
    if (res.data.data?.user) {
      const user = res.data.data?.user;
      localStorage.setItem('TenantId', String(user.tenantId));
      localStorage.setItem('UserId', String(user.userId));
    }

    return res.data.message;
  }
  return Promise.reject(new Error(res.data.message));
}

/**
 * 用户ID登录
 */
export async function loginByUserId(data: LoginParam) {
  const res = await request.post<ApiResult<LoginResult>>(
    'https://server.websoft.top/api/loginByUserId',
    data
  );
  if (res.data.code === 0) {
    setToken(res.data.data?.access_token, data.remember);
    if (res.data.data?.user) {
      const user = res.data.data?.user;
      localStorage.setItem('TenantId', String(user.tenantId));
      localStorage.setItem('UserId', String(user.userId));
    }
    return res.data.message;
  }
  return Promise.reject(new Error(res.data.message));
}

/**
 * 超级管理员短信验证码登录
 * 后端对应 POST /loginBySuperAdminSms，参数为 { phone, code, tenantId }
 * - 单租户：直接返回 ok
 * - 多租户：返回 selectTenant，前端需调用 loginBySelectTenant 二次登录
 */
export async function loginBySuperAdminSms(
  data: LoginParam
): Promise<LoginOutcome> {
  const res = await request.post<ApiResult<LoginResult>>(
    SERVER_API_URL + '/loginBySuperAdminSms',
    { phone: data.phone, code: data.code ?? data.smsCode, smsCode: data.smsCode, tenantId: data.tenantId }
  );
  if (res.data.code !== 0) {
    return Promise.reject(new Error(res.data.message));
  }
  const result = res.data.data;
  if (result?.tenants && result.tenants.length > 0) {
    return {
      status: 'selectTenant',
      tenants: result.tenants as TenantOption[],
      message: res.data.message || '请选择要登录的租户'
    };
  }
  if (result?.user) {
    saveLoginState(result, data.remember);
    return { status: 'ok', user: result.user, message: res.data.message || '登录成功' };
  }
  return Promise.reject(new Error(res.data.message || '登录失败'));
}

/**
 * 选择租户后登录（多租户短信登录专用二次登录接口）
 * 后端对应 POST /loginBySelectTenant，参数为 { phone, code, tenantId }
 */
export async function loginBySelectTenant(data: {
  phone: string;
  code: string;
  tenantId: number;
  remember?: boolean;
}): Promise<LoginOutcome> {
  const res = await request.post<ApiResult<LoginResult>>(
    SERVER_API_URL + '/loginBySelectTenant',
    { phone: data.phone, code: data.code, smsCode: data.code, tenantId: data.tenantId }
  );
  if (res.data.code !== 0) {
    return Promise.reject(new Error(res.data.message));
  }
  const result = res.data.data;
  if (result?.user) {
    saveLoginState(result, data.remember);
    return { status: 'ok', user: result.user, message: res.data.message || '登录成功' };
  }
  return Promise.reject(new Error(res.data.message || '登录失败'));
}

/**
 * 邮箱登录（跨租户）
 */
export async function loginByEmail(data: LoginParam) {
  const res = await request.post<ApiResult<LoginResult>>(
    'https://server.websoft.top/api/loginByEmail',
    data
  );
  if (res.data.code === 0) {
    setToken(res.data.data?.access_token, data.remember);
    if (res.data.data?.user) {
      const user = res.data.data?.user;
      localStorage.setItem('TenantId', String(user.tenantId));
      localStorage.setItem('UserId', String(user.userId));
    }
    return res.data.message;
  }
  return Promise.reject(new Error(res.data.message));
}

/**
 * 发送短信验证码
 */
export async function sendSmsCaptcha(data: LoginParam) {
  const res = await request.post<ApiResult<SmsCaptchaResult>>(
    SERVER_API_URL + '/sendSmsCaptcha',
    data
  );
  if (res.data.code === 0) {
    return res.data.message;
  }
  return Promise.reject(new Error(res.data.message));
}

/**
 * 发送短信验证码（后台管理员，跨租户：只要该手机号是超管或管理员即发送）
 * 后端对应 POST /sendSmsCaptchaByAdmin，参数为 { phone }
 * @param options.skipTenant 为 true 时不携带 tenantId 请求头（登录前无法确定租户时使用）
 */
export async function sendSmsCaptchaByAdmin(
  data: LoginParam,
  options?: { skipTenant?: boolean }
) {
  const res = await request.post<ApiResult<SmsCaptchaResult>>(
    SERVER_API_URL + '/sendSmsCaptchaByAdmin',
    data,
    options?.skipTenant ? { headers: { 'X-Tenant-Skip': '1' } } : undefined
  );
  if (res.data.code === 0) {
    return res.data.message;
  }
  return Promise.reject(new Error(res.data.message));
}

/**
 * 发送邮箱验证码（找回密码等登录前场景使用）
 * 后端对应 POST /sendEmailCaptcha，参数为 { email }
 * @param options.skipTenant 为 true 时不携带 tenantId 请求头（登录前无法确定租户时使用）
 */
export async function sendEmailCaptcha(
  data: LoginParam,
  options?: { skipTenant?: boolean }
) {
  const res = await request.post<ApiResult<unknown>>(
    SERVER_API_URL + '/sendEmailCaptcha',
    data,
    options?.skipTenant ? { headers: { 'X-Tenant-Skip': '1' } } : undefined
  );
  if (res.data.code === 0) {
    return res.data.message;
  }
  return Promise.reject(new Error(res.data.message));
}

/**
 * 登录
 */
export async function remoteLogin(data: LoginParam) {
  const res = await request.post<ApiResult<LoginResult>>(
    'https://open.gxwebsoft.com/api/login',
    data
  );
  if (res.data.code === 0) {
    setToken(res.data.data?.access_token, data.remember);
    return res.data.message;
  }
  return Promise.reject(new Error(res.data.message));
}

/**
 * 获取企业微信登录链接
 */
export async function getWxWorkQrConnect(data) {
  const res = await request.post<ApiResult<unknown>>(
    SERVER_API_URL + '/wx-work',
    data
  );
  if (res.data.code === 0 && res.data.data) {
    return res.data.data;
  }
  return Promise.reject(new Error(res.data.message));
}

export async function registerUser(data: User) {
  const res = await request.post<ApiResult<unknown>>(
    SERVER_API_URL + '/register',
    data
  );
  if (res.data.code === 0) {
    return res.data.message;
  }
  return Promise.reject(new Error(res.data.message));
}
