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

import { getAuthToken } from "@/utils/token";
import {
  getRolesApiV1UsersPermissionsRolesGet,
  createRoleApiV1UsersPermissionsRolesPost,
  getRoleApiV1UsersPermissionsRolesRoleIdGet,
  deleteRoleApiV1UsersPermissionsRolesRoleIdDelete,
  updateRoleApiV1UsersPermissionsRolesRoleIdPut,
} from "@/lib/api/sdk.gen";
import {
  RoleApiData,
  Role,
  RolesApiResponse,
  RolesQueryParams,
} from '../types';

// 本地定义PaginationState以避免导入问题
export interface PaginationState {
  page: number;
  size: number;
  total: number;
  totalPages: number;
  hasNext: boolean;
  hasPrev: boolean;
}

// Re-export types from types.ts for convenience
export type { RolesApiResponse, RolesQueryParams } from '../types';

/**
 * 获取角色列表数据
 */
export async function fetchRoles(params: RolesQueryParams = {}): Promise<RolesApiResponse> {
  try {
    // 构建查询参数对象
    const queryParams: any = {};

    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 getRolesApiV1UsersPermissionsRolesGet({
      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响应数据
    if (data && typeof data === 'object' && data.data) {
      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 roles:', error);
    throw error;
  }
}

/**
 * 将API数据转换为页面所需的角色数据格式
 * 为了保持兼容性，这里转换数据格式
 */
export function transformRoleData(apiRole: RoleApiData): Role {
  return {
    id: apiRole.id, // 使用API返回的真实ID
    name: apiRole.name,
    code: apiRole.id, // 使用API返回的ID作为code，确保唯一性
    description: apiRole.description,
    type: 'custom', // 默认为自定义角色
    menuIds: [],
    permissionIds: [],
    status: 'active',
    createdAt: apiRole.created_at,
    updatedAt: apiRole.updated_at,
    tenant_id: apiRole.tenant_id,
  };
}

/**
 * 批量转换角色数据
 */
export function transformRolesList(apiRoles: RoleApiData[]): Role[] {
  return apiRoles.map(transformRoleData);
}

/**
 * 创建新角色
 */
export async function createRole(roleData: {
  name: string;
  description: string;
  permission_ids: string[];
}) {
  try {
    // 获取认证token
    const token = getAuthToken();
    console.log('创建角色API调用参数:', roleData);

    // 使用SDK API调用创建角色
    const response = await createRoleApiV1UsersPermissionsRolesPost({
      body: roleData,
      headers: token ? {
        'Authorization': `Bearer ${token}`,
      } : undefined,
    });

    if (response.error) {
      throw new Error(response.error.message || '创建角色失败');
    }

    console.log('创建角色API响应:', response.data);
    return response.data;
  } catch (error) {
    console.error('Failed to create role:', error);
    throw error;
  }
}

/**
 * 获取角色详情
 */
export async function getRoleDetail(roleId: string) {
  try {
    // 获取认证token
    const token = getAuthToken();
    console.log('获取角色详情API调用参数:', roleId);
    console.log('即将调用的URL: /api/v1/users/permissions/roles/' + roleId);

    // 使用SDK API调用获取角色详情
    const response = await getRoleApiV1UsersPermissionsRolesRoleIdGet({
      path: {
        role_id: roleId,
      },
      headers: token ? {
        'Authorization': `Bearer ${token}`,
      } : undefined,
    });

    if (response.error) {
      throw new Error(response.error.message || '获取角色详情失败');
    }

    console.log('获取角色详情API响应:', response.data);
    return response.data;
  } catch (error) {
    console.error('Failed to get role detail:', error);
    throw error;
  }
}

/**
 * 更新角色
 */
export async function updateRole(roleId: string, roleData: {
  name: string;
  description: string;
  permission_ids: string[];
}) {
  try {
    // 获取认证token
    const token = getAuthToken();
    console.log('更新角色API调用参数:', roleId, roleData);
    console.log('即将调用的URL: /api/v1/users/permissions/roles/' + roleId);

    // 使用SDK API调用更新角色
    const response = await updateRoleApiV1UsersPermissionsRolesRoleIdPut({
      path: {
        role_id: roleId,
      },
      body: roleData,
      headers: token ? {
        'Authorization': `Bearer ${token}`,
      } : undefined,
    });

    if (response.error) {
      throw new Error(response.error.message || '更新角色失败');
    }

    console.log('更新角色API响应:', response.data);
    return response.data;
  } catch (error) {
    console.error('Failed to update role:', error);
    throw error;
  }
}

/**
 * 删除角色
 */
export async function deleteRole(roleId: string) {
  try {
    // 获取认证token
    const token = getAuthToken();
    console.log('删除角色API调用参数:', roleId);
    console.log('即将调用的URL: /api/v1/users/permissions/roles/' + roleId);

    // 使用SDK API调用删除角色
    const response = await deleteRoleApiV1UsersPermissionsRolesRoleIdDelete({
      path: {
        role_id: roleId,
      },
      headers: token ? {
        'Authorization': `Bearer ${token}`,
      } : undefined,
    });

    if (response.error) {
      throw new Error(response.error.message || '删除角色失败');
    }

    console.log('删除角色API响应:', response.data);
    return response.data;
  } catch (error) {
    console.error('Failed to delete role:', error);
    throw error;
  }
}

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

