// @ts-nocheck
/**
 * filekorolheader: 用户管理API接口 - 用户数据查询接口服务
 * 功能：API请求封装、数据转换、错误处理、分页查询
 * 路径：/central-config/tenant/user-management/components/userManagementApi
 * 规范：遵循crop-x/docs/开发项目规范.md，使用SDK API调用，TypeScript类型安全
 */

import { getAuthToken } from "@/utils/token";
import {
  listSystemUsersApiV1UsersSystemUsersGet,
  createSystemUserApiV1UsersSystemUsersPost,
  getSystemUserApiV1UsersSystemUsersUserIdGet,
  activateSystemUserApiV1UsersSystemUsersUserIdActivatePost,
  deactivateSystemUserApiV1UsersSystemUsersUserIdDeactivatePost,
  deleteSystemUserApiV1UsersSystemUsersUserIdDelete,
} from "@/lib/api/sdk.gen";

// API返回的用户数据类型
export interface UserData {
  id: string;
  tenant_id: string;
  email: string;
  username: string;
  full_name: string | null;
  phone: string | null;
  is_active?: boolean;
  status?: string;
  is_superuser: boolean;
  is_verified: boolean;
  created_at: string;
  updated_at: string;
  last_login_at: string | null;
  avatar_url: string | null;
  bio: string | null;
  display_name: string | null;
  department_id: string | null;
  department_name: string | null;
  scope: string;
  company_name: string | null;
}

// API响应接口
export interface UsersApiResponse {
  data: UserData[];
  total: number;
  page: number;
  size: number;
  total_pages: number;
  has_next: boolean;
  has_prev: boolean;
}

// 查询参数接口
export interface UsersQueryParams {
  search?: string;
  is_active?: boolean;
  page?: number;
  size?: number;
  order_by?: string;
  sort_order?: 'asc' | 'desc';
}

// 页面使用的用户数据类型（转换后的）
export interface User {
  id: string;
  username: string;
  email: string;
  fullName: string | null;
  phone: string | null;
  isActive: boolean;
  isSuperuser: boolean;
  isVerified: boolean;
  createdAt: string;
  updatedAt: string;
  lastLoginAt: string | null;
  avatarUrl: string | null;
  bio: string | null;
  displayName: string | null;
  departmentId: string | null;
  departmentName: string | null;
  scope: string;
  companyName: string | null;
  tenantId: string;
}

/**
 * 获取用户列表数据
 */
export async function fetchUsers(params: UsersQueryParams = {}): Promise<UsersApiResponse> {
  try {
    // 构建查询参数对象
    const queryParams: any = {};

    if (params.search) queryParams.search = params.search;
    if (params.is_active !== undefined) queryParams.is_active = params.is_active;
    if (params.page) queryParams.page = params.page;
    if (params.size) queryParams.size = params.size;
    if (params.order_by) queryParams.order_by = params.order_by;
    if (params.sort_order) queryParams.sort_order = params.sort_order;

    // 默认参数
    if (!params.page) queryParams.page = 1;
    if (!params.size) queryParams.size = 10;
    if (!params.sort_order) queryParams.sort_order = 'desc';

    // 使用SDK API调用用户查询接口，添加缓存破坏器和认证头部
    const token = getAuthToken();
    console.log('用户管理API调用参数:', queryParams);

    const response = await listSystemUsersApiV1UsersSystemUsersGet({
      query: {
        ...queryParams,
        // 添加时间戳防止缓存
        _t: Date.now(),
      },
      headers: token ? {
        'Authorization': `Bearer ${token}`,
      } : undefined,
    });

    if (response.error) {
      throw new Error(`API error: ${response.error.message || 'Unknown error'}`);
    }

    const data = response.data as any;
    console.log('用户管理API响应:', data);

    // 转换响应数据格式以匹配现有的接口
    // API返回的数据结构: { data: [...], total: 25, page: 1, size: 10, ... }
    return {
      data: data?.data || [], // 注意：实际数据在 data.data 中
      total: data?.total || 0,
      page: data?.page || 1,
      size: data?.size || 10,
      total_pages: data?.total_pages || 0,
      has_next: data?.has_next || false,
      has_prev: data?.has_prev || false,
    };
  } catch (error) {
    console.error('Failed to fetch users:', error);
    throw error;
  }
}

/**
 * 将API数据转换为页面所需的用户数据格式
 * 优先显示display_name，其次full_name，最后username
 */
export function transformUserData(user: UserData): User {
  return {
    id: user.id,
    username: user.username,
    email: user.email,
    fullName: user.full_name,
    phone: user.phone,
    isActive: user.is_active !== undefined ? user.is_active : user.status === 'active',
    isSuperuser: user.is_superuser,
    isVerified: user.is_verified,
    createdAt: formatDate(user.created_at),
    updatedAt: formatDate(user.updated_at),
    lastLoginAt: user.last_login_at ? formatDate(user.last_login_at) : null,
    avatarUrl: user.avatar_url,
    bio: user.bio,
    displayName: user.display_name || user.full_name || user.username,
    departmentId: user.department_id,
    departmentName: user.department_name,
    scope: user.scope,
    companyName: user.company_name,
    tenantId: user.tenant_id,
  };
}

/**
 * 格式化日期
 */
function formatDate(dateString: string): string {
  try {
    const date = new Date(dateString);
    return date.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
    }).replace(/\//g, '-');
  } catch (error) {
    return dateString;
  }
}

// Pagination state interface for page components
export interface PaginationState {
  page: number;
  size: number;
  total: number;
  totalPages: number;
  hasNext: boolean;
  hasPrev: boolean;
}

// 创建用户请求参数接口
export interface CreateUserRequest {
  email: string;
  username: string;
  full_name: string;
  phone: string;
  password: string;
  is_superuser: boolean;
  tenant_id?: string; // 系统管理员不传，企业管理员必传
}

// 创建用户响应数据类型
export interface CreateUserResponse {
  id: string;
  email: string;
  username: string;
  full_name: string;
  phone: string;
  is_superuser: boolean;
  tenant_id?: string;
  is_active: boolean;
  created_at: string;
  updated_at: string;
}

/**
 * 创建系统用户（系统管理员或企业管理员）
 *
 * @param userData 用户创建数据
 * @returns 创建成功的用户数据
 */
export async function createUser(userData: CreateUserRequest): Promise<CreateUserResponse> {
  try {
    console.log(`[API] createUser 创建用户:`, userData);

    // 获取认证token
    const token = getAuthToken();

    // 构建请求参数
    const requestData: any = {
      email: userData.email,
      username: userData.username,
      full_name: userData.full_name,
      phone: userData.phone,
      password: userData.password,
      is_superuser: userData.is_superuser,
    };

    // 只有企业管理员才传tenant_id
    if (userData.tenant_id) {
      requestData.tenant_id = userData.tenant_id;
    }

    // 调用SDK API创建系统用户
    const response = await createSystemUserApiV1UsersSystemUsersPost({
      body: requestData,
      headers: token ? {
        'Authorization': `Bearer ${token}`,
      } : undefined,
    });

    if (response.error) {
      // 处理API错误，提取错误信息
      const errorMessage = response.error.message || '创建用户失败';
      console.error('[API] createUser 创建用户失败:', response.error);
      throw new Error(errorMessage);
    }

    const data = response.data as any;
    console.log('[API] createUser 创建用户成功:', data);

    // 返回创建成功的用户数据
    return {
      id: data.id,
      email: data.email,
      username: data.username,
      full_name: data.full_name,
      phone: data.phone,
      is_superuser: data.is_superuser,
      tenant_id: data.tenant_id,
      is_active: data.is_active,
      created_at: data.created_at,
      updated_at: data.updated_at,
    };

  } catch (error) {
    console.error('[API] createUser 创建用户异常:', error);

    // 如果是已知错误，直接抛出
    if (error instanceof Error) {
      throw error;
    }

    // 未知错误包装成标准错误格式
    throw new Error('创建用户失败，请稍后重试');
  }
}

/**
 * 验证用户创建数据
 *
 * @param userData 用户数据
 * @returns 验证结果
 */
export function validateUserData(userData: CreateUserRequest): { isValid: boolean; errors: string[] } {
  const errors: string[] = [];

  // 邮箱验证
  if (!userData.email) {
    errors.push('邮箱不能为空');
  } else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(userData.email)) {
    errors.push('邮箱格式不正确');
  }

  // 用户名验证
  if (!userData.username) {
    errors.push('用户名不能为空');
  } else if (userData.username.length < 3) {
    errors.push('用户名长度至少3位');
  }

  // 姓名验证
  if (!userData.full_name) {
    errors.push('姓名不能为空');
  }

  // 电话验证
  if (!userData.phone) {
    errors.push('电话不能为空');
  } else if (!/^1[3-9]\d{9}$/.test(userData.phone)) {
    errors.push('请输入正确的手机号码');
  }

  // 密码验证
  if (!userData.password) {
    errors.push('密码不能为空');
  } else if (userData.password.length < 6) {
    errors.push('密码长度至少6位');
  }

  // 企业管理员需要tenant_id
  if (!userData.is_superuser && !userData.tenant_id) {
    errors.push('企业管理员必须选择所属企业');
  }

  return {
    isValid: errors.length === 0,
    errors
  };
}

/**
 * 获取用户详情信息
 *
 * @param userId 用户ID
 * @returns 用户详情数据
 */
export async function fetchUserDetails(userId: string): Promise<UserData> {
  try {
    console.log(`[API] fetchUserDetails 获取用户详情: ${userId}`);

    // 获取认证token
    const token = getAuthToken();

    // 调用SDK API获取用户详情
    const response = await getSystemUserApiV1UsersSystemUsersUserIdGet({
      path: {
        user_id: userId,
      },
      headers: token ? {
        'Authorization': `Bearer ${token}`,
      } : undefined,
    });

    if (response.error) {
      const errorMessage = response.error.message || '获取用户详情失败';
      console.error('[API] fetchUserDetails 获取用户详情失败:', response.error);
      throw new Error(errorMessage);
    }

    const data = response.data as any;
    console.log('[API] fetchUserDetails 获取用户详情成功:', data);

    // 返回用户详情数据
    return {
      id: data.id,
      tenant_id: data.tenant_id,
      email: data.email,
      username: data.username,
      full_name: data.full_name,
      phone: data.phone,
      is_active: data.is_active,
      status: data.is_active ? 'active' : 'inactive',
      is_superuser: data.is_superuser,
      is_verified: data.is_verified,
      created_at: data.created_at,
      updated_at: data.updated_at,
      last_login_at: data.last_login_at,
      avatar_url: data.avatar_url,
      bio: data.bio,
      display_name: data.display_name,
      department_id: data.department_id,
      department_name: data.department_name,
      scope: data.scope || 'system',
      company_name: data.company_name,
    };

  } catch (error) {
    console.error('[API] fetchUserDetails 获取用户详情异常:', error);

    // 如果是已知错误，直接抛出
    if (error instanceof Error) {
      throw error;
    }

    // 未知错误包装成标准错误格式
    throw new Error('获取用户详情失败，请稍后重试');
  }
}

/**
 * 激活系统用户
 *
 * @param userId 用户ID
 * @returns 操作结果
 */
export async function activateUser(userId: string): Promise<void> {
  try {
    console.log(`[API] activateUser 激活用户: ${userId}`);

    // 获取认证token
    const token = getAuthToken();

    // 调用SDK API激活用户
    const response = await activateSystemUserApiV1UsersSystemUsersUserIdActivatePost({
      path: {
        user_id: userId,
      },
      headers: token ? {
        'Authorization': `Bearer ${token}`,
      } : undefined,
    });

    if (response.error) {
      // 处理API错误，提取错误信息
      const errorMessage = response.error.message || '激活用户失败';
      console.error('[API] activateUser 激活用户失败:', response.error);
      throw new Error(errorMessage);
    }

    console.log('[API] activateUser 激活用户成功:', userId);

  } catch (error) {
    console.error('[API] activateUser 激活用户异常:', error);

    // 如果是已知错误，直接抛出
    if (error instanceof Error) {
      throw error;
    }

    // 未知错误包装成标准错误格式
    throw new Error('激活用户失败，请稍后重试');
  }
}

/**
 * 停用系统用户
 *
 * @param userId 用户ID
 * @returns 操作结果
 */
export async function deactivateUser(userId: string): Promise<void> {
  try {
    console.log(`[API] deactivateUser 停用用户: ${userId}`);

    // 获取认证token
    const token = getAuthToken();

    // 调用SDK API停用用户
    const response = await deactivateSystemUserApiV1UsersSystemUsersUserIdDeactivatePost({
      path: {
        user_id: userId,
      },
      headers: token ? {
        'Authorization': `Bearer ${token}`,
      } : undefined,
    });

    if (response.error) {
      // 处理API错误，提取错误信息
      const errorMessage = response.error.message || '停用用户失败';
      console.error('[API] deactivateUser 停用用户失败:', response.error);
      throw new Error(errorMessage);
    }

    console.log('[API] deactivateUser 停用用户成功:', userId);

  } catch (error) {
    console.error('[API] deactivateUser 停用用户异常:', error);

    // 如果是已知错误，直接抛出
    if (error instanceof Error) {
      throw error;
    }

    // 未知错误包装成标准错误格式
    throw new Error('停用用户失败，请稍后重试');
  }
}

/**
 * 删除系统用户
 *
 * @param userId 用户ID
 * @returns 操作结果
 */
export async function deleteUser(userId: string): Promise<void> {
  try {
    console.log(`[API] deleteUser 删除用户: ${userId}`);

    // 获取认证token
    const token = getAuthToken();

    // 调用SDK API删除用户
    const response = await deleteSystemUserApiV1UsersSystemUsersUserIdDelete({
      path: {
        user_id: userId,
      },
      headers: token ? {
        'Authorization': `Bearer ${token}`,
      } : undefined,
    });

    if (response.error) {
      // 处理API错误，提取错误信息
      const errorMessage = response.error.message || '删除用户失败';
      console.error('[API] deleteUser 删除用户失败:', response.error);
      throw new Error(errorMessage);
    }

    console.log('[API] deleteUser 删除用户成功:', userId);

  } catch (error) {
    console.error('[API] deleteUser 删除用户异常:', error);

    // 如果是已知错误，直接抛出
    if (error instanceof Error) {
      throw error;
    }

    // 未知错误包装成标准错误格式
    throw new Error('删除用户失败，请稍后重试');
  }
}