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

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

// ==================== 风险相关类型定义 ====================

/** 风险分类 */
export type RiskCategory =
  | "technical"
  | "schedule"
  | "cost"
  | "quality"
  | "resource"
  | "external"
  | "other";

/** 风险来源 */
export type RiskSource = "internal" | "external" | "manual";

/** 风险等级 */
export type RiskLevel = "critical" | "high" | "medium" | "low";

/** 风险状态 */
export type RiskStatus =
  | "identified"
  | "assigned"
  | "mitigating"
  | "resolved"
  | "closed";

/** 风险VO */
export type RiskVO = {
  id?: number;
  riskCode?: string;
  projectId?: number;
  projectName?: string;
  category?: RiskCategory;
  riskName?: string;
  description?: string;
  riskSource?: RiskSource;
  probability?: number;
  impact?: number;
  riskScore?: number;
  riskLevel?: RiskLevel;
  status?: RiskStatus;
  ownerId?: number;
  ownerName?: string;
  ownerAvatar?: string;
  workOrderCount?: number;
  mitigationPlan?: string;
  contingencyPlan?: string;
  triggerCondition?: string;
  discoverTime?: string;
  dueDate?: string;
  resolvedTime?: string;
  tags?: string[];
  createTime?: string;
  updateTime?: string;
};

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

/** 创建风险请求 */
export type CreateRiskRequest = {
  projectId?: number;
  category?: RiskCategory;
  riskName?: string;
  description?: string;
  riskSource?: RiskSource;
  probability?: number;
  impact?: number;
  ownerId?: number;
  mitigationPlan?: string;
  contingencyPlan?: string;
  triggerCondition?: string;
  dueDate?: string;
  tags?: string[];
};

/** 风险查询参数 */
export type RiskQueryParams = {
  projectId?: number | string;
  pageNum: number;
  pageSize: number;
  category?: string;
  riskLevel?: string;
  status?: string;
  keyword?: string;
};

/** 风险统计VO */
export type RiskStatisticsVO = {
  totalCount: number;
  identifiedCount: number;
  assignedCount: number;
  mitigatingCount: number;
  resolvedCount: number;
  closedCount: number;
  criticalCount: number;
  highCount: number;
  mediumCount: number;
  lowCount: number;
  categoryStats: Record<string, number | string>;
  levelStats: Record<string, number | string>;
  trendData: Record<string, number[]> | null;
  averageRiskScore: number;
  unresolvedHighCount: number;
};

// ==================== 工单相关类型定义 ====================

/** 工单类型 */
export type WorkOrderType =
  | "bug"
  | "feature"
  | "task"
  | "incident"
  | "risk_handle"
  | "other";

/** 工单优先级 */
export type WorkOrderPriority = "critical" | "high" | "medium" | "low";

/** 工单状态 */
export type WorkOrderStatus =
  | "pending"
  | "assigned"
  | "processing"
  | "resolved"
  | "closed"
  | "reopened";

/** 工单来源 */
export type WorkOrderSource = "web" | "mobile" | "api" | "system" | "risk";

/** 工单VO */
export type WorkOrderVO = {
  id?: number;
  orderCode?: string;
  orderType?: WorkOrderType;
  projectId?: number;
  projectName?: string;
  riskId?: number;
  riskName?: string;
  title?: string;
  description?: string;
  creatorId?: number;
  creatorName?: string;
  handlerId?: number;
  handlerName?: string;
  handlerAvatar?: string;
  handlerGroupId?: number;
  priority?: WorkOrderPriority;
  status?: WorkOrderStatus;
  source?: WorkOrderSource;
  deadline?: string;
  assignedTime?: string;
  firstResponseTime?: string;
  resolvedTime?: string;
  closedTime?: string;
  satisfactionScore?: number;
  isOverdue?: boolean;
  tags?: string[];
  createTime?: string;
  updateTime?: string;
};

/** 创建工单请求 */
export type CreateWorkOrderRequest = {
  projectId?: number;
  riskId?: number;
  orderType?: WorkOrderType;
  title?: string;
  description?: string;
  priority?: WorkOrderPriority;
  handlerId?: number;
  handlerGroupId?: number;
  deadline?: string;
  source?: WorkOrderSource;
  tags?: string[];
};

/** 工单查询参数 */
export type WorkOrderQueryParams = {
  projectId?: number;
  pageNum: number;
  pageSize: number;
  orderType?: string;
  status?: string;
  priority?: string;
  keyword?: string;
};

/** 我的工单查询参数 */
export type MyWorkOrderQueryParams = {
  pageNum: number;
  pageSize: number;
  status?: string;
  orderType?: string;
};

/** 处理工单请求 */
export type ProcessWorkOrderRequest = {
  workOrderId?: number;
  status?: "processing" | "resolved" | "closed" | "reopened";
  satisfactionScore?: number;
};

/** 工单统计VO */
export type WorkOrderStatisticsVO = {
  totalCount: number;
  pendingCount: number;
  assignedCount: number;
  processingCount: number;
  completedCount: number;
  closedCount: number;
  rejectedCount: number;
  overdueCount: number;
  aboutToExpireCount: number;
  typeStats: Record<string, number>;
  priorityStats: Record<string, number>;
};

// ==================== 风险API ====================

/** 创建风险评估 */
export const createRisk = (data: CreateRiskRequest) => {
  return http.request<Result<number>>("post", "/api/v1/risk", { data });
};

/** 更新风险 */
export const updateRisk = (riskId: number, data: CreateRiskRequest) => {
  return http.request<Result<boolean>>("put", `/api/v1/risk/${riskId}`, {
    data
  });
};

/** 删除风险 */
export const deleteRisk = (riskId: number) => {
  return http.request<Result<boolean>>("delete", `/api/v1/risk/${riskId}`);
};

/** 获取风险详情 */
export const getRiskDetail = (riskId: number) => {
  return http.request<Result<RiskVO>>("get", `/api/v1/risk/${riskId}`);
};

/** 分页查询风险列表 */
export const getRiskList = (params: RiskQueryParams) => {
  return http.request<Result<TableDataInfo<RiskVO>>>(
    "get",
    "/api/v1/risk/list",
    { params }
  );
};

/** 获取风险统计信息 */
export const getRiskStatistics = (projectId?: number) => {
  return http.request<Result<RiskStatisticsVO>>(
    "get",
    "/api/v1/risk/statistics",
    { params: projectId ? { projectId } : undefined }
  );
};

/** 为风险分配工单 */
export const assignWorkOrderToRisk = (
  riskId: number,
  data: CreateWorkOrderRequest
) => {
  return http.request<Result<number>>(
    "post",
    `/api/v1/risk/${riskId}/assign-workorder`,
    { data }
  );
};

/** 批量更新风险状态 */
export const batchUpdateRiskStatus = (riskIds: number[], status: string) => {
  return http.request<Result<boolean>>("put", "/api/v1/risk/batch-status", {
    params: { status },
    data: riskIds
  });
};

// ==================== 工单API ====================

/** 创建工单 */
export const createWorkOrder = (data: CreateWorkOrderRequest) => {
  return http.request<Result<number>>("post", "/api/v1/workorder", { data });
};

/** 更新工单 */
export const updateWorkOrder = (
  workOrderId: number,
  data: CreateWorkOrderRequest
) => {
  return http.request<Result<boolean>>(
    "put",
    `/api/v1/workorder/${workOrderId}`,
    { data }
  );
};

/** 删除工单 */
export const deleteWorkOrder = (workOrderId: number) => {
  return http.request<Result<boolean>>(
    "delete",
    `/api/v1/workorder/${workOrderId}`
  );
};

/** 获取工单详情 */
export const getWorkOrderDetail = (workOrderId: number) => {
  return http.request<Result<WorkOrderVO>>(
    "get",
    `/api/v1/workorder/${workOrderId}`
  );
};

/** 分页查询工单列表 */
export const getWorkOrderList = (params: WorkOrderQueryParams) => {
  return http.request<Result<TableDataInfo<WorkOrderVO>>>(
    "get",
    "/api/v1/workorder/list",
    { params }
  );
};

/** 获取我的工单列表 */
export const getMyWorkOrderList = (params: MyWorkOrderQueryParams) => {
  return http.request<Result<TableDataInfo<WorkOrderVO>>>(
    "get",
    "/api/v1/workorder/my",
    { params }
  );
};

/** 处理工单 */
export const processWorkOrder = (data: ProcessWorkOrderRequest) => {
  return http.request<Result<boolean>>("post", "/api/v1/workorder/process", {
    data
  });
};

/** 分配工单给处理人 */
export const assignWorkOrder = (workOrderId: number, handlerId: number) => {
  return http.request<Result<boolean>>(
    "put",
    `/api/v1/workorder/${workOrderId}/assign`,
    { params: { handlerId } }
  );
};

/** 获取工单统计信息 */
export const getWorkOrderStatistics = (projectId?: number) => {
  return http.request<Result<WorkOrderStatisticsVO>>(
    "get",
    "/api/v1/workorder/statistics",
    { params: projectId ? { projectId } : undefined }
  );
};

/** 获取我的工单统计信息 */
export const getMyWorkOrderStatistics = () => {
  return http.request<Result<WorkOrderStatisticsVO>>(
    "get",
    "/api/v1/workorder/my/statistics"
  );
};

// ==================== SSE风险评估API ====================

/** 风险评估任务VO */
export type RiskAssessmentTaskVO = {
  taskId: string;
  userId?: number;
  status: string; // pending, processing, completed, failed
  statusDesc: string;
  progress: number;
  progressMessage: string;
  projectId: number;
  projectName: string;
  createTime: string;
  startTime?: string;
  completeTime?: string;
  result?: RiskAssessmentResultVO;
  errorMessage?: string;
};

/** 风险评估结果VO */
export type RiskAssessmentResultVO = {
  projectId: number;
  projectName: string;
  overallRiskLevel: string;
  overallRiskScore: number;
  assessmentSummary: string;
  riskAreas: string[];
  identifiedRisks: Array<{
    riskName: string;
    category: string;
    probability: number;
    impact: number;
    mitigationPlan: string;
  }>;
  recommendations: string[];
};

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

/** 提交异步风险评估任务 */
export const submitRiskAssessment = (projectId: number | string) => {
  return http.request<Result<string>>(
    "post",
    `/api/v1/risk/sse/assess/${projectId}`
  );
};

/** 查询我的风险评估任务列表 */
export const getMyRiskAssessmentTasks = () => {
  return http.request<Result<RiskAssessmentTaskVO[]>>(
    "get",
    "/api/v1/risk/sse/my-tasks"
  );
};

/** 查询任务统计信息 */
export const getMyRiskTaskStats = () => {
  return http.request<Result<RiskTaskStats>>(
    "get",
    "/api/v1/risk/sse/my-tasks/stats"
  );
};

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

/** 获取任务评估结果 */
export const getRiskTaskResult = (taskId: string) => {
  return http.request<Result<RiskAssessmentResultVO>>(
    "get",
    `/api/v1/risk/sse/task/${taskId}/result`
  );
};
