/**
 * 表单管理聚合 API Client
 * 基于 form-management API 文档 - 28 个接口
 * 
 * 调用规范：前端只调用 /form-management/*，不直接调用引擎层 API
 */

import apiClient from '@/lib/api-client';

// TODO: 修复类型导入路径 - 原路径不存在
// import type {
//   ProcessNodeType,
//   ProcessNode,
//   ProcessNodeConfig,
//   ProcessEdge,
//   ProcessModel,
//   ApprovalMode,
//   ApproverType,
// } from '@features/approval/components/designer/types';

// 临时类型定义
export type ProcessNodeType = string;
export type ProcessNode = any;
export type ProcessNodeConfig = any;
export type ProcessEdge = any;
export type ProcessModel = any;
export type ApprovalMode = string;
export type ApproverType = string;

// ============================================
// 类型定义
// ============================================

/** 表单定义状态 */
export type FormDefinitionStatus = 'DRAFT' | 'PUBLISHED' | 'DISABLED' | 'ARCHIVED';

/** 版本状态（简化流程：审核通过 = 发布） */
export type VersionStatus = 'DRAFT' | 'PENDING_REVIEW' | 'PUBLISHED' | 'REJECTED' | 'DEPRECATED';

/** 快照状态 */
export type SnapshotStatus = 'DRAFT' | 'PENDING' | 'ACTIVE' | 'ARCHIVED' | 'SUSPENDED';

/** 实例状态 */
export type InstanceStatus = 'DRAFT' | 'SUBMITTED' | 'PENDING_APPROVAL' | 'APPROVED' | 'REJECTED' | 'WITHDRAWN' | 'CANCELLED';

/** 支持的区域 */
export type RegionId = 'CN' | 'US' | 'ME';

/** 表单定义 */
export interface FormDefinition {
  id: string;
  key: string;
  name: string;
  description?: string;
  category?: string;
  icon?: string;
  status: FormDefinitionStatus;
  requiresApproval?: boolean; // 是否需要审批
  approvalProcessKey?: string; // 审批流程 Key
  organizationId?: string | null; // 归属组织 ID（顶层部门）
  organization?: {
    id: string;
    name: string;
    code: string;
  } | null;
  activeSnapshotId?: string;
  currentVersion?: number;
  templateId?: string;
  createdBy: string;
  createdAt: string;
  updatedAt: string;
}

/** 表单版本 */
export interface FormVersion {
  id: string;
  formDefinitionId: string;
  version: number;
  versionName?: string;
  status: VersionStatus;
  schema: Record<string, unknown>;
  uiSchema?: Record<string, unknown>;
  createdBy: string;
  createdAt: string;
  updatedAt: string;
  reviewedBy?: string;
  reviewedAt?: string;
  reviewComment?: string;
}

/** 流程版本 */
export interface ProcessVersion {
  id: string;
  processDefinitionId: string;
  version: number;
  versionName?: string;
  status: VersionStatus;
  model: ProcessModel;
  createdBy: string;
  createdAt: string;
  updatedAt: string;
}

// ProcessModel, ProcessNode, ProcessNodeConfig, ProcessEdge 类型已从 designer/types 导入

/** 发布快照 */
export interface ReleaseSnapshot {
  id: string;
  formDefinitionId: string;
  formVersionId: string;
  processDefinitionId: string;
  processVersionId: string;
  status: SnapshotStatus;
  releaseNote?: string;
  publishedAt?: string;
  publishedBy?: string;
  archivedAt?: string;
  reviewedAt?: string;
  reviewedBy?: string;
  reviewComment?: string;
  createdAt: string;
  updatedAt: string;
  // 关联数据
  formVersion?: FormVersion;
  processVersion?: ProcessVersion;
}

/** 表单实例 */
export interface FormInstance {
  id: string;
  regionId?: string; // 实例提交时的区域（保留，用于记录环境）
  snapshotId: string;
  formDefinitionId: string;
  formVersionId: string;
  processInstanceId?: string;
  approvalInstanceId?: string;
  approvalStatus?: string;
  approvalStartTime?: string;
  approvalEndTime?: string;
  formData?: Record<string, unknown>;
  data?: Record<string, unknown>;
  businessKey?: string;
  status: InstanceStatus;
  submittedBy?: string;
  createdBy?: string;
  submittedAt?: string;
  createdAt: string;
  updatedAt: string;
  // 扩展字段
  form?: {
    id: string;
    key: string;
    name: string;
    category?: string;
  };
  definition?: {
    id: string;
    key: string;
    name: string;
    category?: string;
  };
  version?: {
    id: string;
    version: number;
    schema?: Record<string, unknown>;
    uiSchema?: Record<string, unknown>;
  };
}

/** 分页响应 */
export interface PaginatedResponse<T> {
  items: T[];
  total: number;
  page: number;
  limit: number;
  totalPages: number;
  hasNext: boolean;
  hasPrev: boolean;
}

/** 字段访问权限 */
export interface FieldAccess {
  editable: boolean;
  required: boolean;
  hidden: boolean;
}

/** 版本差异 */
export interface VersionDiff {
  formDefinitionId: string;
  comparison: {
    from: { version: number; versionName?: string; snapshotId?: string };
    to: { version: number; versionName?: string; snapshotId?: string };
  };
  formDiff: {
    schema: DiffResult;
    uiSchema: DiffResult;
  };
  processDiff: {
    nodes: DiffResult;
    edges: DiffResult;
  };
  summary: {
    formFieldsAdded: number;
    formFieldsRemoved: number;
    formFieldsModified: number;
    processNodesAdded: number;
    processNodesRemoved: number;
    processEdgesChanged: number;
  };
}

interface DiffResult {
  added: Array<{ path: string; value: unknown }>;
  removed: Array<{ path: string; value: unknown }>;
  modified: Array<{ path: string; oldValue: unknown; newValue: unknown }>;
}

// ============================================
// API 请求类型
// ============================================

/** 创建表单定义请求 */
export interface CreateFormDefinitionDto {
  key: string;
  name: string;
  description?: string;
  category?: string;
  organizationId?: string; // 归属组织 ID
  templateId?: string;
  requiresApproval?: boolean;
}

/** 更新表单定义请求 */
export interface UpdateFormDefinitionDto {
  name?: string;
  description?: string;
  category?: string;
  icon?: string;
}

/** 查询表单定义请求 */
export interface QueryFormDefinitionsDto {
  page?: number;
  limit?: number;
  status?: FormDefinitionStatus;
  category?: string;
  keyword?: string;
  organizationId?: string; // 组织筛选
  forUse?: boolean;
}

/** 保存设计请求 */
export interface SaveDesignDto {
  formDesign?: {
    schema: Record<string, unknown>;
    uiSchema?: Record<string, unknown>;
  };
  processDesign?: ProcessModel;
}

/** 提交审核请求 */
export interface SubmitReviewDto {
  comment?: string;
}

/** 审核请求 */
export interface ReviewDto {
  action: 'APPROVE' | 'REJECT';
  comment?: string;
}

/** 发布请求 */
export interface PublishDto {
  releaseNote?: string;
}

/** 创建实例请求 */
export interface CreateInstanceDto {
  formDefinitionId: string;
  formData: Record<string, unknown>;
  departmentId?: string;
}

/** 创建实例响应 */
export interface CreateInstanceResponse {
  formInstance: {
    id: string;
    snapshotId: string;
    formDefinitionId: string;
    formVersionId: string;
    regionId: string;
    status: string;
    formData: Record<string, unknown>;
  };
  processInstance: {
    id: string;
    processDefinitionId: string;
    processVersionId: string;
    status: string;
    currentNode: string;
  };
  createdAt: string;
}

// ============================================
// 1. 表单定义管理 API
// ============================================

const BASE_URL = '/form-management';

/**
 * 获取表单定义列表
 */
export async function getFormDefinitions(
  params?: QueryFormDefinitionsDto
): Promise<PaginatedResponse<FormDefinition>> {
  return apiClient.get(`${BASE_URL}/definitions`, { params });
}

/**
 * 创建表单定义
 */
export async function createFormDefinition(
  data: CreateFormDefinitionDto
): Promise<FormDefinition> {
  return apiClient.post(`${BASE_URL}/definitions`, data);
}

/**
 * 获取表单定义详情（通过ID）
 */
export async function getFormDefinition(id: string): Promise<FormDefinition> {
  return apiClient.get(`${BASE_URL}/definitions/${id}`);
}

/**
 * 获取表单定义详情（通过Key）
 * 用于用户填写表单时根据formKey查找表单定义
 */
export async function getFormDefinitionByKey(key: string): Promise<FormDefinition> {
  // 通过 key 查询，返回第一个匹配的表单
  // forUse: true 表示用于提交表单，跳过创建者权限过滤
  const response = await getFormDefinitions({ keyword: key, limit: 1, forUse: true });
  
  if (response.items.length === 0) {
    throw new Error(`Form with key "${key}" not found`);
  }
  
  return response.items[0];
}

/**
 * 获取表单实例详情
 */
export async function getFormInstance(instanceId: string): Promise<any> {
  return apiClient.get(`${BASE_URL}/instances/${instanceId}`);
}

/**
 * 更新表单定义
 */
export async function updateFormDefinition(
  id: string,
  data: UpdateFormDefinitionDto
): Promise<FormDefinition> {
  return apiClient.patch(`${BASE_URL}/definitions/${id}`, data);
}

/**
 * 删除表单定义
 */
export async function deleteFormDefinition(id: string): Promise<void> {
  return apiClient.delete(`${BASE_URL}/definitions/${id}`);
}

/**
 * 归档表单
 */
export async function archiveFormDefinition(id: string): Promise<FormDefinition> {
  return apiClient.post(`${BASE_URL}/definitions/${id}/archive`);
}

/**
 * 禁用表单
 */
export async function disableFormDefinition(id: string): Promise<FormDefinition> {
  return apiClient.post(`${BASE_URL}/definitions/${id}/disable`);
}

/**
 * 启用表单
 */
export async function enableFormDefinition(id: string): Promise<FormDefinition> {
  return apiClient.post(`${BASE_URL}/definitions/${id}/enable`);
}

// ============================================
// 2. 设计器 API
// ============================================

/**
 * 获取设计数据
 */
export async function getDesignData(id: string): Promise<{
  formDefinition: FormDefinition;
  formVersion: FormVersion;
  processVersion: ProcessVersion;
}> {
  return apiClient.get(`${BASE_URL}/definitions/${id}/design`);
}

/**
 * 保存表单设计
 */
export async function saveFormDesign(
  id: string,
  data: { schema: Record<string, unknown>; uiSchema?: Record<string, unknown> }
): Promise<{ formVersionId: string; savedAt: string }> {
  return apiClient.put(`${BASE_URL}/definitions/${id}/form-design`, data);
}

/**
 * 保存流程设计
 */
export async function saveProcessDesign(
  id: string,
  data: ProcessModel
): Promise<{ processVersionId: string; savedAt: string }> {
  return apiClient.put(`${BASE_URL}/definitions/${id}/process-design`, data);
}

/**
 * 一次性保存全部设计
 */
export async function saveDesign(
  id: string,
  data: SaveDesignDto
): Promise<{ formVersionId: string; processVersionId: string; savedAt: string }> {
  return apiClient.put(`${BASE_URL}/definitions/${id}/design`, data);
}

// ============================================
// 3. 版本审核与发布 API
// ============================================

/**
 * 提交审核
 */
export async function submitForReview(
  id: string,
  data?: SubmitReviewDto
): Promise<{
  snapshotId: string;
  formVersionId: string;
  processVersionId: string;
  status: SnapshotStatus;
  submittedAt: string;
}> {
  return apiClient.post(`${BASE_URL}/definitions/${id}/submit-review`, data || {});
}

/** 待审核列表项 */
export interface PendingReviewItem {
  snapshotId: string;
  formDefinitionId: string;
  formDefinitionName: string;
  formVersionId: string;
  formVersion: number;
  submittedAt: string;
  submittedBy: string; // 用户显示名称（用于UI显示）
  submittedById: string; // 用户ID（用于筛选）
  comment?: string;
}

/**
 * 获取待审核列表
 */
export async function getPendingSnapshots(params?: {
  page?: number;
  limit?: number;
  category?: string;
}): Promise<PaginatedResponse<PendingReviewItem>> {
  return apiClient.get(`${BASE_URL}/snapshots/pending`, { params });
}

/**
 * 审核快照
 */
export async function reviewSnapshot(
  snapshotId: string,
  data: ReviewDto
): Promise<{
  snapshotId: string;
  status: SnapshotStatus;
  reviewedAt: string;
  reviewedBy: string;
  reviewComment?: string;
}> {
  return apiClient.post(`${BASE_URL}/snapshots/${snapshotId}/review`, data);
}

/**
 * 发布快照
 */
export async function publishSnapshot(
  snapshotId: string,
  data?: PublishDto
): Promise<{
  snapshotId: string;
  status: SnapshotStatus;
  releaseNote?: string;
  publishedAt: string;
  publishedBy: string;
  previousSnapshotId?: string;
  formDefinitionStatus: FormDefinitionStatus;
}> {
  return apiClient.post(`${BASE_URL}/snapshots/${snapshotId}/publish`, data || {});
}

/**
 * 回滚快照
 */
export async function rollbackSnapshot(snapshotId: string): Promise<{
  previousSnapshotId: string;
  newActiveSnapshotId: string;
}> {
  return apiClient.post(`${BASE_URL}/snapshots/${snapshotId}/rollback`);
}

// ============================================
// 4. 快照与版本管理 API
// ============================================

/**
 * 获取当前激活快照
 */
export async function getActiveSnapshot(id: string): Promise<ReleaseSnapshot> {
  return apiClient.get(`${BASE_URL}/definitions/${id}/active-snapshot`);
}

/**
 * 获取快照历史
 */
export async function getSnapshotHistory(
  id: string,
  params?: { page?: number; limit?: number }
): Promise<PaginatedResponse<ReleaseSnapshot>> {
  return apiClient.get(`${BASE_URL}/definitions/${id}/snapshots`, { params });
}

/**
 * 获取快照详情
 */
export async function getSnapshot(snapshotId: string): Promise<ReleaseSnapshot> {
  return apiClient.get(`${BASE_URL}/snapshots/${snapshotId}`);
}

/**
 * 版本差异对比
 */
export async function compareVersions(
  id: string,
  from: number,
  to: number
): Promise<VersionDiff> {
  return apiClient.get(`${BASE_URL}/definitions/${id}/versions/diff`, {
    params: { from, to },
  });
}

/**
 * 快照差异对比
 */
export async function compareSnapshots(
  snapshotId1: string,
  snapshotId2: string
): Promise<VersionDiff> {
  return apiClient.get(`${BASE_URL}/snapshots/${snapshotId1}/diff/${snapshotId2}`);
}

// ============================================
// 5. 实例管理 API
// ============================================

/**
 * 创建表单实例
 */
export async function createFormInstance(data: CreateInstanceDto): Promise<{
  formInstance: FormInstance;
  processInstance: {
    id: string;
    processDefinitionId: string;
    processVersionId: string;
    status: string;
    currentNode: string;
  };
  createdAt: string;
}> {
  return apiClient.post(`${BASE_URL}/instances`, data);
}

/**
 * 获取当前节点字段权限
 */
export async function getFieldAccess(instanceId: string): Promise<{
  instanceId: string;
  currentNodeId: string;
  currentNodeName: string;
  fieldAccess: Record<string, FieldAccess>;
}> {
  return apiClient.get(`${BASE_URL}/instances/${instanceId}/field-access`);
}

// ============================================
// 6. 统计 API（扩展）
// ============================================

/**
 * 获取表单管理统计
 */
export async function getFormManagementStats(): Promise<{
  totalForms: number;
  activeFormsCount: number;
  draftFormsCount: number;
  pendingReviewCount: number;
  templatesCount: number;
}> {
  return apiClient.get(`${BASE_URL}/stats`);
}

// ============================================
// 7. 实例管理 API（扩展）
// ============================================

/**
 * 获取我的实例列表
 */
export interface QueryMyInstancesDto {
  formDefinitionId?: string;
  status?: InstanceStatus;
  page?: number;
  limit?: number;
}

export async function getMyInstances(
  params?: QueryMyInstancesDto
): Promise<PaginatedResponse<FormInstance>> {
  return apiClient.get(`${BASE_URL}/instances/my`, { params });
}

/**
 * 创建表单实例（草稿）
 * 注意：后端返回的是 CreateInstanceResponse，包含 formInstance 和 processInstance
 */
export async function createInstance(
  data: { formId: string; data: Record<string, unknown> }
): Promise<CreateInstanceResponse> {
  return apiClient.post(`${BASE_URL}/instances`, {
    formDefinitionId: data.formId,
    formData: data.data,
  });
}

/**
 * 获取实例详情
 */
export async function getInstanceDetail(id: string): Promise<FormInstance> {
  return apiClient.get(`${BASE_URL}/instances/${id}`);
}

/**
 * 更新实例（草稿）
 */
export async function updateInstance(
  id: string,
  data: { formData: Record<string, unknown> }
): Promise<FormInstance> {
  return apiClient.patch(`${BASE_URL}/instances/${id}`, data);
}

/**
 * 提交实例
 */
export async function submitInstance(
  id: string,
  data?: { comment?: string }
): Promise<FormInstance> {
  return apiClient.post(`${BASE_URL}/instances/${id}/submit`, data || {});
}

/**
 * 删除实例（软删除）
 */
export async function deleteInstance(id: string): Promise<void> {
  return apiClient.delete(`${BASE_URL}/instances/${id}`);
}

/**
 * 撤回实例响应
 */
export interface WithdrawInstanceResponse {
  id: string;
  status: 'WITHDRAWN';
  withdrawnAt: string;
  withdrawnBy: string;
  reason?: string;
  message: string;
}

/**
 * 撤回实例（用户主动撤回）
 * 只能撤回 PENDING_APPROVAL 状态的实例
 */
export async function withdrawInstance(
  id: string,
  data?: { reason?: string }
): Promise<WithdrawInstanceResponse> {
  return apiClient.post(`${BASE_URL}/instances/${id}/withdraw`, data || {});
}

// ============================================
// 审批流程预览
// ============================================

/**
 * 审批人信息
 */
export interface ApproverInfo {
  id: string;
  name: string;
  avatar?: string;
  type?: 'user' | 'role' | 'department';
}

/**
 * 带审批人的流程节点
 */
export interface ProcessNodeWithApprovers {
  id: string;
  type: string;
  name: string;
  approvers: ApproverInfo[];
  approvalMode?: string;
  config?: Record<string, any>;
}

/**
 * 预览审批流程请求
 */
export interface PreviewProcessRequest {
  formData: Record<string, any>;
  departmentId?: string;
  initiatorId?: string;  // ⭐ 发起人ID，用于计算审批人（如"发起人的上级"）
}

/**
 * 预览审批流程响应
 */
export interface PreviewProcessResponse {
  model: {
    nodes: ProcessNodeWithApprovers[];
    edges: any[];
  };
  initiator: {
    id: string;
    name: string;
    avatar?: string;
  };
}

/**
 * 预览审批流程（含实际审批人）
 * 用于在表单提交前预计算每个节点的实际审批人
 */
export async function previewProcessWithApprovers(
  formId: string,
  data: PreviewProcessRequest,
): Promise<PreviewProcessResponse> {
  return apiClient.post(
    `${BASE_URL}/definitions/${formId}/preview-process`,
    data,
  );
}
