import axiosInstance from '../utils/axios';

function toCommaString(value: unknown): string {
  if (Array.isArray(value)) {
    return value
      .map((item) => String(item).trim())
      .filter((item) => item !== '')
      .join(',');
  }
  if (value === undefined || value === null || value === '') {
    return '';
  }
  return String(value).trim();
}

function normalizeWorkflowContentCopyIds(content: string): string {
  try {
    const parsed = JSON.parse(content);
    if (parsed && Array.isArray(parsed.nodes)) {
      parsed.nodes = parsed.nodes.map((node: any) => {
        const nodeData = node?.data && typeof node.data === 'object' ? { ...node.data } : undefined;
        if (!nodeData) return node;
        if ('copyDeptIds' in nodeData) {
          nodeData.copyDeptIds = toCommaString(nodeData.copyDeptIds);
        }
        if ('copyUserIds' in nodeData) {
          nodeData.copyUserIds = toCommaString(nodeData.copyUserIds);
        }
        return {
          ...node,
          data: nodeData,
        };
      });
    }
    return JSON.stringify(parsed, null, 2);
  } catch {
    return content;
  }
}

// 流程设计 VO
export interface WorkflowDesignVO {
  id?: number;
  content: string | null; // JSON 字符串
  name?: string;
  description?: string;
  nodeCount?: number; // 节点数量
  status?: number; // 状态：1-启用，0-停用
  createTime?: number | Date; // 创建时间（时间戳或Date）
  updateTime?: number | Date; // 更新时间（时间戳或Date）
}

// 流程设计请求参数
export interface InsertWorkflowDesignParam {
  name: string; // 流程名称（必填）
  description?: string; // 描述（可选）
  content?: string; // JSON 字符串（可选，新建时可不传）
}

// 流程设计更新参数
export interface UpdateWorkflowDesignParam {
  id: number;
  content: string; // JSON 字符串
  name?: string;
  description?: string;
  smsTemplateCode?: string; // 短信模板代码
  messageTemplateCode?: string; // 消息模板代码
  emailTemplateCode?: string; // 邮件模板代码
  appTemplateCode?: string; // 应用模板代码
}

// 更新流程设计状态参数
export interface UpdateWorkflowDesignStatusParam {
  id: number;
  status: number; // 0-禁用，1-启用
}

// 分页参数类型
export interface PageParam {
  pageNo?: number;
  pageSize?: number;
  name?: string;
  [key: string]: any;
}

// 分页响应类型
export interface PageResponse<T> {
  list: T[];
  total: number;
}

// 流程设计管理 API
export const workflowDesignApi = {
  // 查询流程设计列表（分页）
  getWorkflowDesignPage: (params?: PageParam) => {
    return axiosInstance.get<PageResponse<WorkflowDesignVO>>('/iscs/workflow-design/getWorkflowDesignPage', { params });
  },
  
  // 查询流程设计详情
  selectWorkflowDesignById: (id: number) => {
    return axiosInstance.get<WorkflowDesignVO>(`/iscs/workflow-design/selectWorkflowDesignById?id=${id}`);
  },
  
  // 新增流程设计
  insertWorkflowDesign: (data: InsertWorkflowDesignParam) => {
    return axiosInstance.post<WorkflowDesignVO>('/iscs/workflow-design/insertWorkflowDesign', data);
  },
  
  // 更新流程设计
  updateWorkflowDesign: (data: UpdateWorkflowDesignParam) => {
    const payload: UpdateWorkflowDesignParam = { ...data };
    if (typeof payload.content === 'string' && payload.content.trim() !== '') {
      payload.content = normalizeWorkflowContentCopyIds(payload.content);
    }
    return axiosInstance.put<WorkflowDesignVO>('/iscs/workflow-design/updateWorkflowDesign', payload);
  },
  
  // 删除流程设计
  deleteWorkflowDesignList: (ids: any) => {
    return axiosInstance.delete(`/iscs/workflow-design/deleteWorkflowDesignList?ids=${ids}`);
  },
  
  // 更新流程设计状态
  updateWorkflowDesignStatus: (data: UpdateWorkflowDesignStatusParam) => {
    return axiosInstance.put('/iscs/workflow-design/updateWorkflowDesignStatus', data);
  },
};
