/**
 * 流程设计器类型定义
 * 基于审批引擎架构设计
 */

// 节点类型枚举
export type ProcessNodeType =
  | 'START'             // 开始节点
  | 'END'               // 结束节点
  | 'USER_TASK'         // 用户任务（审批节点）
  | 'EXECUTOR'          // 执行人节点
  | 'SERVICE_TASK'      // 服务任务
  | 'EXCLUSIVE_GATEWAY' // 排他网关
  | 'PARALLEL_GATEWAY'  // 并行网关
  | 'CC'                // 抄送节点

// 审批模式
export type ApprovalMode = 
  | 'SINGLE'      // 单人审批
  | 'AND'         // 会签（所有人通过）
  | 'OR'          // 或签（任一人通过）
  | 'SEQUENTIAL'; // 顺序审批

// 审批人类型
export type ApproverType =
  | 'FIXED_USER'       // 指定人员
  | 'ROLE'             // 指定角色
  | 'DEPARTMENT'       // 部门负责人
  | 'DEPT_MANAGER'     // 部门主管
  | 'INITIATOR_MANAGER' // 发起人上级
  | 'MANAGER_CHAIN'    // 连续上级审批
  | 'FORM_FIELD'       // 表单字段
  | 'CUSTOM';          // 自定义

// 用户信息类型
export interface UserInfo {
  id: string;
  displayName: string;
  username?: string;
  email?: string;
  avatar?: string;
  department?: string;
}

// 节点配置
export interface ProcessNodeConfig {
  // 审批人配置
  approverType?: ApproverType;
  approvers?: string[];           // 审批人 ID 列表（兼容旧版）
  approverDetails?: UserInfo[];   // 审批人完整信息（新版）
  
  // 发起人上级层级配置（用于 INITIATOR_MANAGER 类型）
  managerLevel?: number;          // 上级层级：1=直属上级, 2=二级上级, 3=...
  
  approverConfig?: {
    users?: string[];           // 指定用户 ID 列表
    roles?: string[];           // 角色列表
    departmentLevel?: number;   // 部门层级
    formField?: string;         // 表单字段
    expression?: string;        // 自定义表达式
  };
  
  // 审批模式
  approvalMode?: ApprovalMode;
  
  // 连续上级审批配置
  chainConfig?: {
    stopCondition?: 'deptHead' | 'orgHead' | string;
    includeTerminator?: boolean;
    skipSelf?: boolean;
    autoApprove?: 'none' | 'sameApprover' | 'initiator' | 'both';
    maxLevels?: number;
  };
  
  // 超时配置
  timeout?: {
    hours: number;
    remindBeforeHours?: number;
    action?: 'remind' | 'escalate' | 'auto_approve' | 'auto_reject';
  };
  
  // 条件表达式（用于网关）
  condition?: string;
  conditionLabel?: string;
  
  // 条件分支配置（用于排他网关的多条件分支）
  conditions?: Array<{
    id: string;
    name: string;
    priority: number;
    condition?: string;
    isDefault?: boolean;
  }>;
  
  // 抄送配置
  ccConfig?: {
    users?: string[];
    roles?: string[];
  };
  
  // 表单权限
  editableFields?: string[];
  requiredFields?: string[];
  hiddenFields?: string[];
  
  // 允许的操作
  allowedActions?: string[];
}

// 流程节点
export interface ProcessNode {
  id: string;
  type: ProcessNodeType;
  name: string;
  description?: string;
  position: { x: number; y: number };
  config: ProcessNodeConfig;
}

// 流程连线
export interface ProcessEdge {
  id: string;
  source: string;
  target: string;
  sourceHandle?: string;
  targetHandle?: string;
  label?: string;
  condition?: string;
  priority?: number;
}

// 流程模型
export interface ProcessModel {
  nodes: ProcessNode[];
  edges: ProcessEdge[];
}

// 流程设置
export interface ProcessSettings {
  // 发起人撤回配置
  withdraw?: {
    allowWithdraw: boolean;
    withdrawBeforeNode?: string[];
    withdrawReason: boolean;
  };
  
  // 审批人撤回配置
  approverWithdraw?: {
    enabled: boolean;
    timeLimit: number;
    requireReason: boolean;
    notifyInitiator: boolean;
  };
  
  // 默认优先级
  defaultPriority?: number;
  
  // 循环保护
  maxNodeExecutions?: number;
  maxTotalNodeExecutions?: number;
  maxReturnCount?: number;
}

// 节点类型配置（用于面板展示）
export interface ProcessNodeTypeConfig {
  type: ProcessNodeType;
  label: string;
  icon: string;
  color: string;
  description: string;
  category: 'control' | 'task' | 'gateway';
  defaultConfig: ProcessNodeConfig;
}

// 节点类型配置列表
// 注意：label 和 description 应该通过 getNodeTypeLabel() 和 getNodeTypeDescription() 获取翻译
export const PROCESS_NODE_TYPES: ProcessNodeTypeConfig[] = [
  // 控制节点
  {
    type: 'START',
    label: 'Start', // Fallback, use translation in components
    icon: 'Play',
    color: '#22c55e',
    description: 'Process start node', // Fallback
    category: 'control',
    defaultConfig: {},
  },
  {
    type: 'END',
    label: 'End',
    icon: 'Square',
    color: '#ef4444',
    description: 'Process end node',
    category: 'control',
    defaultConfig: {},
  },
  
  // 任务节点
  {
    type: 'USER_TASK',
    label: 'Approval Node',
    icon: 'UserCheck',
    color: '#3b82f6',
    description: 'Node requiring personnel approval',
    category: 'task',
    defaultConfig: {
      approverType: 'INITIATOR_MANAGER',
      approvalMode: 'SINGLE',
    },
  },
  {
    type: 'CC',
    label: 'CC Node',
    icon: 'Send',
    color: '#8b5cf6',
    description: 'Send CC notification',
    category: 'task',
    defaultConfig: {},
  },
  
  // 网关节点
  {
    type: 'EXCLUSIVE_GATEWAY',
    label: 'Conditional Branch',
    icon: 'GitBranch',
    color: '#f59e0b',
    description: 'Choose branch based on condition',
    category: 'gateway',
    defaultConfig: {},
  },
  {
    type: 'PARALLEL_GATEWAY',
    label: 'Parallel Branch',
    icon: 'GitMerge',
    color: '#06b6d4',
    description: 'Execute multiple branches in parallel',
    category: 'gateway',
    defaultConfig: {},
  },
];

// 审批人类型配置
// 注意：label 和 description 应该通过 getApproverTypeLabel() 和 getApproverTypeDescription() 获取翻译
export const APPROVER_TYPES: Array<{
  value: ApproverType;
  label: string;
  description: string;
}> = [
  {
    value: 'INITIATOR_MANAGER',
    label: 'Direct Manager', // Fallback, use translation in components
    description: 'Initiator\'s direct manager',
  },
  {
    value: 'MANAGER_CHAIN',
    label: 'Manager Chain',
    description: 'Sequential approval up to department head',
  },
  {
    value: 'FIXED_USER',
    label: 'Specified User',
    description: 'Fixed approver',
  },
  {
    value: 'ROLE',
    label: 'Specified Role',
    description: 'Users with specific role',
  },
  {
    value: 'DEPARTMENT',
    label: 'Department Head',
    description: 'Head of specified department',
  },
  {
    value: 'FORM_FIELD',
    label: 'Form Field',
    description: 'Get approver from form field',
  },
];

// 审批模式配置
// 注意：label 和 description 应该通过 getApprovalModeLabel() 和 getApprovalModeDescription() 获取翻译
export const APPROVAL_MODES: Array<{
  value: ApprovalMode;
  label: string;
  description: string;
}> = [
  {
    value: 'SINGLE',
    label: 'Single Approval', // Fallback, use translation in components
    description: 'Only one person needs to approve',
  },
  {
    value: 'AND',
    label: 'Countersign',
    description: 'All approvers must agree',
  },
  {
    value: 'OR',
    label: 'OR Sign',
    description: 'Any one approver can agree',
  },
  {
    value: 'SEQUENTIAL',
    label: 'Sequential Approval',
    description: 'Approve in sequence',
  },
];

// 生成唯一 ID
export function generateNodeId(): string {
  return `node_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
}

// 生成唯一边 ID
export function generateEdgeId(): string {
  return `edge_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
}

// 创建默认流程模型
export function createDefaultProcessModel(): ProcessModel {
  const startId = generateNodeId();
  const approvalId = generateNodeId();
  const endId = generateNodeId();
  
  return {
    nodes: [
      {
        id: startId,
        type: 'START',
        name: 'Start', // Use translation in components
        position: { x: 250, y: 50 },
        config: {},
      },
      {
        id: approvalId,
        type: 'USER_TASK',
        name: 'Manager Approval',
        position: { x: 250, y: 150 },
        config: {
          approverType: 'INITIATOR_MANAGER',
          approvalMode: 'SINGLE',
        },
      },
      {
        id: endId,
        type: 'END',
        name: 'End',
        position: { x: 250, y: 250 },
        config: {},
      },
    ],
    edges: [
      {
        id: generateEdgeId(),
        source: startId,
        target: approvalId,
      },
      {
        id: generateEdgeId(),
        source: approvalId,
        target: endId,
      },
    ],
  };
}

// 验证流程模型
export function validateProcessModel(model: ProcessModel): { valid: boolean; errors: string[] } {
  const errors: string[] = [];
  
  // 检查开始节点
  const startNodes = model.nodes.filter(n => n.type === 'START');
  if (startNodes.length === 0) {
    errors.push('Process must have one start node'); // Use translation in components
  } else if (startNodes.length > 1) {
    errors.push('Process can only have one start node');
  }
  
  // 检查结束节点
  const endNodes = model.nodes.filter(n => n.type === 'END');
  if (endNodes.length === 0) {
    errors.push('Process must have one end node');
  }
  
  // 检查审批节点配置
  const userTasks = model.nodes.filter(n => n.type === 'USER_TASK');
  for (const task of userTasks) {
    if (!task.config.approverType) {
      errors.push(`Approval node "${task.name}" has no approver configured`); // Use translation in components
    }
  }
  
  // 检查节点连通性
  const nodeIds = new Set(model.nodes.map(n => n.id));
  for (const edge of model.edges) {
    if (!nodeIds.has(edge.source)) {
      errors.push(`Edge source node ${edge.source} does not exist`);
    }
    if (!nodeIds.has(edge.target)) {
      errors.push(`Edge target node ${edge.target} does not exist`);
    }
  }
  
  return {
    valid: errors.length === 0,
    errors,
  };
}
