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

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

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

/** 项目列表项 - 根据 OpenAPI 定义 */
export type ProjectItem = {
  id?: string;
  projectCode?: string;
  projectName?: string;
  projectType?: string;
  managerId?: number;
  managerName?: string;
  managerAvatar?: 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: string) => {
  return http.request<Result<void>>("delete", `/api/v1/project/${id}`);
};

// ==================== 项目管理 API ====================

/** 项目实体 - 根据 OpenAPI 定义（用于编辑） */
export type Project = {
  id?: string;
  projectCode?: string;
  projectName?: string;
  projectType?: string;
  description?: string;
  objectives?: string;
  managerId?: string;
  sponsorId?: string;
  planStartDate?: string;
  planEndDate?: string;
  actualStartDate?: string;
  actualEndDate?: string;
  budget?: number;
  cost?: number;
  currency?: string;
  progress?: number;
  status?: string; // draft-草稿, planning-规划中, ongoing-进行中, paused-暂停, completed-已完成, cancelled-已取消
  priority?: string; // critical-关键, high-高, medium-中, low-低
  riskLevel?: string; // high-高, medium-中, low-低
  visibility?: number; // 1-公开, 2-部门内, 3-项目成员
  tags?: string[];
  extraData?: Record<string, any>;
};

/** 修改项目 */
export const updateProject = (data: Project) => {
  return http.request<Result<void>>("put", "/api/v1/project", { data });
};

/** 更新项目状态 */
export const updateProjectStatus = (id: string, status: string) => {
  return http.request<Result<void>>("put", `/api/v1/project/${id}/status`, {
    params: { status }
  });
};

/** 更新项目进度 */
export const updateProjectProgress = (id: string, progress: number) => {
  return http.request<Result<void>>("put", `/api/v1/project/${id}/progress`, {
    params: { progress }
  });
};

/** 更新项目经理 */
export const updateProjectManager = (id: string, managerName: string) => {
  return http.request<Result<void>>("put", `/api/v1/project/${id}/manager`, {
    params: { managerName }
  });
};

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

/** 项目统计数据 - 根据 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?: string;
  taskName?: string;
  type?: string; // task-任务, milestone-里程碑
  startDate?: string;
  endDate?: string;
  actualStartDate?: string;
  actualEndDate?: string;
  progress?: number;
  status?: string;
  priority?: string;
  parentId?: string;
  sortOrder?: number;
  assigneeName?: string;
  dependencies?: string[];
};

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

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

// ==================== 项目详情 ====================

/** 项目成员 */
export type ProjectMember = {
  id: string;
  userId?: string;
  userName?: string;
  realName?: string;
  avatar?: string;
  roleCode: string;
  department?: string;
  responsibility?: string;
  weeklyHours?: number;
  joinDate?: string;
  status?: number;
};

/** 项目里程碑 */
export type ProjectMilestone = {
  id: string;
  milestoneName: string;
  description?: string;
  planDate?: string;
  actualDate?: string;
  status?: string;
  progress?: number;
  isKey?: number;
  deliverables?: string;
  sortOrder?: number;
};

/** 项目任务 */
export type ProjectTask = {
  id: string;
  taskCode?: string;
  taskName: string;
  description?: string;
  taskType?: string;
  milestoneId?: string;
  assigneeId?: string;
  assigneeName?: string;
  planStartDate?: string;
  planEndDate?: string;
  actualStartDate?: string;
  actualEndDate?: string;
  planHours?: number;
  actualHours?: number;
  progress?: number;
  priority?: string;
  status?: string;
  sortOrder?: number;
};

/** 项目资源 */
export type ProjectResource = {
  id: string;
  resourceCode?: string;
  resourceType?: string;
  resourceName: string;
  description?: string;
  specification?: string;
  unit?: string;
  planQuantity?: number;
  actualQuantity?: number;
  unitPrice?: number;
  currency?: string;
  supplier?: string;
  status?: string;
  planArriveDate?: string;
  actualArriveDate?: string;
};

/** 项目风险 */
export type ProjectRisk = {
  id: string;
  riskCode?: string;
  category?: string;
  riskName: string;
  description?: string;
  probability?: number;
  impact?: number;
  riskScore?: number;
  riskLevel?: string;
  status?: string;
  ownerId?: string;
  mitigationPlan?: string;
  dueDate?: string;
  discoverTime?: string;
};

/** 时间线节点 */
export type TimelineNode = {
  id: string;
  nodeName: string;
  nodeType?: string;
  planDate?: string;
  actualDate?: string;
  description?: string;
  status?: string;
  sortOrder?: number;
  kbScope?: string[];
};

/** 项目详情 */
export type ProjectDetail = {
  id: string;
  projectCode: string;
  projectName: string;
  projectType: string;
  description?: string;
  objectives?: string;
  managerId?: string;
  managerName?: string;
  sponsorId?: string;
  planStartDate?: string;
  planEndDate?: string;
  actualStartDate?: string;
  actualEndDate?: string;
  budget?: number;
  cost?: number;
  currency?: string;
  progress?: number;
  status?: string;
  priority?: string;
  riskLevel?: string;
  visibility?: number;
  tags?: string[];
  createTime?: string;
  updateTime?: string;
  memberCount?: number;
  taskCount?: number;
  completedTaskCount?: number;
  milestoneCount?: number;
  resourceCount?: number;
  riskCount?: number;
  highRiskCount?: number;
  members?: ProjectMember[];
  milestones?: ProjectMilestone[];
  tasks?: ProjectTask[];
  resources?: ProjectResource[];
  risks?: ProjectRisk[];
  timelineNodes?: TimelineNode[];
};

/** 获取项目详情 */
export const getProjectDetail = (projectId: string) => {
  return http.request<Result<ProjectDetail>>(
    "get",
    `/api/v1/project/${projectId}`
  );
};

export type OverallProgressAssessment = {
  status?: string;
  deviationPercentage?: number;
  description?: string;
  keyIssues?: string[];
};

export type DailyReportUpdateSuggestionVO = {
  suggestionId?: string;
  targetType?: string;
  targetId?: string;
  targetName?: string;
  currentStatus?: string;
  currentProgress?: number;
  suggestedStatus?: string;
  suggestedProgress?: number;
  reason?: string;
  confidence?: number;
  status?: string;
};

export type DailyReportAnalysisSuggestionsVO = {
  analysisId?: string;
  reportId?: string;
  projectId?: string;
  reportDate?: string;
  overallProgressAssessment?: OverallProgressAssessment;
  suggestions?: DailyReportUpdateSuggestionVO[];
};

export const getDailyReportAnalysisSuggestions = (params: {
  projectId: string;
  reportId?: string;
  reportDate?: string;
  submitterUsername?: string;
}) => {
  return http.request<
    Result<DailyReportAnalysisSuggestionsVO | DailyReportUpdateSuggestionVO[]>
  >("get", "/api/v1/daily-report/analysis/suggestions", { params });
};

export type ApplyDailyReportSuggestionsRequest = {
  projectId: string;
  suggestionIds: string[];
};

export const applyDailyReportAnalysisSuggestions = (
  data: ApplyDailyReportSuggestionsRequest
) => {
  return http.request<Result<number>>(
    "post",
    "/api/v1/daily-report/analysis/suggestions/apply",
    { data }
  );
};

// ==================== 项目初始化（复用 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}`
  );
};

// ==================== 里程碑管理 API ====================

/** 里程碑查询参数 */
export type MilestoneQueryParams = {
  pageNum?: number;
  pageSize?: number;
  projectId?: string;
  status?: string;
};

/** 分页查询里程碑列表 */
export const getMilestoneList = (params?: MilestoneQueryParams) => {
  return http.request<Result<TableDataInfo<ProjectMilestone>>>(
    "get",
    "/api/v1/milestone/list",
    { params }
  );
};

/** 根据ID查询里程碑详情 */
export const getMilestoneById = (id: string) => {
  return http.request<Result<ProjectMilestone>>(
    "get",
    `/api/v1/milestone/${id}`
  );
};

/** 新增里程碑 */
export const createMilestone = (data: ProjectMilestone) => {
  return http.request<Result<string>>("post", "/api/v1/milestone", { data });
};

/** 修改里程碑 */
export const updateMilestone = (data: ProjectMilestone) => {
  return http.request<Result<void>>("put", "/api/v1/milestone", { data });
};

/** 删除里程碑 */
export const deleteMilestone = (id: string) => {
  return http.request<Result<void>>("delete", `/api/v1/milestone/${id}`);
};

/** 更新里程碑进度 */
export const updateMilestoneProgress = (id: string, progress: number) => {
  return http.request<Result<void>>("put", `/api/v1/milestone/${id}/progress`, {
    params: { progress }
  });
};

/** 更新里程碑状态 */
export const updateMilestoneStatus = (id: string, status: string) => {
  return http.request<Result<void>>("put", `/api/v1/milestone/${id}/status`, {
    params: { status }
  });
};

/** 查询已延期的关键里程碑 */
export const getDelayedKeyMilestones = (projectId: string) => {
  return http.request<Result<ProjectMilestone[]>>(
    "get",
    "/api/v1/milestone/delayed-key",
    { params: { projectId } }
  );
};

/** 查询即将到期的里程碑 */
export const getUpcomingMilestones = (projectId: string, days: number = 7) => {
  return http.request<Result<ProjectMilestone[]>>(
    "get",
    "/api/v1/milestone/upcoming",
    { params: { projectId, days } }
  );
};

/** 查询里程碑完成进度统计 */
export const getMilestoneProgressStats = (projectId: string) => {
  return http.request<Result<Record<string, any>>>(
    "get",
    "/api/v1/milestone/stats/progress",
    { params: { projectId } }
  );
};

// ==================== 任务管理 API ====================

/** 任务查询参数 */
export type TaskQueryParams = {
  pageNum?: number;
  pageSize?: number;
  projectId?: string;
  milestoneId?: string;
  assigneeId?: string;
  status?: string;
  priority?: string;
  keyword?: string;
};

/** 分页查询任务列表 */
export const getTaskList = (params?: TaskQueryParams) => {
  return http.request<Result<TableDataInfo<ProjectTask>>>(
    "get",
    "/api/v1/task/list",
    { params }
  );
};

/** 根据ID查询任务详情 */
export const getTaskById = (id: string) => {
  return http.request<Result<ProjectTask>>("get", `/api/v1/task/${id}`);
};

/** 新增任务 */
export const createTask = (data: ProjectTask) => {
  return http.request<Result<string>>("post", "/api/v1/task", { data });
};

/** 修改任务 */
export const updateTask = (data: ProjectTask) => {
  return http.request<Result<void>>("put", "/api/v1/task", { data });
};

/** 删除任务 */
export const deleteTask = (id: string) => {
  return http.request<Result<void>>("delete", `/api/v1/task/${id}`);
};

/** 查询我的待办任务 */
export const getMyTodoTasks = (userId: string, projectId?: string) => {
  return http.request<Result<ProjectTask[]>>("get", "/api/v1/task/my-tasks", {
    params: { userId, projectId }
  });
};

/** 更新任务进度 */
export const updateTaskProgress = (id: string, progress: number) => {
  return http.request<Result<void>>("put", `/api/v1/task/${id}/progress`, {
    params: { progress }
  });
};

/** 更新任务状态 */
export const updateTaskStatus = (id: string, status: string) => {
  return http.request<Result<void>>("put", `/api/v1/task/${id}/status`, {
    params: { status }
  });
};

/** 查询任务依赖关系 */
export const getTaskDependencies = (id: string) => {
  return http.request<Result<Record<string, any>[]>>(
    "get",
    `/api/v1/task/${id}/dependencies`
  );
};

/** 统计项目任务状态分布 */
export const getTaskStatusStats = (projectId: string) => {
  return http.request<Result<Record<string, any>[]>>(
    "get",
    "/api/v1/task/stats/status",
    { params: { projectId } }
  );
};

// ==================== 资源管理 API ====================

/** 资源实体 - 根据 OpenAPI 定义 */
export type Resource = {
  id?: string;
  resourceCode?: string;
  projectId?: string;
  resourceType?: string; // human-人力, material-物料, equipment-设备, software-软件, finance-资金, other-其他
  resourceName?: string;
  description?: string;
  specification?: string;
  unit?: string;
  planQuantity?: number;
  actualQuantity?: number;
  unitPrice?: number;
  currency?: string;
  supplier?: string;
  status?: string; // planned-计划中, requested-已申请, approved-已批准, procuring-采购中, arrived-已到货, in_use-使用中, completed-已完成
  planArriveDate?: string;
  actualArriveDate?: string;
  responsibleId?: string;
  responsibleName?: string;
  location?: string;
  tags?: string[];
  extraData?: Record<string, any>;
  createBy?: string;
  createTime?: string;
  updateBy?: string;
  updateTime?: string;
};

/** 资源更新请求 - 根据 OpenAPI 定义 */
export type ResourceUpdateRequest = {
  id: string;
  resourceType?: string;
  resourceName?: string;
  description?: string;
  specification?: string;
  unit?: string;
  planQuantity?: number;
  actualQuantity?: number;
  unitPrice?: number;
  currency?: string;
  supplier?: string;
  status?: string;
  planArriveDate?: string;
  actualArriveDate?: string;
  responsibleId?: string;
  responsibleName?: string;
  location?: string;
  tags?: string[];
  extraData?: Record<string, any>;
};

/** 资源查询参数 */
export type ResourceQueryParams = {
  pageNum?: number;
  pageSize?: number;
  projectId?: string;
  resourceType?: string;
  status?: string;
  keyword?: string;
};

/** 分页数据结构（资源列表用） */
export type PageResult<T> = {
  records: T[];
  total: number;
  size: number;
  current: number;
};

/** 分页查询资源列表 */
export const getResourceList = (params?: ResourceQueryParams) => {
  return http.request<Result<PageResult<Resource>>>(
    "get",
    "/api/v1/resource/list",
    { params }
  );
};

/** 根据ID查询资源详情 */
export const getResourceById = (id: string) => {
  return http.request<Result<Resource>>("get", `/api/v1/resource/${id}`);
};

/** 新增资源 */
export const createResource = (data: Resource) => {
  return http.request<Result<string>>("post", "/api/v1/resource", { data });
};

/** 修改资源 */
export const updateResource = (data: ResourceUpdateRequest) => {
  return http.request<Result<void>>("put", "/api/v1/resource", { data });
};

/** 删除资源 */
export const deleteResource = (id: string) => {
  return http.request<Result<void>>("delete", `/api/v1/resource/${id}`);
};

/** 更新资源状态 */
export const updateResourceStatus = (id: string, status: string) => {
  return http.request<Result<void>>("put", `/api/v1/resource/${id}/status`, {
    params: { status }
  });
};

/** 更新资源数量 */
export const updateResourceQuantity = (id: string, actualQuantity: string) => {
  return http.request<Result<void>>("put", `/api/v1/resource/${id}/quantity`, {
    params: { actualQuantity }
  });
};

/** 查询资源预算汇总 */
export const getResourceBudgetStats = (projectId: string) => {
  return http.request<Result<Record<string, any>[]>>(
    "get",
    "/api/v1/resource/stats/budget",
    { params: { projectId } }
  );
};

/** 查询即将到位的资源 */
export const getPendingArrivalResources = (
  projectId: string,
  days: number = 7
) => {
  return http.request<Result<Resource[]>>(
    "get",
    "/api/v1/resource/pending-arrival",
    { params: { projectId, days } }
  );
};

/** 查询待审批的资源申请 */
export const getPendingApprovalResources = (projectId?: string) => {
  return http.request<Result<Record<string, any>[]>>(
    "get",
    "/api/v1/resource/pending-approval",
    { params: { projectId } }
  );
};
