import type { DevelopmentLanguageTypeEnum } from '@/pages/Deploy/Application/List/types';

export interface Approver {
  userId: number;
  username: string;
  realName: string;
}

/**
 * 部署状态类型
 */
export type DeployStatus = 
  | 'CREATED'           // 已创建
  | 'PENDING_APPROVAL'  // 待审批
  | 'RUNNING'           // 运行中
  | 'SUCCESS'           // 部署成功
  | 'FAILED'            // 部署失败
  | 'PARTIAL_SUCCESS'   // 部分成功（工作流完成但存在失败的节点）
  | 'REJECTED'          // 审批被拒绝（终态）
  | 'CANCELLED'         // 已取消（终态）
  | 'TERMINATED';       // 已终止（终态）

export interface DeployStatistics {
  totalCount: number;
  successCount: number;
  failedCount: number;
  runningCount: number;
  lastDeployTime?: string;
  lastDeployBy?: string;
  latestStatus?: DeployStatus;
}

export interface DeployRecord {
  id: number;
  status: DeployStatus;
  deployBy: string;
  startTime: string;
  endTime?: string;
  deployRemark?: string;
  duration?: number; // 持续时间（毫秒）
}

export type BuildType = 'JENKINS' | 'NATIVE';

export interface ApplicationConfig {
  teamApplicationId: number;
  applicationId: number;
  applicationCode: string;
  applicationName: string;
  applicationDesc?: string;
  language?: DevelopmentLanguageTypeEnum; // 开发语言
  buildType?: BuildType;                  // 构建类型
  deploySystemId?: number;
  deploySystemName?: string;
  deployJob?: string;
  workflowDefinitionId?: number;
  workflowDefinitionFormId?: number;
  workflowDefinitionName?: string;
  workflowDefinitionKey?: string;
  // 源Git配置
  sourceGitSystemId?: number;
  sourceGitSystemName?: string;
  sourceGitProjectId?: number;
  sourceGitProjectName?: string;
  sourceBranch?: string;
  // 目标Git配置
  targetGitSystemId?: number;
  targetGitSystemName?: string;
  targetGitProjectId?: number;
  targetGitProjectName?: string;
  targetBranch?: string;
  deployStatistics?: DeployStatistics;
  isDeploying?: boolean;
  recentDeployRecords?: DeployRecord[];
}

export interface NotificationConfig {
  notificationChannelId: number;
  preApprovalNotificationEnabled: boolean;
  preApprovalNotificationTemplateId: number;
  buildNotificationEnabled: boolean;
  buildNotificationTemplateId: number;
  buildFailureFileEnabled: boolean;
}

export interface DeployEnvironment {
    environmentId: number;
  environmentCode: string;
  environmentName: string;
  environmentDesc?: string;
  enabled: boolean;
  sort: number;
  requiresApproval: boolean;
  approvers: Approver[];
  notificationConfig?: NotificationConfig;
  requireCodeReview: boolean;
  canDeploy: boolean;
  canApprove: boolean;
  applications: ApplicationConfig[];
}

export interface TeamMember {
  userId: number;
  username: string;
  realName: string;
  roleInTeam: string;
}

export interface DeployTeam {
  teamId: number;
  teamCode: string;
  teamName: string;
  description?: string;
  ownerId: number;
  ownerName: string;
  members: TeamMember[];
  environments: DeployEnvironment[];
}

export type DeployEnvironmentsResponse = DeployTeam[];

export interface StartDeploymentRequest {
  teamApplicationId: number;
  workflowDefinitionKey: string;
  formData?: Record<string, any>;
}

export interface StartDeploymentResponse {
  instanceId: string;
  processDefinitionId: string;
  businessKey: string;
  processKey: string;
  startTime?: string;
}

/**
 * 后端返回的待审批任务原始结构（嵌套对象）
 */
export interface PendingApprovalTaskResponse {
  approvalTask: {
    taskId: string;
    taskName: string;
    taskDescription?: string;
    processInstanceId: string;
    processDefinitionId: string;
    assignee: string | null;
    createTime: string;
    dueDate?: string | null;
    pendingDuration?: number;
    approvalTitle?: string;
    approvalContent?: string;
    approvalMode: 'SINGLE' | 'MULTI' | 'OR' | 'ANY';
    allowDelegate?: boolean;
    allowAddSign?: boolean;
    requireComment?: boolean;
  };
  deployRecord: {
    id: number;
    businessKey: string;
    remark?: string;
    startTime: string;
  };
  team: {
    id: number;
    name: string;
  };
  application: {
    id: number;
    code: string;
    name: string;
  };
  environment: {
    id: number;
    code: string;
    name: string;
  };
  deployUser: {
    username: string;
    nickname: string;
    email: string;
    phone: string;
    departmentName: string;
  };
}

/**
 * 待审批任务（前端使用的扁平结构）
 */
export interface PendingApprovalTask {
  // ============ 审批任务基本信息 ============
  taskId: string;
  taskName: string;
  taskDescription?: string;
  processInstanceId: string;
  processDefinitionId: string;
  assignee: string;
  createTime: string;
  dueDate?: string;
  approvalTitle?: string;
  approvalContent?: string;
  approvalMode: 'SINGLE' | 'MULTI' | 'OR' | 'ANY';
  allowDelegate?: boolean;
  allowAddSign?: boolean;
  requireComment?: boolean;

  // ============ 部署业务上下文信息 ============
  deployRecordId: number;
  businessKey: string;
  teamId: number;
  teamName: string;
  applicationId: number;
  applicationCode: string;
  applicationName: string;
  environmentId: number;
  environmentCode: string;
  environmentName: string;
  deployBy: string;
  deployRemark?: string;
  deployStartTime: string;
  pendingDuration?: number; // 待审批时长（毫秒）
}

/**
 * 审批结果枚举
 */
export enum ApprovalResult {
  APPROVED = 'APPROVED',  // 通过
  REJECTED = 'REJECTED',  // 拒绝
}

/**
 * 完成审批请求
 */
export interface CompleteApprovalRequest {
  taskId: string;          // Flowable任务ID
  result: ApprovalResult;  // 审批结果
  comment?: string;        // 审批意见
}

/**
 * 工作流节点实例
 */
export interface WorkflowNodeInstance {
  id: number | null;
  nodeId: string;
  nodeName: string;
  nodeType: string;
  status: string; // NOT_STARTED/RUNNING/COMPLETED/FAILED/SUSPENDED/TERMINATED
  startTime?: string | null;
  endTime?: string | null;
  duration?: number | null; // 执行时长（毫秒）
  errorMessage?: string | null;
  outputs?: Record<string, any> | null;
}

/**
 * 工作流定义图节点
 */
export interface WorkflowDefinitionGraphNode {
  id: string;
  nodeCode?: string;
  nodeType: string;
  nodeName: string;
  position: {
    x: number;
    y: number;
  };
  configs?: Record<string, any>;
  inputMapping?: Record<string, any>;
  outputs?: any[];
}

/**
 * 工作流定义图边
 */
export interface WorkflowDefinitionGraphEdge {
  id: string;
  from: string;
  to: string;
  name?: string;
  config?: Record<string, any>;
}

/**
 * 工作流定义图
 */
export interface WorkflowDefinitionGraph {
  nodes: WorkflowDefinitionGraphNode[];
  edges: WorkflowDefinitionGraphEdge[];
}

/**
 * 部署流程图数据
 */
export interface DeployRecordFlowGraph {
  // 部署基本信息
  deployRecordId: number;
  businessKey: string;
  deployStatus: DeployStatus;
  deployBy: string;
  deployRemark?: string | null;
  deployStartTime: string;
  deployEndTime?: string | null;
  deployDuration?: number | null; // 毫秒
  
  // 业务信息
  applicationName: string;
  applicationCode: string;
  environmentName: string;
  teamName: string;
  
  // 工作流信息
  workflowInstanceId: number;
  processInstanceId: string;
  workflowStatus: string;
  workflowStartTime: string;
  workflowEndTime?: string | null;
  workflowDuration?: number | null; // 毫秒
  
  // 统计信息
  totalNodeCount: number;
  executedNodeCount: number;
  successNodeCount: number;
  failedNodeCount: number;
  runningNodeCount: number;
  
  // 流程图数据
  graph: WorkflowDefinitionGraph;
  nodeInstances: WorkflowNodeInstance[];
}

/**
 * 日志级别
 */
export type LogLevel = 'INFO' | 'WARN' | 'ERROR';

/**
 * 日志条目
 */
export interface LogEntry {
  sequenceId: number;
  timestamp: string;
  level: LogLevel;
  message: string;
}

/**
 * 部署节点日志响应
 */
export interface DeployNodeLogDTO {
  expired: boolean;
  logs: LogEntry[];
}
