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

import { getAuthToken } from "@/utils/token";
import {
  getDepartmentTreeApiV1DepartmentsTreeGet,
  getUsersApiV1UsersGet
} from "@/lib/api/sdk.gen";

// API返回的部门数据类型
export interface DepartmentApiData {
  id: string;
  name: string;
  code: string;
  parent_id: string | null;
  manager_name: string | null;
  manager_phone: string | null;
  manager_email: string | null;
  description: string | null;
  status: string;
  created_at: string;
  updated_at: string;
  tenant_id: string;
  order_index: number;
  created_by: string | null;
  updated_by: string | null;
  children?: DepartmentApiData[];
}

// API返回的用户数据类型（用于部门成员）
export interface UserApiData {
  id: string;
  username: string;
  email: string;
  full_name: string | null;
  display_name: string | null;
  phone: string | null;
  is_active: boolean;
  department_id: string | null;
  department_name: string | null;
  created_at: string;
  last_login_at: string | null;
}

// API响应接口
export interface DepartmentTreeApiResponse {
  data: DepartmentApiData[];
  total: number;
  success: boolean;
  message?: string;
}

// 页面使用的部门数据类型（转换后的）
export interface Department {
  id: string;
  name: string;
  code: string;
  parentId: string | null;
  managerId: string | null;
  description: string | null;
  isActive: boolean;
  createdAt: string;
  updatedAt: string;
  tenantId: string;
  sortOrder: number;
  memberCount?: number;
  children: Department[];
  expanded: boolean;
  level: number;
  // 兼容现有页面的字段
  manager?: string;
  employeeCount?: number;
  description?: string;
  status?: 'active' | 'inactive';
}

// 页面使用的用户数据类型（转换后的）
export interface DepartmentUser {
  id: string;
  username: string;
  email: string;
  fullName: string | null;
  displayName: string | null;
  phone: string | null;
  isActive: boolean;
  departmentId: string | null;
  departmentName: string | null;
  createdAt: string;
  lastLoginAt: string | null;
}

// 查询参数接口
export interface DepartmentQueryParams {
  include_inactive?: boolean;
  include_members?: boolean;
}

/**
 * 获取部门树形结构数据
 */
export async function fetchDepartmentTree(params: DepartmentQueryParams = {}): Promise<DepartmentTreeApiResponse> {
  try {
    // 构建查询参数对象
    const queryParams: any = {};

    if (params.include_inactive !== undefined) queryParams.include_inactive = params.include_inactive;
    if (params.include_members !== undefined) queryParams.include_members = params.include_members;

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

    // 使用SDK API调用部门树形结构查询接口
    const response = await getDepartmentTreeApiV1DepartmentsTreeGet({
      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 (Array.isArray(data)) {
      // 如果API直接返回数组
      return {
        data: data,
        total: data.length,
        success: true,
      };
    } else if (data && typeof data === 'object') {
      // 如果API返回对象格式
      return {
        data: data.data || data.items || [],
        total: data.total || data.count || 0,
        success: data.success !== false,
        message: data.message,
      };
    } else {
      // 其他情况，返回空结果
      return {
        data: [],
        total: 0,
        success: false,
        message: 'Invalid response format',
      };
    }
  } catch (error) {
    console.error('Failed to fetch department tree:', error);
    throw error;
  }
}

/**
 * 获取部门成员列表
 */
export async function fetchDepartmentUsers(departmentId: string): Promise<DepartmentUser[]> {
  try {
    // 获取认证token
    const token = getAuthToken();

    // 使用SDK API调用用户查询接口，按部门筛选
    const response = await getUsersApiV1UsersGet({
      query: {
        department_id: departmentId,
        _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;

    let users: any[] = [];
    if (Array.isArray(data)) {
      users = data;
    } else if (data && typeof data === 'object' && data.data) {
      users = data.data;
    }

    return users.map(transformUserData);
  } catch (error) {
    console.error('Failed to fetch department users:', error);
    throw error;
  }
}

/**
 * 将API数据转换为页面所需的部门数据格式
 */
export function transformDepartmentData(department: DepartmentApiData, level: number = 0): Department {
  return {
    id: department.id,
    name: department.name,
    code: department.code,
    parentId: department.parent_id,
    managerId: null, // API中没有manager_id字段
    description: department.description,
    isActive: department.status === 'active',
    createdAt: formatDate(department.created_at),
    updatedAt: formatDate(department.updated_at),
    tenantId: department.tenant_id,
    sortOrder: department.order_index,
    memberCount: 0, // API中没有member_count字段
    children: (department.children || []).map(child => transformDepartmentData(child, level + 1)),
    expanded: level === 0, // 默认展开顶级部门
    level,
    // 兼容现有页面的字段
    manager: department.manager_name || undefined,
    phone: department.manager_phone || undefined,
    email: department.manager_email || undefined,
    employeeCount: 0,
    status: department.status as 'active' | 'inactive',
  };
}

/**
 * 将API数据转换为页面所需的用户数据格式
 */
export function transformUserData(user: UserApiData): DepartmentUser {
  return {
    id: user.id,
    username: user.username,
    email: user.email,
    fullName: user.full_name,
    displayName: user.display_name || user.full_name || user.username,
    phone: user.phone,
    isActive: user.is_active,
    departmentId: user.department_id,
    departmentName: user.department_name,
    createdAt: formatDate(user.created_at),
    lastLoginAt: user.last_login_at ? formatDate(user.last_login_at) : null,
  };
}

/**
 * 批量转换部门数据
 */
export function transformDepartmentList(departments: DepartmentApiData[]): Department[] {
  return departments.map(dept => transformDepartmentData(dept));
}

/**
 * 扁平化部门树形结构（用于搜索和筛选）
 */
export function flattenDepartments(departments: Department[]): Department[] {
  const result: Department[] = [];

  function flatten(depts: Department[]) {
    depts.forEach(dept => {
      result.push(dept);
      if (dept.children && dept.children.length > 0) {
        flatten(dept.children);
      }
    });
  }

  flatten(departments);
  return result;
}

/**
 * 在部门树中查找部门
 */
export function findDepartmentInTree(departments: Department[], departmentId: string): Department | null {
  for (const dept of departments) {
    if (dept.id === departmentId) {
      return dept;
    }
    if (dept.children && dept.children.length > 0) {
      const found = findDepartmentInTree(dept.children, departmentId);
      if (found) return found;
    }
  }
  return null;
}

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

// Department tree state interface for page components
export interface DepartmentTreeState {
  departments: Department[];
  flattenedDepartments: Department[];
  selectedDepartment: Department | null;
  loading: boolean;
  error: string | null;
  searchKeyword: string;
  expandedDepartments: Set<string>;
}