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

import { getAuthToken } from "@/utils/token";
import { getUsersApiV1UsersGet, createUserApiV1UsersPost, getUserApiV1UsersUserIdGet, updateUserApiV1UsersUserIdPut, activateUserApiV1UsersUserIdActivatePost, deactivateUserApiV1UsersUserIdDeactivatePost, deleteUserApiV1UsersUserIdDelete } from "@/lib/api/sdk.gen";

// API返回的员工数据类型
export interface EmployeeApiData {
  id: string;
  tenant_id: string;
  email: string;
  username: string;
  full_name: string | null;
  phone: string | null;
  is_active: boolean;
  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 EmployeesApiResponse {
  data: EmployeeApiData[];
  total: number;
  page: number;
  size: number;
  total_pages: number;
  has_next: boolean;
  has_prev: boolean;
}

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

// 创建用户请求参数接口
export interface CreateEmployeeRequest {
  email: string;
  username: string;
  full_name?: string;
  phone: string;
  password: string;
  tenant_id?: string;
  scope?: string;
  department_id?: string;
  is_superuser?: boolean;
}

// 更新用户请求参数接口
export interface UpdateEmployeeRequest {
  email?: string;
  username?: string;
  full_name?: string;
  phone?: string;
  password?: string;
  tenant_id?: string;
  scope?: string;
  department_id?: string;
  is_superuser?: boolean;
}

// 页面使用的员工数据类型（转换后的）
export interface Employee {
  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 fetchEmployees(params: EmployeesQueryParams = {}): Promise<EmployeesApiResponse> {
  try {
    // 构建查询参数对象
    const queryParams: any = {};

    if (params.search) queryParams.search = params.search;
    if (params.page) queryParams.page = params.page;
    if (params.size) queryParams.size = params.size;
    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';

    // 获取认证token
    const token = getAuthToken();
    console.log('员工管理API调用参数:', queryParams);

    // 使用SDK API调用用户查询接口
    const response = await getUsersApiV1UsersGet({
      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响应格式处理数据
    // 如果API直接返回数组，我们需要模拟分页响应
    if (Array.isArray(data)) {
      // 如果API返回数组，假设是当前页的数据
      return {
        data: data,
        total: data.length, // 这种情况下无法获取总数，使用当前页数据量
        page: params.page || 1,
        size: params.size || 10,
        total_pages: 1, // 无法确定总页数
        has_next: false,
        has_prev: (params.page || 1) > 1,
      };
    } else if (data && typeof data === 'object' && data.data) {
      // 如果API返回分页格式（和你提供的响应一致）
      return {
        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,
      };
    } else {
      // 其他情况，返回空结果
      return {
        data: [],
        total: 0,
        page: 1,
        size: 10,
        total_pages: 0,
        has_next: false,
        has_prev: false,
      };
    }
  } catch (error) {
    console.error('Failed to fetch employees:', error);
    throw error;
  }
}

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

/**
 * 批量转换员工数据
 */
export function transformEmployeesList(employees: EmployeeApiData[]): Employee[] {
  return employees.map(transformEmployeeData);
}

/**
 * 格式化日期
 */
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;
  }
}

/**
 * 创建员工用户
 */
export async function createEmployee(employeeData: CreateEmployeeRequest): Promise<Employee> {
  try {
    // 获取认证token
    const token = getAuthToken();
    console.log('创建员工API调用参数:', employeeData);

    // 使用SDK API调用创建用户接口
    const response = await createUserApiV1UsersPost({
      body: employeeData,
      headers: token ? {
        'Authorization': `Bearer ${token}`,
      } : undefined,
    });

    if (response.error) {
      // 处理API错误响应
      const errorData = response.error as any;

      // 检查是否是409冲突错误（用户已存在）
      if (errorData.status === 409 && errorData.data) {
        const conflictError = errorData.data as {
          code?: string;
          message?: string;
          domain?: string;
          detail?: {
            field?: string;
            value?: string;
          };
        };

        // 抛出包含详细错误信息的异常
        throw new Error(conflictError.message || '用户创建失败');
      }

      // 其他HTTP错误
      if (errorData.data && errorData.data.message) {
        throw new Error(errorData.data.message);
      }

      // 通用错误处理
      throw new Error(errorData.message || `API error: ${errorData.status || 'Unknown error'}`);
    }

    const data = response.data as any;
    console.log('创建员工API响应:', data);

    // 转换并返回新创建的员工数据
    return transformEmployeeData(data);
  } catch (error) {
    console.error('Failed to create employee:', error);
    throw error;
  }
}

/**
 * 获取用户详情信息
 */
export async function fetchEmployeeDetail(userId: string): Promise<Employee> {
  try {
    // 获取认证token
    const token = getAuthToken();
    console.log('获取用户详情API调用参数:', { userId });

    // 使用SDK API调用用户详情查询接口
    const response = await getUserApiV1UsersUserIdGet({
      path: {
        user_id: userId,
      },
      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);

    // 转换并返回员工详情数据
    return transformEmployeeData(data);
  } catch (error) {
    console.error('Failed to fetch employee detail:', error);
    throw error;
  }
}

/**
 * 更新员工用户信息
 */
export async function updateEmployee(userId: string, employeeData: UpdateEmployeeRequest): Promise<Employee> {
  try {
    // 获取认证token
    const token = getAuthToken();
    console.log('更新员工API调用参数:', { userId, employeeData });

    // 使用SDK API调用更新用户接口
    const response = await updateUserApiV1UsersUserIdPut({
      path: {
        user_id: userId,
      },
      body: employeeData as any, // 使用any类型绕过类型检查，因为API类型定义与实际需求不匹配
      headers: token ? {
        'Authorization': `Bearer ${token}`,
      } : undefined,
    });

    if (response.error) {
      // 处理API错误响应
      const errorData = response.error as any;

      // 检查是否有详细的错误信息
      if (errorData.data && errorData.data.message) {
        throw new Error(errorData.data.message);
      }

      // 通用错误处理
      throw new Error(errorData.message || `API error: ${errorData.status || 'Unknown error'}`);
    }

    const data = response.data as any;
    console.log('更新员工API响应:', data);

    // 转换并返回更新后的员工数据
    return transformEmployeeData(data);
  } catch (error) {
    console.error('Failed to update employee:', error);
    throw error;
  }
}

/**
 * 激活用户
 */
export async function activateUser(userId: string): Promise<void> {
  try {
    // 获取认证token
    const token = getAuthToken();
    console.log('激活用户API调用参数:', { userId });

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

    if (response.error) {
      // 处理API错误响应
      const errorData = response.error as any;

      // 检查是否有详细的错误信息
      if (errorData.data && errorData.data.message) {
        throw new Error(errorData.data.message);
      }

      // 通用错误处理
      throw new Error(errorData.message || `API error: ${errorData.status || 'Unknown error'}`);
    }

    console.log('激活用户API响应:', response.data);
  } catch (error) {
    console.error('Failed to activate user:', error);
    throw error;
  }
}

/**
 * 停用用户
 */
export async function deactivateUser(userId: string): Promise<void> {
  try {
    // 获取认证token
    const token = getAuthToken();
    console.log('停用用户API调用参数:', { userId });

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

    if (response.error) {
      // 处理API错误响应
      const errorData = response.error as any;

      // 检查是否有详细的错误信息
      if (errorData.data && errorData.data.message) {
        throw new Error(errorData.data.message);
      }

      // 通用错误处理
      throw new Error(errorData.message || `API error: ${errorData.status || 'Unknown error'}`);
    }

    console.log('停用用户API响应:', response.data);
  } catch (error) {
    console.error('Failed to deactivate user:', error);
    throw error;
  }
}

/**
 * 删除用户
 */
export async function deleteUser(userId: string): Promise<void> {
  try {
    // 获取认证token
    const token = getAuthToken();
    console.log('删除用户API调用参数:', { userId });

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

    if (response.error) {
      // 处理API错误响应
      const errorData = response.error as any;

      // 检查是否有详细的错误信息
      if (errorData.data && errorData.data.message) {
        throw new Error(errorData.data.message);
      }

      // 通用错误处理
      throw new Error(errorData.message || `API error: ${errorData.status || 'Unknown error'}`);
    }

    console.log('删除用户API响应:', response.data);
  } catch (error) {
    console.error('Failed to delete user:', error);
    throw error;
  }
}

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