import { http } from "@/utils/http";

/** 通用响应结果 */
type Result<T = any> = {
  code: number;
  message: string;
  data?: T;
};

// ==================== 项目列表 ====================

/** 项目列表项 - 根据 OpenAPI 定义 */
export type ProjectItem = {
  id?: number;
  projectCode?: string;
  projectName?: string;
  projectType?: string;
  managerId?: number;
  managerName?: string;
  planStartDate?: string;
  planEndDate?: string;
  progress?: number;
  status?: string;
  priority?: string;
  riskLevel?: string;
  tags?: string[];
  budget?: number;
  cost?: number;
  createTime?: string;
  myRole?: string;
};

/** 分页数据结构 */
export type TableDataInfo<T> = {
  total: number;
  rows: T[];
  code: number;
  msg: string;
};

/** 项目查询参数 */
export type ProjectQueryParams = {
  pageNum?: number;
  pageSize?: number;
  keyword?: string;
  status?: string;
};

/** 分页查询项目列表 */
export const getProjectList = (params?: ProjectQueryParams) => {
  return http.request<Result<TableDataInfo<ProjectItem>>>(
    "get",
    "/api/v1/project/list",
    { params }
  );
};

/** 删除项目 */
export const deleteProject = (id: number) => {
  return http.request<Result<void>>("delete", `/api/v1/project/${id}`);
};

// ==================== 项目统计 ====================

/** 项目统计数据 - 根据 OpenAPI 定义 */
export type ProjectStatistics = {
  totalCount: number;
  ongoingCount: number;
  completedCount: number;
  pausedCount: number;
  planningCount: number;
  cancelledCount: number;
  draftCount: number;
  statusCountMap: Record<string, number>;
  newThisMonth: number;
  aboutToExpireCount: number;
  averageProgress: number;
  highRiskCount: number;
};

/** 获取项目统计数据 */
export const getProjectStatistics = () => {
  return http.request<Result<ProjectStatistics>>(
    "get",
    "/api/v1/project/statistics"
  );
};

// ==================== 项目甘特图 ====================

/** 甘特图任务 */
export type GanttTask = {
  id?: number;
  taskName?: string;
  type?: string; // task-任务, milestone-里程碑
  startDate?: string;
  endDate?: string;
  actualStartDate?: string;
  actualEndDate?: string;
  progress?: number;
  status?: string;
  priority?: string;
  parentId?: number;
  sortOrder?: number;
  assigneeName?: string;
  dependencies?: number[];
};

/** 项目甘特图数据 */
export type ProjectGantt = {
  projectId?: number;
  projectName?: string;
  projectStatus?: string;
  projectStartDate?: string;
  projectEndDate?: string;
  projectProgress?: number;
  tasks?: GanttTask[];
  milestones?: GanttTask[];
};

/** 获取项目甘特图数据 */
export const getProjectGantt = (projectId: number) => {
  return http.request<Result<ProjectGantt>>(
    "get",
    `/api/v1/project/${projectId}/gantt`
  );
};

// ==================== 项目初始化（复用 system.ts 中的定义） ====================

/** 项目信息 */
export type ProjectInfo = {
  project_name?: string;
  project_type?: string;
  description?: string;
  objectives?: string;
  plan_start_date?: string;
  plan_end_date?: string;
  budget?: number;
  currency?: string;
  priority?: string;
  tags?: string[];
};

/** 里程碑信息 */
export type MilestoneInfo = {
  milestone_name?: string;
  description?: string;
  plan_date?: string;
  deliverables?: string;
  owner_role?: string;
};

/** 任务信息 */
export type TaskInfo = {
  task_id?: string;
  task_name?: string;
  parent_task_id?: string;
  description?: string;
  plan_start_date?: string;
  plan_end_date?: string;
  estimated_hours?: number;
  priority?: string;
  assignee_role?: string;
  dependencies?: string[];
  deliverables?: string;
};

/** 成员信息 */
export type MemberInfo = {
  name?: string;
  role_code?: string;
  responsibility?: string;
  department?: string;
  weekly_hours?: number;
};

/** 资源信息 */
export type ResourceInfo = {
  resource_name?: string;
  resource_type?: string;
  quantity?: number;
  unit?: string;
  unit_price?: number;
  supplier?: string;
};

/** 风险信息 */
export type RiskInfo = {
  risk_name?: string;
  category?: string;
  description?: string;
  probability?: number;
  impact?: number;
  mitigation_plan?: string;
};

/** 时间节点信息 */
export type TimelineNodeInfo = {
  node_name?: string;
  node_type?: string;
  plan_date?: string;
  description?: string;
  kb_scope?: string[];
};

/** 项目初始化结果 */
export type ProjectInitResult = {
  project: ProjectInfo;
  milestones: MilestoneInfo[];
  tasks: TaskInfo[];
  members: MemberInfo[];
  resources: ResourceInfo[];
  risks: RiskInfo[];
  timeline_nodes: TimelineNodeInfo[];
};

/** 上传文件并生成项目初始化预览数据 */
export const previewProjectInit = (file: File) => {
  const formData = new FormData();
  formData.append("file", file);
  return http.request<Result<ProjectInitResult>>(
    "post",
    "/api/v1/project-init/preview",
    { data: formData },
    {
      headers: {
        "Content-Type": undefined
      }
    }
  );
};

/** 确认并保存项目初始化数据 */
export const confirmProjectInit = (data: ProjectInitResult) => {
  return http.request<Result<ProjectInitResult>>(
    "post",
    "/api/v1/project-init/confirm",
    { data }
  );
};

// ==================== 项目初始化任务（SSE） ====================

/** 项目初始化任务 VO - 根据 OpenAPI 定义 */
export type ProjectInitTaskVO = {
  taskId: string;
  userId?: number;
  status: string; // pending, processing, completed, failed
  statusDesc: string;
  progress: number;
  progressMessage: string;
  originalFilename: string;
  createTime: string;
  startTime?: string;
  completeTime?: string;
  result?: ProjectInitResult;
  errorMessage?: string;
};

/** 任务统计信息 */
export type TaskStats = {
  total: number;
  processing: number;
  completed: number;
  failed: number;
};

/** 查询我的任务列表 */
export const getMyTasks = () => {
  return http.request<Result<ProjectInitTaskVO[]>>(
    "get",
    "/api/v1/project-init/my-tasks"
  );
};

/** 查询我的任务统计信息 */
export const getMyTaskStats = () => {
  return http.request<Result<TaskStats>>(
    "get",
    "/api/v1/project-init/my-tasks/stats"
  );
};

/** 查询单个任务状态 */
export const getTaskStatus = (taskId: string) => {
  return http.request<Result<ProjectInitTaskVO>>(
    "get",
    `/api/v1/project-init/task/${taskId}`
  );
};
